TypeScript
Share PDF and DOCX layout block cards and speed up the Blocks gallery
Andrew Luo1aaa4dd4184c
diff --git a/apps/v4/components/block-code-panel.tsx b/apps/v4/components/block-code-panel.tsxnew file mode 100644index 0000000..c685ab8--- /dev/null+++ b/apps/v4/components/block-code-panel.tsx@@ -0,0 +1,213 @@+"use client"++import * as React from "react"+import { CodeIcon } from "@hugeicons/core-free-icons"+import { HugeiconsIcon } from "@hugeicons/react"+import { prepareFileTreeInput } from "@pierre/trees"+import { FileTree as PierreFileTree, useFileTree } from "@pierre/trees/react"++import type {+ BlockCodeFile,+ LoadedBlockCodeFile,+} from "@/lib/block-code-samples"+import { CodeHeaderCopyButton } from "@/components/copy-button"+import { HighlightedCodeBlock } from "@/components/highlighted-code-block"++export type BlockCodeLoadState =+ | { status: "loading" }+ | { status: "error" }+ | { status: "loaded"; files: LoadedBlockCodeFile[] }++export function BlockCodePanel({+ codeSamples,+ loadState,+ activeFile,+ onActiveFileChange,+}: {+ codeSamples: BlockCodeFile[]+ loadState: BlockCodeLoadState+ activeFile: string | null+ onActiveFileChange: (file: string) => void+}) {+ const activeCodeSample =+ codeSamples.find((sample) => sample.targetPath === activeFile) ??+ codeSamples[0]++ if (!activeCodeSample) {+ return (+ <div className="grid h-full place-items-center rounded-xl border bg-code text-sm text-code-foreground">+ No source sample available.+ </div>+ )+ }++ const activeLoadedSample =+ loadState.status === "loaded"+ ? loadState.files.find(+ (file) => file.targetPath === activeCodeSample.targetPath+ )+ : undefined++ return (+ <div className="flex h-full overflow-hidden rounded-xl border bg-code text-code-foreground">+ <div className="hidden w-72 shrink-0 border-r bg-code md:block">+ <div className="flex h-12 items-center border-b px-4 text-sm font-medium">+ Files+ </div>+ <BlockFileTree+ codeSamples={codeSamples}+ activeFile={activeCodeSample.targetPath}+ onActiveFileChange={onActiveFileChange}+ />+ </div>+ <div className="flex min-w-0 flex-1 flex-col">+ <div className="flex h-12 items-center gap-2 border-b px-4 text-sm">+ <HugeiconsIcon icon={CodeIcon} className="size-4 opacity-70" />+ <span className="truncate">{activeCodeSample.targetPath}</span>+ {activeLoadedSample ? (+ <CodeHeaderCopyButton+ value={activeLoadedSample.content}+ className="ml-auto"+ event="copy_block_code"+ />+ ) : null}+ </div>+ {activeLoadedSample ? (+ <BlockCodeContent code={activeLoadedSample} />+ ) : loadState.status === "error" ? (+ <div className="grid min-h-0 flex-1 place-items-center text-sm text-code-foreground/70">+ Failed to load source.+ </div>+ ) : (+ <BlockCodeContentSkeleton />+ )}+ </div>+ </div>+ )+}++function BlockCodeContent({ code }: { code: LoadedBlockCodeFile }) {+ return (+ <HighlightedCodeBlock+ code={code.content}+ fileName={code.targetPath}+ language={code.language}+ lazy={false}+ renderFallbackCode+ showCopy={false}+ className="min-h-0 flex-1 rounded-none border-0"+ maxHeightClassName="h-full max-h-none"+ />+ )+}++function BlockCodeContentSkeleton() {+ return (+ <div+ aria-hidden="true"+ className="min-h-0 flex-1 animate-pulse space-y-3 overflow-hidden p-4"+ >+ {Array.from({ length: 14 }, (_, index) => (+ <div+ key={index}+ className="h-3 rounded bg-code-foreground/10"+ style={{ width: `${30 + ((index * 37) % 55)}%` }}+ />+ ))}+ </div>+ )+}++function BlockFileTree({+ codeSamples,+ activeFile,+ onActiveFileChange,+}: {+ codeSamples: BlockCodeFile[]+ activeFile: string+ onActiveFileChange: (file: string) => void+}) {+ const paths = React.useMemo(+ () => codeSamples.map((sample) => sample.targetPath),+ [codeSamples]+ )++ return (+ <PierreBlockFileTree+ key={paths.join("\0")}+ activeFile={activeFile}+ paths={paths}+ onActiveFileChange={onActiveFileChange}+ />+ )+}++function PierreBlockFileTree({+ activeFile,+ paths,+ onActiveFileChange,+}: {+ activeFile: string+ paths: string[]+ onActiveFileChange: (file: string) => void+}) {+ const filePathSet = React.useMemo(() => new Set(paths), [paths])+ const preparedInput = React.useMemo(+ () =>+ prepareFileTreeInput(paths, {+ flattenEmptyDirectories: true,+ sort: "default",+ }),+ [paths]+ )+ const { model } = useFileTree({+ flattenEmptyDirectories: true,+ initialExpansion: "open",+ initialSelectedPaths: activeFile ? [activeFile] : [],+ itemHeight: 28,+ overscan: 12,+ preparedInput,+ unsafeCSS: `+ button[data-type='item'][data-item-selected] {+ background: var(--color-primary);+ color: var(--color-primary-foreground);+ }+ button[data-type='item'][data-item-selected] *,+ button[data-type='item'][data-item-selected] svg {+ color: var(--color-primary-foreground) !important;+ }+ `,+ onSelectionChange: (selectedPaths) => {+ const nextPath = selectedPaths.find((path) => filePathSet.has(path))+ if (nextPath) {+ onActiveFileChange(nextPath)+ }+ },+ })++ React.useEffect(() => {+ if (!activeFile) return++ const item = model.getItem(activeFile)+ if (!item) return++ item.select()+ model.scrollToPath(activeFile, { focus: false, offset: "nearest" })+ }, [activeFile, model])++ return (+ <PierreFileTree+ model={model}+ className="block h-[calc(680px-3rem)]"+ style={+ {+ "--trees-bg-override": "var(--color-code)",+ "--trees-border-color-override": "var(--color-border)",+ "--trees-fg-override":+ "color-mix(in oklab, var(--color-code-foreground) 78%, transparent)",+ "--trees-selected-bg-override": "var(--color-primary)",+ } as React.CSSProperties+ }+ />+ )+}diff --git a/apps/v4/components/block-previews.tsx b/apps/v4/components/block-previews.tsxnew file mode 100644index 0000000..f908961--- /dev/null+++ b/apps/v4/components/block-previews.tsx@@ -0,0 +1,120 @@+"use client"++import type * as React from "react"+import dynamic from "next/dynamic"++import type { PdfViewerBlockId } from "@/lib/pdf-viewer-blocks"+import { withUiBasePath } from "@/lib/zone-path"++export function BlockPreviewPlaceholder() {+ return <div className="h-full min-h-[560px] bg-muted/20" />+}++type BlockPreviewProps = {+ file?: string+ defaultViewerZoom?: number+ heightClassName?: string+}++const HumanReviewBlock = dynamic<+ BlockPreviewProps & { showExpected?: boolean }+>(+ () =>+ import("@/components/bounding-box-citations-docs").then(+ (mod) => mod.HumanReviewBlock+ ),+ { loading: BlockPreviewPlaceholder }+)++const PdfDropzoneBlock = dynamic<BlockPreviewProps>(+ () =>+ import("@/components/pdf-dropzone-block").then(+ (mod) => mod.PdfDropzoneBlock+ ),+ { loading: BlockPreviewPlaceholder }+)++const OcrBlocksBlock = dynamic<BlockPreviewProps>(+ () =>+ import("@/components/layout-blocks-docs").then((mod) => mod.OcrBlocksBlock),+ { loading: BlockPreviewPlaceholder }+)++const ESignatureBlock = dynamic<BlockPreviewProps>(+ () =>+ import("@/components/e-signature-docs").then((mod) => mod.ESignatureBlock),+ { loading: BlockPreviewPlaceholder }+)++const DocumentSplitsBlock = dynamic<BlockPreviewProps>(+ () =>+ import("@/components/document-splitter-docs").then(+ (mod) => mod.DocumentSplitsBlock+ ),+ { loading: BlockPreviewPlaceholder }+)++const XlsxEditorBlock = dynamic<BlockPreviewProps>(+ () =>+ import("@/registry/new-york-v4/blocks/excel-editor").then(+ (mod) => mod.ExcelEditorBlock+ ),+ { ssr: false, loading: BlockPreviewPlaceholder }+)++const PdfEditorBlock = dynamic<BlockPreviewProps>(+ () =>+ import("@/components/pdf-editor-preview-client").then(+ (mod) => mod.PdfEditorPreviewClient+ ),+ { ssr: false, loading: BlockPreviewPlaceholder }+)++const DocxLayoutBlocks = dynamic<BlockPreviewProps>(+ () =>+ import("@/registry/new-york-v4/blocks/docx-layout-blocks").then(+ (mod) => mod.DocxLayoutBlocks+ ),+ { ssr: false, loading: BlockPreviewPlaceholder }+)++const DocxEditorBlock = dynamic<BlockPreviewProps>(+ () =>+ import("@/components/docx-editor-docs").then((mod) => mod.DocxEditorBlock),+ { loading: BlockPreviewPlaceholder }+)++const FileSystemFinderBlock = dynamic<BlockPreviewProps>(+ () =>+ import("@/components/file-system-docs").then(+ (mod) => mod.FileSystemFinderBlock+ ),+ { loading: BlockPreviewPlaceholder }+)++export const blockPreviews: Record<+ PdfViewerBlockId,+ React.ComponentType<BlockPreviewProps>+> = {+ "bounding-box-citations": (props) => (+ <HumanReviewBlock {...props} showExpected={false} />+ ),+ "pdf-dropzone": PdfDropzoneBlock,+ "layout-blocks": OcrBlocksBlock,+ "e-signature": ESignatureBlock,+ "document-splits": DocumentSplitsBlock,+ "excel-editor": ({ heightClassName = "h-[680px]" }) => (+ <XlsxEditorBlock+ file={withUiBasePath("/samples/crazy-chart-zoo.xlsx")}+ heightClassName={heightClassName}+ />+ ),+ "docx-layout-blocks": () => (+ <DocxLayoutBlocks file={withUiBasePath("/samples/demo.docx")} />+ ),+ "docx-editor-block": DocxEditorBlock,+ "pdf-editor-block": ({ heightClassName = "h-full" }) => (+ <PdfEditorBlock heightClassName={heightClassName} />+ ),+ "file-system": FileSystemFinderBlock,+}diff --git a/apps/v4/components/bounding-box-citations-docs.tsx b/apps/v4/components/bounding-box-citations-docs.tsxindex af5382a..1c4ab9d 100644--- a/apps/v4/components/bounding-box-citations-docs.tsx+++ b/apps/v4/components/bounding-box-citations-docs.tsx@@ -271,6 +271,7 @@ const CODE_HIGHLIGHTER_OPTIONS = {} satisfies WorkerInitializationRenderOptionsconst CODE_WORKER_POOL_OPTIONS = {+ poolSize: 2,workerFactory: () =>new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), {type: "module",@@ -2721,7 +2722,7 @@ function HumanReviewPanel({</div></ScrollArea></TabsContent>- <TabsContent value="json" keepMounted className="min-h-0 flex-1">+ <TabsContent value="json" className="min-h-0 flex-1">{showExpected ? (<JsonDiffViewactual={actualValues}@@ -3028,7 +3029,7 @@ export function HumanReviewExample() {}`const humanReviewSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n DataEditor,\n emptyGridSelection,\n GridCellKind,\n TextCellEntry,\n type EditableGridCell,\n type GridCell,\n type GridColumn,\n type GridMouseEventArgs,\n type GridSelection,\n type Item,\n type NumberCell,\n type ProvideEditorComponent,\n type Rectangle,\n type TextCell,\n type Theme,\n} from "@glideapps/glide-data-grid"\nimport { Virtualizer as DiffsVirtualizer } from "@pierre/diffs"\nimport {\n File,\n MultiFileDiff,\n VirtualizerContext,\n WorkerPoolContextProvider,\n type VirtualFileMetrics,\n type WorkerInitializationRenderOptions,\n type WorkerPoolOptions,\n} from "@pierre/diffs/react"\nimport { flushSync } from "react-dom"\n\nimport type { RegistryIconProps } from "@/lib/registry-icon-props"\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport { Input } from "@/components/ui/input"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nimport "@glideapps/glide-data-grid/dist/index.css"\n\nfunction InputNumericGlyph(props: RegistryIconProps) {\n return (\n <IconPlaceholder\n lucide="Hash"\n tabler="IconNumber123"\n hugeicons="InputNumericIcon"\n phosphor="NumpadIcon"\n remixicon="RiHashtag"\n {...props}\n />\n )\n}\n\nfunction InputTextGlyph(props: RegistryIconProps) {\n return (\n <IconPlaceholder\n lucide="TextCursorInput"\n tabler="IconForms"\n hugeicons="InputTextIcon"\n phosphor="TextboxIcon"\n remixicon="RiInputField"\n {...props}\n />\n )\n}\n\nfunction SecondBracketGlyph(props: RegistryIconProps) {\n return (\n <IconPlaceholder\n lucide="Brackets"\n tabler="IconBrackets"\n hugeicons="SecondBracketIcon"\n phosphor="BracketsSquareIcon"\n remixicon="RiBracketsLine"\n {...props}\n />\n )\n}\n\nfunction SourceCodeSquareGlyph(props: RegistryIconProps) {\n return (\n <IconPlaceholder\n lucide="SquareCode"\n tabler="IconSourceCode"\n hugeicons="SourceCodeSquareIcon"\n phosphor="CodeIcon"\n remixicon="RiCodeBlock"\n {...props}\n />\n )\n}\n\nfunction TextCheckGlyph(props: RegistryIconProps) {\n return (\n <IconPlaceholder\n lucide="CaptionsIcon"\n tabler="IconTextCaption"\n hugeicons="TextCheckIcon"\n phosphor="TextTIcon"\n remixicon="RiTextWrap"\n {...props}\n />\n )\n}\n\nexport type JsonPrimitive = string | number | boolean | null\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray\nexport type JsonObject = { [key: string]: JsonValue }\nexport type JsonArray = JsonValue[]\nexport type SchemaPropertyType =\n | "string"\n | "number"\n | "integer"\n | "boolean"\n | "object"\n | "array"\n\nexport type ReviewFieldSchema = {\n type: SchemaPropertyType\n title?: string\n description?: string\n enum?: Array<string | number>\n properties?: Record<string, ReviewFieldSchema>\n items?: ReviewFieldSchema\n}\n\nexport type HighlightArea = {\n left: number\n top: number\n width: number\n height: number\n}\n\nexport type ReviewField = {\n key: string\n schema: ReviewFieldSchema\n actual: JsonValue\n expected: JsonValue\n location?: ReviewLocation\n metadataPath?: string\n}\n\nexport type ReviewLocation = {\n page: number\n area: HighlightArea\n}\n\nexport type ReviewCitation = {\n page: number\n polygon?: Array<{ x: number; y: number }>\n pageWidth: number\n pageHeight: number\n}\n\nexport type ReviewMetadataEntry = {\n citations?: ReviewCitation[]\n}\n\nfunction ScrollAreaVirtualizer({\n children,\n className,\n contentClassName,\n contentStyle,\n scrollFade = true,\n}: {\n children: React.ReactNode\n className?: string\n contentClassName?: string\n contentStyle?: React.CSSProperties\n scrollFade?: boolean\n}) {\n const [virtualizer] = React.useState(() =>\n typeof window !== "undefined" ? new DiffsVirtualizer() : undefined\n )\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const contentRef = React.useRef<HTMLDivElement | null>(null)\n const syncVirtualizer = React.useCallback(() => {\n if (!virtualizer) return\n\n const viewport = viewportRef.current\n const content = contentRef.current\n\n if (viewport && content) {\n virtualizer.setup(viewport, content)\n return\n }\n\n virtualizer.cleanUp()\n }, [virtualizer])\n const setViewportRef = React.useCallback(\n (node: HTMLDivElement | null) => {\n viewportRef.current = node\n syncVirtualizer()\n },\n [syncVirtualizer]\n )\n const setContentRef = React.useCallback(\n (node: HTMLDivElement | null) => {\n contentRef.current = node\n syncVirtualizer()\n },\n [syncVirtualizer]\n )\n\n React.useEffect(() => {\n return () => virtualizer?.cleanUp()\n }, [virtualizer])\n\n return (\n <VirtualizerContext.Provider value={virtualizer}>\n <ScrollArea\n className={className}\n scrollFade={scrollFade}\n scrollbarOverflowOnly\n viewportRef={setViewportRef}\n >\n <div\n ref={setContentRef}\n className={contentClassName}\n style={contentStyle}\n >\n {children}\n </div>\n </ScrollArea>\n </VirtualizerContext.Provider>\n )\n}\n\nconst REVIEW_HIGHLIGHT_STYLE =\n "border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_10%)]"\n\nconst CODE_FILE_THEME = {\n "--diffs-light-bg": "var(--color-code)",\n "--diffs-dark-bg": "var(--color-code)",\n "--diffs-light": "var(--color-code-foreground)",\n "--diffs-dark": "var(--color-code-foreground)",\n "--diffs-bg-context-override": "var(--color-code)",\n "--diffs-bg-context-gutter-override": "var(--color-code)",\n "--diffs-bg-buffer-override": "var(--color-code)",\n "--diffs-fg-number-override": "var(--color-muted-foreground)",\n "--diffs-font-size": "0.8rem",\n "--diffs-line-height": "1.625",\n} as React.CSSProperties\n\nconst CODE_FONT_SIZE_PX = 12.8\nconst CODE_LINE_HEIGHT_PX = CODE_FONT_SIZE_PX * 1.625\n\nconst CODE_VIRTUAL_FILE_METRICS = {\n hunkLineCount: 50,\n lineHeight: CODE_LINE_HEIGHT_PX,\n diffHeaderHeight: 44,\n spacing: 8,\n paddingTop: 0,\n paddingBottom: 8,\n} satisfies VirtualFileMetrics\n\nconst CODE_HIGHLIGHTER_OPTIONS = {\n theme: {\n light: "pierre-light-soft",\n dark: "pierre-dark-soft",\n },\n langs: ["json"],\n} satisfies WorkerInitializationRenderOptions\n\nconst CODE_WORKER_POOL_OPTIONS = {\n workerFactory: () =>\n new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), {\n type: "module",\n }),\n} satisfies WorkerPoolOptions\n\nfunction readIsDarkTheme() {\n return (\n typeof document !== "undefined" &&\n document.documentElement.classList.contains("dark")\n )\n}\n\n// A single shared MutationObserver backs every consumer. Each grid previously\n// created its own observer (two, via useHumanReviewGridTheme), so opening a\n// nested array view spun up and tore down several observers at once.\nconst darkThemeListeners = new Set<(isDark: boolean) => void>()\nlet darkThemeObserver: MutationObserver | null = null\nlet sharedIsDarkTheme = false\n\nfunction ensureDarkThemeObserver() {\n if (\n darkThemeObserver ||\n typeof document === "undefined" ||\n typeof MutationObserver === "undefined"\n ) {\n return\n }\n\n sharedIsDarkTheme = readIsDarkTheme()\n darkThemeObserver = new MutationObserver(() => {\n const nextIsDark = readIsDarkTheme()\n if (nextIsDark === sharedIsDarkTheme) return\n\n sharedIsDarkTheme = nextIsDark\n darkThemeListeners.forEach((listener) => listener(nextIsDark))\n })\n darkThemeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ["class"],\n })\n}\n\nfunction subscribeToDarkTheme(listener: () => void) {\n ensureDarkThemeObserver()\n darkThemeListeners.add(listener)\n return () => {\n darkThemeListeners.delete(listener)\n if (darkThemeListeners.size === 0 && darkThemeObserver) {\n darkThemeObserver.disconnect()\n darkThemeObserver = null\n }\n }\n}\n\nfunction useIsDarkTheme() {\n return React.useSyncExternalStore(\n subscribeToDarkTheme,\n readIsDarkTheme,\n () => false\n )\n}\n\nfunction useHumanReviewGridTheme() {\n const isDark = useIsDarkTheme()\n\n return React.useMemo<Partial<Theme>>(\n () => ({\n accentColor: isDark ? "rgb(96, 165, 250)" : "rgb(37, 99, 235)",\n accentLight: isDark ? "rgba(29, 78, 216, 0.15)" : "rgb(219, 234, 254)",\n accentFg: "rgb(255, 255, 255)",\n textDark: isDark ? "rgb(229, 229, 229)" : "rgb(23, 23, 23)",\n textMedium: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n textLight: isDark ? "rgb(115, 115, 115)" : "rgb(163, 163, 163)",\n textBubble: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n textHeader: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n textGroupHeader: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n bgCell: isDark ? "rgb(10, 10, 10)" : "rgb(255, 255, 255)",\n bgCellMedium: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n bgHeader: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n bgHeaderHasFocus: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n bgHeaderHovered: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n borderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n horizontalBorderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n cellHorizontalPadding: 8,\n cellVerticalPadding: 3,\n headerIconSize: 18,\n baseFontStyle: "13px",\n headerFontStyle: "600 13px",\n markerFontStyle: "11px",\n fontFamily: \'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif\',\n editorFontSize: "13px",\n }),\n [isDark]\n )\n}\n\nexport const REVIEW_FIELDS: ReviewField[] = [\n {\n key: "statement_period",\n schema: {\n type: "string",\n title: "Statement period",\n description: "Date range covered by the bank statement.",\n },\n actual: "Jan 1-31, 2026",\n expected: "January 1-31, 2026",\n location: {\n page: 1,\n area: { left: 31, top: 30, width: 40, height: 5.8 },\n },\n },\n {\n key: "transactions",\n schema: {\n type: "array",\n title: "Transactions",\n description: "Posted account activity during the statement period.",\n items: {\n type: "object",\n properties: {\n date: {\n type: "string",\n title: "Date",\n },\n description: {\n type: "string",\n title: "Description",\n },\n amount: {\n type: "number",\n title: "Amount",\n },\n category: {\n type: "string",\n title: "Category",\n },\n merchant: {\n type: "object",\n title: "Merchant",\n properties: {\n name: {\n type: "string",\n title: "Name",\n },\n city: {\n type: "string",\n title: "City",\n },\n risk_level: {\n type: "string",\n title: "Risk level",\n },\n },\n },\n tags: {\n type: "array",\n title: "Tags",\n items: {\n type: "string",\n title: "Tag",\n },\n },\n },\n },\n },\n actual: [\n {\n date: "2026-01-03",\n description: "ACH CREDIT PAYROLL",\n amount: 4250,\n category: "Deposit",\n merchant: {\n name: "Acme Payroll",\n city: "New York",\n risk_level: "low",\n },\n tags: ["payroll", "recurring"],\n },\n {\n date: "2026-01-12",\n description: "POS PURCHASE GROCERY MART",\n amount: -86.42,\n category: "Debit",\n merchant: {\n name: "Grocery Mart",\n city: "Brooklyn",\n risk_level: "medium",\n },\n tags: ["card", "groceries"],\n },\n ],\n expected: [\n {\n date: "2026-01-03",\n description: "ACH CREDIT PAYROLL",\n amount: 4250,\n category: "Deposit",\n merchant: {\n name: "Acme Payroll",\n city: "New York",\n risk_level: "low",\n },\n tags: ["payroll", "recurring"],\n },\n {\n date: "2026-01-12",\n description: "POS PURCHASE GROCERY MART",\n amount: -68.42,\n category: "Debit",\n merchant: {\n name: "Grocery Mart",\n city: "Brooklyn",\n risk_level: "low",\n },\n tags: ["card", "groceries", "needs_review"],\n },\n ],\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "ending_balance",\n schema: {\n type: "number",\n title: "Ending balance",\n description: "Final account balance at the end of the statement period.",\n },\n actual: 12840.18,\n expected: 12858.18,\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "overdraft_protection_enabled",\n schema: {\n type: "boolean",\n title: "Overdraft protection enabled",\n description: "Whether overdraft protection is enabled for the account.",\n },\n actual: false,\n expected: true,\n location: {\n page: 2,\n area: { left: 9.5, top: 12, width: 81, height: 11.5 },\n },\n },\n {\n key: "account_details",\n schema: {\n type: "object",\n title: "Account details",\n description: "Account owner and identifying details from the statement.",\n properties: {\n holder_name: {\n type: "string",\n title: "Holder name",\n },\n account_last_four: {\n type: "string",\n title: "Account last four",\n },\n account_type: {\n type: "string",\n title: "Account type",\n },\n mailing_address: {\n type: "object",\n title: "Mailing address",\n properties: {\n line_1: {\n type: "string",\n title: "Line 1",\n },\n city: {\n type: "string",\n title: "City",\n },\n state: {\n type: "string",\n title: "State",\n },\n },\n },\n linked_accounts: {\n type: "array",\n title: "Linked accounts",\n items: {\n type: "object",\n properties: {\n nickname: {\n type: "string",\n title: "Nickname",\n },\n last_four: {\n type: "string",\n title: "Last four",\n },\n },\n },\n },\n },\n },\n actual: {\n holder_name: "Jordan Lee",\n account_last_four: "4821",\n account_type: "Checking",\n mailing_address: {\n line_1: "42 Market Street",\n city: "Brooklyn",\n state: "NY",\n },\n linked_accounts: [\n {\n nickname: "Operations reserve",\n last_four: "1842",\n },\n ],\n },\n expected: {\n holder_name: "Jordan Lee",\n account_last_four: "4821",\n account_type: "Premier Checking",\n mailing_address: {\n line_1: "42 Market Street",\n city: "New York",\n state: "NY",\n },\n linked_accounts: [\n {\n nickname: "Operations reserve",\n last_four: "1842",\n },\n {\n nickname: "Payroll sweep",\n last_four: "9174",\n },\n ],\n },\n },\n]\n\nfunction getCitationLocation(\n citation: ReviewCitation\n): ReviewLocation | undefined {\n const polygon = citation.polygon\n if (!polygon?.length || !citation.pageWidth || !citation.pageHeight) {\n return undefined\n }\n\n const xs = polygon.map((point) => point.x)\n const ys = polygon.map((point) => point.y)\n const left = Math.min(...xs)\n const top = Math.min(...ys)\n const right = Math.max(...xs)\n const bottom = Math.max(...ys)\n\n return {\n page: citation.page,\n area: {\n left: (left / citation.pageWidth) * 100,\n top: (top / citation.pageHeight) * 100,\n width: ((right - left) / citation.pageWidth) * 100,\n height: ((bottom - top) / citation.pageHeight) * 100,\n },\n }\n}\n\nexport function getMetadataLocation(\n metadata: Record<string, ReviewMetadataEntry> | undefined,\n metadataPath: string | undefined\n) {\n if (!metadata || !metadataPath) return undefined\n\n const citation = metadata[metadataPath]?.citations?.find(\n (candidate) => candidate.polygon?.length\n )\n\n return citation ? getCitationLocation(citation) : undefined\n}\n\nexport function getReviewFieldLocation(\n field: ReviewField | undefined,\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n) {\n if (!field) return undefined\n\n return (\n field.location ??\n resolveLocation?.(field.metadataPath ?? field.key) ??\n undefined\n )\n}\n\nexport function getReviewLocationKey(location: ReviewLocation | undefined) {\n if (!location) return null\n\n const { area } = location\n return [location.page, area.left, area.top, area.width, area.height].join(":")\n}\n\nfunction valuesFromFields(\n fields: ReviewField[],\n valueKey: "actual" | "expected"\n) {\n return fields.reduce<JsonObject>((values, field) => {\n values[field.key] = field[valueKey]\n return values\n }, {})\n}\n\nfunction formatJson(value: unknown) {\n return JSON.stringify(value, null, 2)\n}\n\nfunction isJsonObject(value: JsonValue): value is JsonObject {\n return typeof value === "object" && value !== null && !Array.isArray(value)\n}\n\nfunction isJsonArray(value: JsonValue): value is JsonArray {\n return Array.isArray(value)\n}\n\nfunction getObjectValue(value: JsonValue, key: string): JsonValue {\n if (!isJsonObject(value)) return null\n return value[key] ?? null\n}\n\nfunction setObjectValue(\n value: JsonValue,\n key: string,\n childValue: JsonValue\n): JsonObject {\n return {\n ...(isJsonObject(value) ? value : {}),\n [key]: childValue,\n }\n}\n\nfunction getArrayValue(value: JsonValue): JsonArray {\n return isJsonArray(value) ? value : []\n}\n\nfunction setArrayItemValue(\n value: JsonValue,\n index: number,\n childValue: JsonValue\n): JsonArray {\n const nextValue = getArrayValue(value).slice()\n nextValue[index] = childValue\n return nextValue\n}\n\nfunction getPrimitiveValue(value: JsonValue): JsonPrimitive {\n return isJsonObject(value) || isJsonArray(value) ? null : value\n}\n\nfunction jsonValuesEqual(left: JsonValue, right: JsonValue) {\n return formatJson(left) === formatJson(right)\n}\n\nexport function findReviewField(\n fields: ReviewField[],\n fieldKey: string | undefined\n): ReviewField | undefined {\n if (!fieldKey) return undefined\n\n for (const field of fields) {\n if (field.key === fieldKey) return field\n\n if (field.schema.type === "object") {\n const childFields = Object.entries(field.schema.properties ?? {}).map(\n ([key, schema]): ReviewField => ({\n key: `${field.key}.${key}`,\n schema,\n actual: getObjectValue(field.actual, key),\n expected: getObjectValue(field.expected, key),\n metadataPath: `${field.metadataPath ?? field.key}.${key}`,\n })\n )\n const childField = findReviewField(childFields, fieldKey)\n if (childField) return childField\n }\n }\n\n return undefined\n}\n\nfunction formatValue(value: JsonValue) {\n if (value === null) return "NULL"\n if (isJsonObject(value) || isJsonArray(value)) return formatJson(value)\n if (typeof value === "boolean") return value ? "true" : "false"\n return String(value)\n}\n\nfunction areGridRangesEqual(\n left: Readonly<Rectangle> | undefined,\n right: Readonly<Rectangle> | undefined\n) {\n return (\n left === right ||\n (left !== undefined &&\n right !== undefined &&\n left.x === right.x &&\n left.y === right.y &&\n left.width === right.width &&\n left.height === right.height)\n )\n}\n\nfunction areGridRangeStacksEqual(\n left: readonly Readonly<Rectangle>[] | undefined,\n right: readonly Readonly<Rectangle>[] | undefined\n) {\n if (left === right) return true\n if (!left || !right || left.length !== right.length) return false\n\n return left.every((range, index) => areGridRangesEqual(range, right[index]))\n}\n\nfunction areGridSelectionsEqual(left: GridSelection, right: GridSelection) {\n const leftCurrent = left.current\n const rightCurrent = right.current\n\n return (\n leftCurrent?.cell[0] === rightCurrent?.cell[0] &&\n leftCurrent?.cell[1] === rightCurrent?.cell[1] &&\n areGridRangesEqual(leftCurrent?.range, rightCurrent?.range) &&\n areGridRangeStacksEqual(\n leftCurrent?.rangeStack,\n rightCurrent?.rangeStack\n ) &&\n left.columns.equals(right.columns) &&\n left.rows.equals(right.rows)\n )\n}\n\nfunction getGridSelectionRanges(selection: GridSelection | undefined) {\n const current = selection?.current\n if (!current) return []\n\n return [...(current.rangeStack ?? []), current.range]\n}\n\nfunction areArrayNestedViewsEqual(\n left: ArrayNestedView[],\n right: ArrayNestedView[]\n) {\n if (left === right) return true\n if (left.length !== right.length) return false\n\n return left.every((view, index) => {\n const other = right[index]\n\n return (\n view.rowIndex === other?.rowIndex &&\n view.columnId === other.columnId &&\n view.title === other.title &&\n view.schema === other.schema &&\n Object.is(view.value, other.value)\n )\n })\n}\n\ntype HumanReviewOverlayCell = TextCell | NumberCell\n\ntype HumanReviewTextOverlayEditorProps = React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n> & {\n overlayOpenRef: React.RefObject<boolean>\n readOnly?: boolean\n}\n\nfunction HumanReviewTextOverlayEditor({\n isHighlighted,\n onFinishedEditing,\n overlayOpenRef,\n readOnly = false,\n validatedSelection,\n value,\n}: HumanReviewTextOverlayEditorProps) {\n const initialValue =\n value.kind === GridCellKind.Number ? value.displayData : value.data\n const [entryValue, setEntryValue] = React.useState(initialValue)\n const latestValueRef = React.useRef(initialValue)\n const finishedRef = React.useRef(false)\n\n const finishEditing = React.useCallback(\n (\n shouldSave: boolean,\n movement: readonly [-1 | 0 | 1, -1 | 0 | 1] = [0, 0]\n ) => {\n if (finishedRef.current) return\n\n finishedRef.current = true\n overlayOpenRef.current = false\n\n if (!shouldSave || readOnly) {\n onFinishedEditing(undefined, movement)\n return\n }\n\n if (value.kind === GridCellKind.Number) {\n const numericValue = Number(latestValueRef.current)\n\n onFinishedEditing(\n {\n ...value,\n data: Number.isFinite(numericValue) ? numericValue : value.data,\n displayData: latestValueRef.current,\n },\n movement\n )\n return\n }\n\n onFinishedEditing(\n {\n ...value,\n data: latestValueRef.current,\n displayData: latestValueRef.current,\n },\n movement\n )\n },\n [onFinishedEditing, overlayOpenRef, readOnly, value]\n )\n\n const handleEntryChange = React.useCallback(\n (event: React.ChangeEvent<HTMLTextAreaElement>) => {\n event.stopPropagation()\n latestValueRef.current = event.target.value\n setEntryValue(event.target.value)\n },\n []\n )\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n event.stopPropagation()\n\n if (event.key === "Escape") {\n event.preventDefault()\n finishEditing(false)\n return\n }\n\n if (event.key === "Tab") {\n event.preventDefault()\n finishEditing(true, [event.shiftKey ? -1 : 1, 0])\n return\n }\n\n if (event.key === "Enter" && !event.shiftKey) {\n event.preventDefault()\n finishEditing(true, [0, 1])\n }\n },\n [finishEditing]\n )\n\n React.useEffect(() => {\n overlayOpenRef.current = true\n\n return () => {\n overlayOpenRef.current = false\n }\n }, [overlayOpenRef])\n\n React.useEffect(() => {\n const handlePointerOutside = (event: PointerEvent | MouseEvent) => {\n const input = document.querySelector<HTMLTextAreaElement>(".gdg-input")\n const overlayRoot = input?.closest(".gdg-clip-region")\n\n if (!overlayRoot || overlayRoot.contains(event.target as Node | null)) {\n return\n }\n\n finishEditing(true)\n }\n\n document.addEventListener("pointerdown", handlePointerOutside, true)\n document.addEventListener("contextmenu", handlePointerOutside, true)\n\n return () => {\n document.removeEventListener("pointerdown", handlePointerOutside, true)\n document.removeEventListener("contextmenu", handlePointerOutside, true)\n }\n }, [finishEditing])\n\n return (\n <TextCellEntry\n autoFocus={!readOnly}\n disabled={readOnly}\n highlight={isHighlighted}\n value={entryValue}\n validatedSelection={validatedSelection}\n altNewline\n onChange={handleEntryChange}\n onKeyDown={handleKeyDown}\n />\n )\n}\n\nfunction getFieldIcon(type: SchemaPropertyType) {\n if (type === "number" || type === "integer") return InputNumericGlyph\n if (type === "boolean") return TextCheckGlyph\n if (type === "array") return SecondBracketGlyph\n if (type === "object") return SourceCodeSquareGlyph\n return InputTextGlyph\n}\n\nfunction HumanReviewValueInput({\n readOnly = false,\n schema,\n value,\n onChange,\n}: {\n readOnly?: boolean\n schema: ReviewFieldSchema\n value: JsonPrimitive\n onChange: (value: JsonPrimitive) => void\n}) {\n if (schema.enum?.length) {\n return (\n <span className="relative inline-flex w-full rounded-lg border border-input bg-background text-sm text-foreground shadow-xs/5 dark:bg-input/32">\n <select\n disabled={readOnly}\n value={value === null ? "" : String(value)}\n onChange={(event) => onChange(event.target.value)}\n className="h-8.5 w-full appearance-none rounded-[inherit] bg-transparent px-3 text-sm outline-none sm:h-7.5"\n >\n {schema.enum.map((option) => (\n <option key={String(option)} value={String(option)}>\n {String(option)}\n </option>\n ))}\n </select>\n </span>\n )\n }\n\n if (schema.type === "number" || schema.type === "integer") {\n return (\n <Input\n nativeInput\n readOnly={readOnly}\n type="number"\n value={value === null ? "" : String(value)}\n onChange={(event) => {\n const nextValue = event.currentTarget.value\n onChange(nextValue === "" ? null : Number(nextValue))\n }}\n />\n )\n }\n\n if (schema.type === "boolean") {\n return (\n <div className="grid grid-cols-2 gap-1 rounded-lg bg-muted p-0.5">\n {[true, false].map((option) => (\n <Button\n key={String(option)}\n type="button"\n size="sm"\n variant={value === option ? "outline" : "ghost"}\n className={cn(\n "h-7 shadow-none",\n value === option && "bg-background dark:bg-input"\n )}\n disabled={readOnly}\n onClick={() => onChange(option)}\n >\n {option ? "True" : "False"}\n </Button>\n ))}\n </div>\n )\n }\n\n return (\n <Input\n nativeInput\n readOnly={readOnly}\n value={value === null ? "" : String(value)}\n onChange={(event) => onChange(event.currentTarget.value)}\n />\n )\n}\n\nfunction getArrayItemSchema(schema: ReviewFieldSchema): ReviewFieldSchema {\n return schema.items ?? { type: "string" }\n}\n\nfunction isComplexSchema(schema: ReviewFieldSchema) {\n return schema.type === "object" || schema.type === "array"\n}\n\nfunction summarizeComplexValue(value: JsonValue) {\n if (isJsonArray(value)) return `${value.length} items`\n if (isJsonObject(value)) return `${Object.keys(value).length} fields`\n return formatValue(value)\n}\n\nfunction getCellValueForArrayColumn(\n rowValue: JsonValue,\n itemSchema: ReviewFieldSchema,\n columnId: string\n) {\n if (itemSchema.type === "object") {\n return getObjectValue(rowValue, columnId)\n }\n\n return rowValue\n}\n\nfunction getCellSchemaForArrayColumn(\n itemSchema: ReviewFieldSchema,\n columnId: string\n) {\n if (itemSchema.type === "object") {\n return itemSchema.properties?.[columnId] ?? { type: "string" }\n }\n\n return itemSchema\n}\n\nfunction applyPrimitiveEdit(\n schema: ReviewFieldSchema,\n value: EditableGridCell\n): JsonValue | undefined {\n if (schema.type === "boolean" && value.kind === GridCellKind.Boolean) {\n return value.data\n }\n\n if (\n (schema.type === "number" || schema.type === "integer") &&\n value.kind === GridCellKind.Number\n ) {\n return value.data ?? null\n }\n\n if (value.kind === GridCellKind.Text) {\n if (schema.type === "number" || schema.type === "integer") {\n return value.data.trim() === "" ? null : Number(value.data)\n }\n\n return value.data\n }\n\n return undefined\n}\n\ntype ArrayNestedView = {\n rowIndex: number\n columnId: string\n title: string\n schema: ReviewFieldSchema\n value: JsonValue\n}\n\ntype ArrayReviewSide = "actual" | "expected"\n\ntype SyncedArrayNestedView = {\n activeSide: ArrayReviewSide | null\n stack: ArrayNestedView[]\n}\n\ntype SyncedArraySelection = {\n activeSide: ArrayReviewSide | null\n depth: number\n gridSelection: GridSelection\n}\n\nexport type HumanReviewTheme = "light" | "dark"\n\nconst EMPTY_SYNCED_ARRAY_NESTED_VIEW: SyncedArrayNestedView = {\n activeSide: null,\n stack: [],\n}\n\nconst EMPTY_SYNCED_ARRAY_SELECTION: SyncedArraySelection = {\n activeSide: null,\n depth: 0,\n gridSelection: emptyGridSelection,\n}\n\nfunction setNestedArrayValue({\n value,\n schema,\n nestedStack,\n nextNestedValue,\n}: {\n value: JsonValue\n schema: ReviewFieldSchema\n nestedStack: ArrayNestedView[]\n nextNestedValue: JsonValue\n}): JsonValue {\n const [currentView, ...remainingViews] = nestedStack\n\n if (!currentView) return nextNestedValue\n\n const itemSchema = getArrayItemSchema(schema)\n const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n const cellSchema = getCellSchemaForArrayColumn(\n itemSchema,\n currentView.columnId\n )\n const currentCellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n currentView.columnId\n )\n const nextCellValue: JsonValue = remainingViews.length\n ? setNestedArrayValue({\n value: currentCellValue,\n schema: cellSchema,\n nestedStack: remainingViews,\n nextNestedValue,\n })\n : nextNestedValue\n const nextRowValue: JsonValue =\n itemSchema.type === "object"\n ? setObjectValue(rowValue, currentView.columnId, nextCellValue)\n : nextCellValue\n\n return setArrayItemValue(value, currentView.rowIndex, nextRowValue)\n}\n\nfunction getNestedArrayValue({\n value,\n schema,\n nestedStack,\n}: {\n value: JsonValue\n schema: ReviewFieldSchema\n nestedStack: ArrayNestedView[]\n}): JsonValue {\n const [currentView, ...remainingViews] = nestedStack\n\n if (!currentView) return value\n\n const itemSchema = getArrayItemSchema(schema)\n const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n const cellSchema = getCellSchemaForArrayColumn(\n itemSchema,\n currentView.columnId\n )\n const cellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n currentView.columnId\n )\n\n if (!remainingViews.length) return cellValue\n\n return getNestedArrayValue({\n value: cellValue,\n schema: cellSchema,\n nestedStack: remainingViews,\n })\n}\n\nfunction HumanReviewArrayValueGrid({\n activeNestedSide = null,\n activeSelectionSide = null,\n label,\n nestedStackBaseDepth = 0,\n readOnly = false,\n schema,\n selectionDepth = 0,\n sharedGridSelection,\n sharedNestedStack,\n value,\n viewSide = "expected",\n metadataPath,\n onChange,\n onGridSelectionChange,\n onLocationHover,\n onNestedStackChange,\n resolveArrayItemMetadataPath,\n resolveLocation,\n}: {\n activeNestedSide?: ArrayReviewSide | null\n activeSelectionSide?: ArrayReviewSide | null\n label: string\n nestedStackBaseDepth?: number\n readOnly?: boolean\n schema: ReviewFieldSchema\n selectionDepth?: number\n sharedGridSelection?: GridSelection\n sharedNestedStack?: ArrayNestedView[]\n value: JsonValue\n viewSide?: ArrayReviewSide\n metadataPath?: string\n onChange?: (value: JsonValue) => void\n onGridSelectionChange?: (\n selection: GridSelection,\n side: ArrayReviewSide,\n depth: number\n ) => void\n onNestedStackChange?: (\n stack: ArrayNestedView[],\n side: ArrayReviewSide\n ) => void\n onLocationHover?: (location?: ReviewLocation) => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n}) {\n const rows = getArrayValue(value)\n const itemSchema = getArrayItemSchema(schema)\n const gridTheme = useHumanReviewGridTheme()\n const isDark = useIsDarkTheme()\n const [localNestedStack, setLocalNestedStack] = React.useState<\n ArrayNestedView[]\n >([])\n const [localGridSelection, setLocalGridSelection] =\n React.useState<GridSelection>(emptyGridSelection)\n const fastTextOverlayOpenRef = React.useRef(false)\n const nestedStack = sharedNestedStack ?? localNestedStack\n const visibleNestedStack = nestedStack.slice(nestedStackBaseDepth)\n const activeNestedView = visibleNestedStack[0] ?? null\n const activeNestedValue = activeNestedView\n ? getNestedArrayValue({\n value,\n schema,\n nestedStack: [activeNestedView],\n })\n : null\n const isActiveNestedSource =\n Boolean(activeNestedView) && activeNestedSide === viewSide\n const isMirroredNestedTarget =\n Boolean(activeNestedView) &&\n activeNestedSide !== null &&\n activeNestedSide !== viewSide\n const blueCellText = isDark ? "rgb(147, 197, 253)" : "rgb(37, 99, 235)"\n const selectedCellBackground = isDark\n ? "rgba(37, 99, 235, 0.2)"\n : "rgba(219, 234, 254, 0.85)"\n const mirroredCellBackground = isDark\n ? "rgba(167, 139, 250, 0.18)"\n : "rgba(237, 233, 254, 0.9)"\n const mirroredHighlightRegions = React.useMemo<\n React.ComponentProps<typeof DataEditor>["highlightRegions"]\n >(() => {\n if (\n !activeSelectionSide ||\n activeSelectionSide === viewSide ||\n selectionDepth !== nestedStackBaseDepth\n ) {\n return undefined\n }\n\n const ranges = getGridSelectionRanges(sharedGridSelection)\n if (!ranges.length) return undefined\n\n return ranges.map((range) => ({\n color: mirroredCellBackground,\n range,\n style: "dashed" as const,\n }))\n }, [\n activeSelectionSide,\n mirroredCellBackground,\n nestedStackBaseDepth,\n selectionDepth,\n sharedGridSelection,\n viewSide,\n ])\n\n const setNestedStack = React.useCallback(\n (\n updater:\n | ArrayNestedView[]\n | ((current: ArrayNestedView[]) => ArrayNestedView[])\n ) => {\n if (onNestedStackChange) {\n const nextStack =\n typeof updater === "function" ? updater(nestedStack) : updater\n\n onNestedStackChange(nextStack, viewSide)\n return\n }\n\n setLocalNestedStack(updater)\n },\n [nestedStack, onNestedStackChange, viewSide]\n )\n\n const handleGridSelectionChange = React.useCallback(\n (selection: GridSelection) => {\n flushSync(() => {\n setLocalGridSelection((current) =>\n areGridSelectionsEqual(current, selection) ? current : selection\n )\n })\n\n if (onGridSelectionChange) {\n if (\n activeSelectionSide === viewSide &&\n sharedGridSelection &&\n areGridSelectionsEqual(sharedGridSelection, selection)\n ) {\n return\n }\n\n React.startTransition(() => {\n onGridSelectionChange(selection, viewSide, nestedStackBaseDepth)\n })\n return\n }\n },\n [\n activeSelectionSide,\n nestedStackBaseDepth,\n onGridSelectionChange,\n sharedGridSelection,\n viewSide,\n ]\n )\n\n const columns = React.useMemo<GridColumn[]>(() => {\n if (itemSchema.type === "object") {\n const propertyEntries = Object.entries(itemSchema.properties ?? {})\n\n if (propertyEntries.length) {\n return propertyEntries.map(([key, propertySchema]) => ({\n id: key,\n title: propertySchema.title ?? key,\n width: isComplexSchema(propertySchema) ? 148 : 132,\n }))\n }\n }\n\n return [\n {\n id: "value",\n title: itemSchema.title ?? "Value",\n width: isComplexSchema(itemSchema) ? 148 : 180,\n },\n ]\n }, [itemSchema])\n\n const getCellContent = React.useCallback(\n ([col, row]: Item): GridCell => {\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n const cellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n columnId\n )\n const matchedNestedCell =\n activeNestedView?.rowIndex === row &&\n activeNestedView.columnId === columnId\n const nestedCellTheme: Partial<Theme> | undefined = matchedNestedCell\n ? {\n bgCell: isMirroredNestedTarget\n ? mirroredCellBackground\n : selectedCellBackground,\n textDark: blueCellText,\n }\n : undefined\n\n if (isComplexSchema(cellSchema)) {\n return {\n kind: GridCellKind.Text,\n data: summarizeComplexValue(cellValue),\n displayData: summarizeComplexValue(cellValue),\n allowOverlay: false,\n readonly: true,\n cursor: "pointer",\n activationBehaviorOverride: "double-click",\n themeOverride: {\n textDark: blueCellText,\n ...(nestedCellTheme ?? {}),\n },\n }\n }\n\n if (cellSchema.type === "boolean") {\n return {\n kind: GridCellKind.Boolean,\n data: typeof cellValue === "boolean" ? cellValue : false,\n allowOverlay: false,\n readonly: readOnly,\n }\n }\n\n if (cellSchema.type === "number" || cellSchema.type === "integer") {\n return {\n kind: GridCellKind.Number,\n data: typeof cellValue === "number" ? cellValue : undefined,\n displayData: typeof cellValue === "number" ? String(cellValue) : "",\n allowOverlay: true,\n readonly: false,\n }\n }\n\n return {\n kind: GridCellKind.Text,\n data:\n cellValue === null ||\n isJsonObject(cellValue) ||\n isJsonArray(cellValue)\n ? ""\n : String(cellValue),\n displayData:\n cellValue === null ||\n isJsonObject(cellValue) ||\n isJsonArray(cellValue)\n ? ""\n : String(cellValue),\n allowOverlay: true,\n readonly: false,\n }\n },\n [\n activeNestedView,\n blueCellText,\n columns,\n isMirroredNestedTarget,\n itemSchema,\n mirroredCellBackground,\n readOnly,\n rows,\n selectedCellBackground,\n ]\n )\n\n const updateCellValue = React.useCallback(\n ([col, row]: Item, nextCell: EditableGridCell) => {\n if (readOnly || !onChange) return\n\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n const nextValue = applyPrimitiveEdit(cellSchema, nextCell)\n\n if (nextValue === undefined) return\n\n const nextRowValue =\n itemSchema.type === "object"\n ? setObjectValue(rowValue, columnId, nextValue)\n : nextValue\n\n onChange(setArrayItemValue(value, row, nextRowValue))\n },\n [columns, itemSchema, onChange, readOnly, rows, value]\n )\n const provideEditor = React.useCallback<\n NonNullable<React.ComponentProps<typeof DataEditor>["provideEditor"]>\n >(\n (cell) => {\n if (\n cell.kind !== GridCellKind.Text &&\n cell.kind !== GridCellKind.Number\n ) {\n return undefined\n }\n\n return {\n editor: (props) => {\n if (\n props.value.kind !== GridCellKind.Text &&\n props.value.kind !== GridCellKind.Number\n ) {\n return null\n }\n\n return (\n <HumanReviewTextOverlayEditor\n {...(props as React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n >)}\n overlayOpenRef={fastTextOverlayOpenRef}\n readOnly={readOnly}\n />\n )\n },\n }\n },\n [readOnly]\n )\n const handleOutsideClick = React.useCallback(\n () => !fastTextOverlayOpenRef.current,\n []\n )\n const handleItemHovered = React.useCallback(\n (args: GridMouseEventArgs) => {\n if (!onLocationHover || !resolveLocation || !metadataPath) return\n\n if (args.kind !== "cell") {\n onLocationHover(undefined)\n return\n }\n\n const [col, row] = args.location\n const column = columns[col]\n const rowValue = rows[row]\n if (!column || rowValue === undefined) {\n onLocationHover(undefined)\n return\n }\n\n const columnId = String(column.id ?? "value")\n const rowMetadataPath = resolveArrayItemMetadataPath\n ? resolveArrayItemMetadataPath(metadataPath, row, rowValue)\n : `${metadataPath}[${row}]`\n if (!rowMetadataPath) {\n onLocationHover(undefined)\n return\n }\n\n const propertyMetadataPath =\n itemSchema.type === "object"\n ? `${rowMetadataPath}.${columnId}`\n : rowMetadataPath\n\n onLocationHover(\n resolveLocation(propertyMetadataPath) ??\n resolveLocation(rowMetadataPath)\n )\n },\n [\n columns,\n itemSchema.type,\n metadataPath,\n onLocationHover,\n resolveArrayItemMetadataPath,\n resolveLocation,\n rows,\n ]\n )\n\n const openNestedCell = React.useCallback(\n ([col, row]: Item) => {\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n\n if (!isComplexSchema(cellSchema)) return\n\n setNestedStack((current) => {\n const nextView = {\n rowIndex: row,\n columnId,\n title: `${column?.title ?? columnId} / row ${row + 1}`,\n schema: cellSchema,\n value: getCellValueForArrayColumn(rowValue, itemSchema, columnId),\n }\n const currentView = current[nestedStackBaseDepth]\n\n if (\n currentView?.rowIndex === nextView.rowIndex &&\n currentView.columnId === nextView.columnId\n ) {\n return current\n }\n\n return [...current.slice(0, nestedStackBaseDepth), nextView]\n })\n },\n [columns, itemSchema, nestedStackBaseDepth, rows, setNestedStack]\n )\n\n const updateNestedValue = React.useCallback(\n (nextNestedValue: JsonValue) => {\n if (!activeNestedView || readOnly || !onChange) return\n\n onChange(\n setNestedArrayValue({\n value,\n schema,\n nestedStack: visibleNestedStack.slice(0, 1),\n nextNestedValue,\n })\n )\n setNestedStack((current) =>\n current.map((view, index) =>\n index === nestedStackBaseDepth\n ? { ...view, value: nextNestedValue }\n : view\n )\n )\n },\n [\n activeNestedView,\n nestedStackBaseDepth,\n onChange,\n readOnly,\n schema,\n setNestedStack,\n value,\n visibleNestedStack,\n ]\n )\n\n return (\n <div\n onMouseLeave={() => onLocationHover?.(undefined)}\n className={cn(\n "relative overflow-hidden rounded-md border bg-background transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:shadow-[0_0_0_1px_rgb(59_130_246_/_8%)] hover:border-blue-500/50",\n isActiveNestedSource &&\n "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_10%)]"\n )}\n >\n <div>\n <div className="flex h-8 items-center justify-between gap-2 border-b px-2 text-[11px] font-medium text-muted-foreground">\n <span>{label}</span>\n <span>{rows.length} rows</span>\n </div>\n <div className="h-[220px]">\n <DataEditor\n columns={columns}\n rows={rows.length}\n getCellContent={getCellContent}\n cellActivationBehavior="double-click"\n gridSelection={localGridSelection}\n highlightRegions={mirroredHighlightRegions}\n onCellEdited={updateCellValue}\n onCellActivated={openNestedCell}\n onGridSelectionChange={handleGridSelectionChange}\n onItemHovered={handleItemHovered}\n provideEditor={provideEditor}\n isOutsideClick={handleOutsideClick}\n rowMarkers="number"\n smoothScrollX\n smoothScrollY\n theme={gridTheme}\n width="100%"\n height="100%"\n rowHeight={32}\n headerHeight={34}\n />\n </div>\n </div>\n {activeNestedView ? (\n <div className="absolute inset-0 z-10 flex flex-col bg-background">\n <div className="flex h-8 items-center gap-2 border-b px-2">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="size-6 text-muted-foreground"\n onClick={() =>\n setNestedStack((current) =>\n current.slice(\n 0,\n Math.max(nestedStackBaseDepth, current.length - 1)\n )\n )\n }\n aria-label="Back to parent array"\n >\n <IconPlaceholder\n lucide="ChevronLeft"\n tabler="IconChevronLeft"\n hugeicons="ArrowLeft01Icon"\n phosphor="CaretLeftIcon"\n remixicon="RiArrowLeftSLine"\n className="size-3.5"\n />\n </Button>\n <div className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">\n {activeNestedView.title}\n </div>\n </div>\n <div className="min-h-0 flex-1 overflow-auto p-2">\n {activeNestedView.schema.type === "array" ? (\n <HumanReviewArrayValueGrid\n label={\n activeNestedView.schema.title ?? activeNestedView.columnId\n }\n nestedStackBaseDepth={nestedStackBaseDepth + 1}\n readOnly={readOnly}\n schema={activeNestedView.schema}\n sharedGridSelection={sharedGridSelection}\n sharedNestedStack={sharedNestedStack}\n value={activeNestedValue}\n viewSide={viewSide}\n activeNestedSide={activeNestedSide}\n activeSelectionSide={activeSelectionSide}\n selectionDepth={selectionDepth}\n onChange={updateNestedValue}\n onGridSelectionChange={onGridSelectionChange}\n onNestedStackChange={onNestedStackChange}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n ) : (\n <HumanReviewObjectValueEditor\n schema={activeNestedView.schema}\n value={activeNestedValue}\n originalValue={activeNestedValue}\n readOnly={readOnly}\n onChange={updateNestedValue}\n />\n )}\n </div>\n </div>\n ) : null}\n </div>\n )\n}\n\nfunction HumanReviewObjectValueEditor({\n schema,\n value,\n originalValue,\n readOnly = false,\n onChange,\n}: {\n schema: ReviewFieldSchema\n value: JsonValue\n originalValue: JsonValue\n readOnly?: boolean\n onChange: (value: JsonValue) => void\n}) {\n const propertyEntries = Object.entries(schema.properties ?? {})\n\n if (!propertyEntries.length) {\n return (\n <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n No properties\n </div>\n )\n }\n\n return (\n <div className="space-y-2">\n {propertyEntries.map(([propertyKey, propertySchema]) => (\n <HumanReviewFieldCard\n key={propertyKey}\n field={{\n key: propertyKey,\n schema: propertySchema,\n actual: getObjectValue(originalValue, propertyKey),\n expected: getObjectValue(originalValue, propertyKey),\n }}\n value={getObjectValue(value, propertyKey)}\n originalValue={getObjectValue(originalValue, propertyKey)}\n readOnly={readOnly}\n onChange={(childValue) =>\n !readOnly &&\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onUndo={() =>\n !readOnly &&\n onChange(\n setObjectValue(\n value,\n propertyKey,\n getObjectValue(originalValue, propertyKey)\n )\n )\n }\n onSetNull={() =>\n !readOnly && onChange(setObjectValue(value, propertyKey, null))\n }\n />\n ))}\n </div>\n )\n}\n\ntype HumanReviewFieldCardProps = {\n field: ReviewField\n value: JsonValue\n originalValue: JsonValue\n active?: boolean\n activeFieldKey?: string\n readOnly?: boolean\n showExpected?: boolean\n onChange: (value: JsonValue) => void\n onFieldFocus?: (field: ReviewField) => void\n onLocationHover?: (location?: ReviewLocation) => void\n onUndo: () => void\n onSetNull: () => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n}\n\nfunction areHumanReviewFieldCardPropsEqual(\n previous: HumanReviewFieldCardProps,\n next: HumanReviewFieldCardProps\n) {\n return (\n previous.field === next.field &&\n Object.is(previous.value, next.value) &&\n Object.is(previous.originalValue, next.originalValue) &&\n previous.active === next.active &&\n previous.activeFieldKey === next.activeFieldKey &&\n previous.readOnly === next.readOnly &&\n previous.showExpected === next.showExpected &&\n previous.onFieldFocus === next.onFieldFocus &&\n previous.onLocationHover === next.onLocationHover &&\n previous.resolveArrayItemMetadataPath ===\n next.resolveArrayItemMetadataPath &&\n previous.resolveLocation === next.resolveLocation\n )\n}\n\nconst HumanReviewFieldCard = React.memo(\n HumanReviewFieldCardBase,\n areHumanReviewFieldCardPropsEqual\n)\n\nfunction HumanReviewFieldCardBase({\n field,\n value,\n originalValue,\n active,\n activeFieldKey,\n readOnly = false,\n showExpected = true,\n onChange,\n onFieldFocus,\n onLocationHover,\n onUndo,\n onSetNull,\n resolveArrayItemMetadataPath,\n resolveLocation,\n}: HumanReviewFieldCardProps) {\n const isExpectedEditable = showExpected && !readOnly\n const modified = showExpected && !jsonValuesEqual(value, originalValue)\n const fieldTypeIcon = React.createElement(getFieldIcon(field.schema.type), {\n className: "size-3.5",\n })\n const propertyEntries = Object.entries(field.schema.properties ?? {})\n const [syncedArrayNestedView, setSyncedArrayNestedView] =\n React.useState<SyncedArrayNestedView>(EMPTY_SYNCED_ARRAY_NESTED_VIEW)\n const [syncedArraySelection, setSyncedArraySelection] =\n React.useState<SyncedArraySelection>(EMPTY_SYNCED_ARRAY_SELECTION)\n const updateSyncedArrayNestedView = React.useCallback(\n (stack: ArrayNestedView[], side: ArrayReviewSide) => {\n const activeSide = stack.length ? side : null\n\n setSyncedArrayNestedView((current) =>\n current.activeSide === activeSide &&\n areArrayNestedViewsEqual(current.stack, stack)\n ? current\n : {\n activeSide,\n stack,\n }\n )\n },\n []\n )\n const updateSyncedArraySelection = React.useCallback(\n (gridSelection: GridSelection, side: ArrayReviewSide, depth: number) => {\n const activeSide = gridSelection.current ? side : null\n\n setSyncedArraySelection((current) =>\n current.activeSide === activeSide &&\n current.depth === depth &&\n areGridSelectionsEqual(current.gridSelection, gridSelection)\n ? current\n : {\n activeSide,\n depth,\n gridSelection,\n }\n )\n },\n []\n )\n const focusAndHoverField = React.useCallback(() => {\n onFieldFocus?.(field)\n onLocationHover?.(getReviewFieldLocation(field, resolveLocation))\n }, [field, onFieldFocus, onLocationHover, resolveLocation])\n\n return (\n <div\n tabIndex={0}\n onFocusCapture={focusAndHoverField}\n onMouseEnter={focusAndHoverField}\n onMouseLeave={() => onLocationHover?.(undefined)}\n className={cn(\n "rounded-lg border bg-background p-3 transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:bg-blue-500/5 hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",\n active &&\n "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_8%)]"\n )}\n >\n <div className="mb-3 flex min-h-8 items-start justify-between gap-3">\n <div className="min-w-0">\n <div className="flex min-w-0 items-center gap-2">\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">\n {field.schema.title ?? field.key}\n </div>\n </div>\n <span\n className={cn(\n "size-2 shrink-0 rounded-full bg-amber-400",\n !modified && "opacity-0"\n )}\n />\n </div>\n <div className="truncate text-xs text-muted-foreground">\n {field.key}\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-1">\n {isExpectedEditable && modified ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="text-muted-foreground"\n onClick={onUndo}\n aria-label={`Undo ${field.key}`}\n >\n <IconPlaceholder\n lucide="Undo2"\n tabler="IconArrowBackUp"\n hugeicons="Undo02Icon"\n phosphor="ArrowUUpLeftIcon"\n remixicon="RiArrowGoBackLine"\n className="size-4"\n />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Revert changes</TooltipContent>\n </Tooltip>\n ) : null}\n {isExpectedEditable ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="text-muted-foreground"\n onClick={onSetNull}\n aria-label={`Set ${field.key} to null`}\n >\n <IconPlaceholder\n lucide="CircleX"\n tabler="IconCircleX"\n hugeicons="CancelCircleIcon"\n phosphor="XCircleIcon"\n remixicon="RiCloseCircleLine"\n className="size-4"\n />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Set to NULL</TooltipContent>\n </Tooltip>\n ) : null}\n <div className="flex h-6 items-center gap-1 rounded-md border bg-muted/50 px-1.5 text-xs text-muted-foreground">\n {fieldTypeIcon}\n {field.schema.type}\n </div>\n </div>\n </div>\n {field.schema.type === "object" ? (\n <div className="rounded-md border bg-muted/25 p-2">\n <div className="mb-2 flex items-center justify-between gap-3 text-[11px] font-medium text-muted-foreground">\n <span>Properties</span>\n <span>{propertyEntries.length} fields</span>\n </div>\n <div className="space-y-2">\n {propertyEntries.length ? (\n propertyEntries.map(([propertyKey, schema]) => {\n const childField: ReviewField = {\n key: `${field.key}.${propertyKey}`,\n schema,\n actual: getObjectValue(field.actual, propertyKey),\n expected: getObjectValue(originalValue, propertyKey),\n metadataPath: `${field.metadataPath ?? field.key}.${propertyKey}`,\n }\n\n return (\n <HumanReviewFieldCard\n key={childField.key}\n field={childField}\n value={getObjectValue(value, propertyKey)}\n originalValue={childField.expected}\n active={childField.key === activeFieldKey}\n activeFieldKey={activeFieldKey}\n readOnly={readOnly}\n showExpected={showExpected}\n onChange={(childValue) =>\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onFieldFocus={onFieldFocus}\n onLocationHover={onLocationHover}\n onUndo={() =>\n onChange(\n setObjectValue(value, propertyKey, childField.expected)\n )\n }\n onSetNull={() =>\n onChange(setObjectValue(value, propertyKey, null))\n }\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n )\n })\n ) : (\n <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n No properties\n </div>\n )}\n </div>\n </div>\n ) : field.schema.type === "array" ? (\n <div className="grid gap-2">\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Actual"\n metadataPath={field.metadataPath ?? field.key}\n readOnly\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n schema={field.schema}\n selectionDepth={syncedArraySelection.depth}\n sharedGridSelection={syncedArraySelection.gridSelection}\n sharedNestedStack={syncedArrayNestedView.stack}\n value={field.actual}\n viewSide="actual"\n onGridSelectionChange={updateSyncedArraySelection}\n onLocationHover={onLocationHover}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n {showExpected ? (\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Expected"\n metadataPath={field.metadataPath ?? field.key}\n readOnly={readOnly}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n schema={field.schema}\n selectionDepth={syncedArraySelection.depth}\n sharedGridSelection={syncedArraySelection.gridSelection}\n sharedNestedStack={syncedArrayNestedView.stack}\n value={value}\n viewSide="expected"\n onChange={onChange}\n onGridSelectionChange={updateSyncedArraySelection}\n onLocationHover={onLocationHover}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n ) : null}\n </div>\n ) : (\n <div className={cn("grid gap-2", showExpected && "sm:grid-cols-2")}>\n <div className="rounded-md border bg-muted/30 p-2">\n {field.schema.description ? (\n <p className="mb-2 text-xs text-muted-foreground">\n {field.schema.description}\n </p>\n ) : null}\n <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n Actual\n </div>\n <div className="min-h-7 rounded-md bg-background px-2 py-1.5 text-sm">\n {formatValue(field.actual)}\n </div>\n </div>\n {showExpected ? (\n <div className="rounded-md border bg-muted/30 p-2">\n <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n Expected\n </div>\n <HumanReviewValueInput\n readOnly={readOnly}\n schema={field.schema}\n value={getPrimitiveValue(value)}\n onChange={onChange}\n />\n </div>\n ) : null}\n </div>\n )}\n </div>\n )\n}\n\nexport function HumanReviewHighlight({\n location,\n}: {\n location: ReviewLocation\n}) {\n const area = location.area\n\n return (\n <div\n className={cn(\n "pointer-events-none absolute z-10 border",\n REVIEW_HIGHLIGHT_STYLE\n )}\n style={{\n left: `${area.left}%`,\n top: `${area.top}%`,\n width: `${area.width}%`,\n height: `${area.height}%`,\n }}\n />\n )\n}\n\nexport function JsonDiffView({\n actual,\n expected,\n theme = "light",\n}: {\n actual: JsonObject\n expected: JsonObject\n theme?: HumanReviewTheme\n}) {\n const oldFile = React.useMemo(\n () => ({\n name: "actual.json",\n contents: formatJson(actual),\n lang: "json",\n }),\n [actual]\n )\n const newFile = React.useMemo(\n () => ({\n name: "expected.json",\n contents: formatJson(expected),\n lang: "json",\n }),\n [expected]\n )\n\n return (\n <ScrollAreaVirtualizer\n className="h-full bg-surface/60"\n contentClassName="min-w-full"\n >\n <div className="bounding-box-citations-diff h-full text-xs">\n <MultiFileDiff\n className="block min-w-full"\n oldFile={oldFile}\n newFile={newFile}\n options={{\n diffStyle: "split",\n disableFileHeader: true,\n diffIndicators: "bars",\n hunkSeparators: "line-info-basic",\n overflow: "wrap",\n themeType: theme,\n theme: {\n light: "pierre-light-soft",\n dark: "pierre-dark-soft",\n },\n }}\n />\n </div>\n </ScrollAreaVirtualizer>\n )\n}\n\nexport function JsonCodeView({\n name = "actual.json",\n theme = "light",\n value,\n}: {\n name?: string\n theme?: HumanReviewTheme\n value: JsonValue\n}) {\n const file = React.useMemo(() => {\n const contents = formatJson(value)\n\n return {\n name,\n contents,\n lang: "json" as const,\n cacheKey: contents,\n }\n }, [name, value])\n\n return (\n <div\n data-rehype-pretty-code-figure\n className="relative m-0! h-full overflow-hidden rounded-none! bg-code text-code-foreground"\n >\n <WorkerPoolContextProvider\n poolOptions={CODE_WORKER_POOL_OPTIONS}\n highlighterOptions={CODE_HIGHLIGHTER_OPTIONS}\n >\n <ScrollAreaVirtualizer\n key={`${file.cacheKey}:${theme}`}\n className="h-full min-w-0"\n contentClassName="min-w-full"\n >\n <File\n key={`${file.cacheKey}:${theme}`}\n className="block min-w-full"\n file={file}\n metrics={CODE_VIRTUAL_FILE_METRICS}\n style={CODE_FILE_THEME}\n options={{\n disableFileHeader: true,\n overflow: "scroll",\n themeType: theme,\n theme: {\n light: "pierre-light-soft",\n dark: "pierre-dark-soft",\n },\n }}\n />\n </ScrollAreaVirtualizer>\n </WorkerPoolContextProvider>\n </div>\n )\n}\n\nexport function HumanReviewPanel({\n fields = REVIEW_FIELDS,\n activeFieldKey,\n className,\n onFieldFocus,\n onLocationHover,\n resolveArrayItemMetadataPath,\n resolveLocation,\n showExpected = true,\n theme = "light",\n}: {\n fields?: ReviewField[]\n activeFieldKey?: string\n className?: string\n onFieldFocus?: (field: ReviewField) => void\n onLocationHover?: (location?: ReviewLocation) => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n showExpected?: boolean\n theme?: HumanReviewTheme\n} = {}) {\n const [activeTab, setActiveTab] = React.useState("form")\n const actualValues = React.useMemo(\n () => valuesFromFields(fields, "actual"),\n [fields]\n )\n const initialExpectedValues = React.useMemo(\n () => valuesFromFields(fields, "expected"),\n [fields]\n )\n const [expected, setExpected] = React.useState<JsonObject>(\n initialExpectedValues\n )\n\n const [previousExpectedValues, setPreviousExpectedValues] = React.useState(\n initialExpectedValues\n )\n if (!Object.is(previousExpectedValues, initialExpectedValues)) {\n setPreviousExpectedValues(initialExpectedValues)\n setExpected(initialExpectedValues)\n }\n\n const updateValue = React.useCallback((key: string, value: JsonValue) => {\n setExpected((current) =>\n Object.is(current[key], value) ? current : { ...current, [key]: value }\n )\n }, [])\n\n return (\n <TooltipProvider delay={200}>\n <Tabs\n value={activeTab}\n onValueChange={setActiveTab}\n className={cn("flex h-[560px] flex-col gap-0 bg-background", className)}\n >\n <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">\n <TabsList className="h-8 sm:h-7">\n <TabsTrigger value="form" className="h-7 sm:h-6">\n <IconPlaceholder\n lucide="CaptionsIcon"\n tabler="IconTextCaption"\n hugeicons="TextCheckIcon"\n phosphor="TextTIcon"\n remixicon="RiTextWrap"\n className="size-4"\n />\n Form\n </TabsTrigger>\n <TabsTrigger value="json" className="h-7 sm:h-6">\n <IconPlaceholder\n lucide="SquareCode"\n tabler="IconSourceCode"\n hugeicons="SourceCodeSquareIcon"\n phosphor="CodeIcon"\n remixicon="RiCodeBlock"\n className="size-4"\n />\n JSON\n </TabsTrigger>\n </TabsList>\n </div>\n <TabsContent value="form" keepMounted className="min-h-0 flex-1">\n <ScrollArea className="h-full" scrollFade>\n <div className="space-y-3 p-3">\n {fields.map((field) => (\n <HumanReviewFieldCard\n key={field.key}\n field={field}\n value={\n showExpected ? (expected[field.key] ?? null) : field.actual\n }\n originalValue={showExpected ? field.expected : field.actual}\n active={\n field.key === activeFieldKey ||\n activeFieldKey?.startsWith(`${field.key}.`)\n }\n activeFieldKey={activeFieldKey}\n showExpected={showExpected}\n onChange={(value) => updateValue(field.key, value)}\n onFieldFocus={onFieldFocus}\n onLocationHover={onLocationHover}\n onUndo={() => updateValue(field.key, field.expected)}\n onSetNull={() => updateValue(field.key, null)}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n ))}\n </div>\n </ScrollArea>\n </TabsContent>\n <TabsContent value="json" keepMounted className="min-h-0 flex-1">\n {showExpected ? (\n <JsonDiffView\n actual={actualValues}\n expected={expected}\n theme={theme}\n />\n ) : (\n <JsonCodeView value={actualValues} theme={theme} />\n )}\n </TabsContent>\n </Tabs>\n </TooltipProvider>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n DataEditor,\n emptyGridSelection,\n GridCellKind,\n TextCellEntry,\n type EditableGridCell,\n type GridCell,\n type GridColumn,\n type GridMouseEventArgs,\n type GridSelection,\n type Item,\n type NumberCell,\n type ProvideEditorComponent,\n type Rectangle,\n type TextCell,\n type Theme,\n} from "@glideapps/glide-data-grid"\nimport { Virtualizer as DiffsVirtualizer } from "@pierre/diffs"\nimport {\n File,\n MultiFileDiff,\n VirtualizerContext,\n WorkerPoolContextProvider,\n type VirtualFileMetrics,\n type WorkerInitializationRenderOptions,\n type WorkerPoolOptions,\n} from "@pierre/diffs/react"\nimport { flushSync } from "react-dom"\n\nimport type { RegistryIconProps } from "@/lib/registry-icon-props"\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport { Input } from "@/components/ui/input"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nimport "@glideapps/glide-data-grid/dist/index.css"\n\nfunction InputNumericGlyph(props: RegistryIconProps) {\n return (\n <IconPlaceholder\n lucide="Hash"\n tabler="IconNumber123"\n hugeicons="InputNumericIcon"\n phosphor="NumpadIcon"\n remixicon="RiHashtag"\n {...props}\n />\n )\n}\n\nfunction InputTextGlyph(props: RegistryIconProps) {\n return (\n <IconPlaceholder\n lucide="TextCursorInput"\n tabler="IconForms"\n hugeicons="InputTextIcon"\n phosphor="TextboxIcon"\n remixicon="RiInputField"\n {...props}\n />\n )\n}\n\nfunction SecondBracketGlyph(props: RegistryIconProps) {\n return (\n <IconPlaceholder\n lucide="Brackets"\n tabler="IconBrackets"\n hugeicons="SecondBracketIcon"\n phosphor="BracketsSquareIcon"\n remixicon="RiBracketsLine"\n {...props}\n />\n )\n}\n\nfunction SourceCodeSquareGlyph(props: RegistryIconProps) {\n return (\n <IconPlaceholder\n lucide="SquareCode"\n tabler="IconSourceCode"\n hugeicons="SourceCodeSquareIcon"\n phosphor="CodeIcon"\n remixicon="RiCodeBlock"\n {...props}\n />\n )\n}\n\nfunction TextCheckGlyph(props: RegistryIconProps) {\n return (\n <IconPlaceholder\n lucide="CaptionsIcon"\n tabler="IconTextCaption"\n hugeicons="TextCheckIcon"\n phosphor="TextTIcon"\n remixicon="RiTextWrap"\n {...props}\n />\n )\n}\n\nexport type JsonPrimitive = string | number | boolean | null\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray\nexport type JsonObject = { [key: string]: JsonValue }\nexport type JsonArray = JsonValue[]\nexport type SchemaPropertyType =\n | "string"\n | "number"\n | "integer"\n | "boolean"\n | "object"\n | "array"\n\nexport type ReviewFieldSchema = {\n type: SchemaPropertyType\n title?: string\n description?: string\n enum?: Array<string | number>\n properties?: Record<string, ReviewFieldSchema>\n items?: ReviewFieldSchema\n}\n\nexport type HighlightArea = {\n left: number\n top: number\n width: number\n height: number\n}\n\nexport type ReviewField = {\n key: string\n schema: ReviewFieldSchema\n actual: JsonValue\n expected: JsonValue\n location?: ReviewLocation\n metadataPath?: string\n}\n\nexport type ReviewLocation = {\n page: number\n area: HighlightArea\n}\n\nexport type ReviewCitation = {\n page: number\n polygon?: Array<{ x: number; y: number }>\n pageWidth: number\n pageHeight: number\n}\n\nexport type ReviewMetadataEntry = {\n citations?: ReviewCitation[]\n}\n\nfunction ScrollAreaVirtualizer({\n children,\n className,\n contentClassName,\n contentStyle,\n scrollFade = true,\n}: {\n children: React.ReactNode\n className?: string\n contentClassName?: string\n contentStyle?: React.CSSProperties\n scrollFade?: boolean\n}) {\n const [virtualizer] = React.useState(() =>\n typeof window !== "undefined" ? new DiffsVirtualizer() : undefined\n )\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const contentRef = React.useRef<HTMLDivElement | null>(null)\n const syncVirtualizer = React.useCallback(() => {\n if (!virtualizer) return\n\n const viewport = viewportRef.current\n const content = contentRef.current\n\n if (viewport && content) {\n virtualizer.setup(viewport, content)\n return\n }\n\n virtualizer.cleanUp()\n }, [virtualizer])\n const setViewportRef = React.useCallback(\n (node: HTMLDivElement | null) => {\n viewportRef.current = node\n syncVirtualizer()\n },\n [syncVirtualizer]\n )\n const setContentRef = React.useCallback(\n (node: HTMLDivElement | null) => {\n contentRef.current = node\n syncVirtualizer()\n },\n [syncVirtualizer]\n )\n\n React.useEffect(() => {\n return () => virtualizer?.cleanUp()\n }, [virtualizer])\n\n return (\n <VirtualizerContext.Provider value={virtualizer}>\n <ScrollArea\n className={className}\n scrollFade={scrollFade}\n scrollbarOverflowOnly\n viewportRef={setViewportRef}\n >\n <div\n ref={setContentRef}\n className={contentClassName}\n style={contentStyle}\n >\n {children}\n </div>\n </ScrollArea>\n </VirtualizerContext.Provider>\n )\n}\n\nconst REVIEW_HIGHLIGHT_STYLE =\n "border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_10%)]"\n\nconst CODE_FILE_THEME = {\n "--diffs-light-bg": "var(--color-code)",\n "--diffs-dark-bg": "var(--color-code)",\n "--diffs-light": "var(--color-code-foreground)",\n "--diffs-dark": "var(--color-code-foreground)",\n "--diffs-bg-context-override": "var(--color-code)",\n "--diffs-bg-context-gutter-override": "var(--color-code)",\n "--diffs-bg-buffer-override": "var(--color-code)",\n "--diffs-fg-number-override": "var(--color-muted-foreground)",\n "--diffs-font-size": "0.8rem",\n "--diffs-line-height": "1.625",\n} as React.CSSProperties\n\nconst CODE_FONT_SIZE_PX = 12.8\nconst CODE_LINE_HEIGHT_PX = CODE_FONT_SIZE_PX * 1.625\n\nconst CODE_VIRTUAL_FILE_METRICS = {\n hunkLineCount: 50,\n lineHeight: CODE_LINE_HEIGHT_PX,\n diffHeaderHeight: 44,\n spacing: 8,\n paddingTop: 0,\n paddingBottom: 8,\n} satisfies VirtualFileMetrics\n\nconst CODE_HIGHLIGHTER_OPTIONS = {\n theme: {\n light: "pierre-light-soft",\n dark: "pierre-dark-soft",\n },\n langs: ["json"],\n} satisfies WorkerInitializationRenderOptions\n\nconst CODE_WORKER_POOL_OPTIONS = {\n poolSize: 2,\n workerFactory: () =>\n new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), {\n type: "module",\n }),\n} satisfies WorkerPoolOptions\n\nfunction readIsDarkTheme() {\n return (\n typeof document !== "undefined" &&\n document.documentElement.classList.contains("dark")\n )\n}\n\n// A single shared MutationObserver backs every consumer. Each grid previously\n// created its own observer (two, via useHumanReviewGridTheme), so opening a\n// nested array view spun up and tore down several observers at once.\nconst darkThemeListeners = new Set<(isDark: boolean) => void>()\nlet darkThemeObserver: MutationObserver | null = null\nlet sharedIsDarkTheme = false\n\nfunction ensureDarkThemeObserver() {\n if (\n darkThemeObserver ||\n typeof document === "undefined" ||\n typeof MutationObserver === "undefined"\n ) {\n return\n }\n\n sharedIsDarkTheme = readIsDarkTheme()\n darkThemeObserver = new MutationObserver(() => {\n const nextIsDark = readIsDarkTheme()\n if (nextIsDark === sharedIsDarkTheme) return\n\n sharedIsDarkTheme = nextIsDark\n darkThemeListeners.forEach((listener) => listener(nextIsDark))\n })\n darkThemeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ["class"],\n })\n}\n\nfunction subscribeToDarkTheme(listener: () => void) {\n ensureDarkThemeObserver()\n darkThemeListeners.add(listener)\n return () => {\n darkThemeListeners.delete(listener)\n if (darkThemeListeners.size === 0 && darkThemeObserver) {\n darkThemeObserver.disconnect()\n darkThemeObserver = null\n }\n }\n}\n\nfunction useIsDarkTheme() {\n return React.useSyncExternalStore(\n subscribeToDarkTheme,\n readIsDarkTheme,\n () => false\n )\n}\n\nfunction useHumanReviewGridTheme() {\n const isDark = useIsDarkTheme()\n\n return React.useMemo<Partial<Theme>>(\n () => ({\n accentColor: isDark ? "rgb(96, 165, 250)" : "rgb(37, 99, 235)",\n accentLight: isDark ? "rgba(29, 78, 216, 0.15)" : "rgb(219, 234, 254)",\n accentFg: "rgb(255, 255, 255)",\n textDark: isDark ? "rgb(229, 229, 229)" : "rgb(23, 23, 23)",\n textMedium: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n textLight: isDark ? "rgb(115, 115, 115)" : "rgb(163, 163, 163)",\n textBubble: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n textHeader: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n textGroupHeader: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n bgCell: isDark ? "rgb(10, 10, 10)" : "rgb(255, 255, 255)",\n bgCellMedium: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n bgHeader: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n bgHeaderHasFocus: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n bgHeaderHovered: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n borderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n horizontalBorderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n cellHorizontalPadding: 8,\n cellVerticalPadding: 3,\n headerIconSize: 18,\n baseFontStyle: "13px",\n headerFontStyle: "600 13px",\n markerFontStyle: "11px",\n fontFamily: \'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif\',\n editorFontSize: "13px",\n }),\n [isDark]\n )\n}\n\nexport const REVIEW_FIELDS: ReviewField[] = [\n {\n key: "statement_period",\n schema: {\n type: "string",\n title: "Statement period",\n description: "Date range covered by the bank statement.",\n },\n actual: "Jan 1-31, 2026",\n expected: "January 1-31, 2026",\n location: {\n page: 1,\n area: { left: 31, top: 30, width: 40, height: 5.8 },\n },\n },\n {\n key: "transactions",\n schema: {\n type: "array",\n title: "Transactions",\n description: "Posted account activity during the statement period.",\n items: {\n type: "object",\n properties: {\n date: {\n type: "string",\n title: "Date",\n },\n description: {\n type: "string",\n title: "Description",\n },\n amount: {\n type: "number",\n title: "Amount",\n },\n category: {\n type: "string",\n title: "Category",\n },\n merchant: {\n type: "object",\n title: "Merchant",\n properties: {\n name: {\n type: "string",\n title: "Name",\n },\n city: {\n type: "string",\n title: "City",\n },\n risk_level: {\n type: "string",\n title: "Risk level",\n },\n },\n },\n tags: {\n type: "array",\n title: "Tags",\n items: {\n type: "string",\n title: "Tag",\n },\n },\n },\n },\n },\n actual: [\n {\n date: "2026-01-03",\n description: "ACH CREDIT PAYROLL",\n amount: 4250,\n category: "Deposit",\n merchant: {\n name: "Acme Payroll",\n city: "New York",\n risk_level: "low",\n },\n tags: ["payroll", "recurring"],\n },\n {\n date: "2026-01-12",\n description: "POS PURCHASE GROCERY MART",\n amount: -86.42,\n category: "Debit",\n merchant: {\n name: "Grocery Mart",\n city: "Brooklyn",\n risk_level: "medium",\n },\n tags: ["card", "groceries"],\n },\n ],\n expected: [\n {\n date: "2026-01-03",\n description: "ACH CREDIT PAYROLL",\n amount: 4250,\n category: "Deposit",\n merchant: {\n name: "Acme Payroll",\n city: "New York",\n risk_level: "low",\n },\n tags: ["payroll", "recurring"],\n },\n {\n date: "2026-01-12",\n description: "POS PURCHASE GROCERY MART",\n amount: -68.42,\n category: "Debit",\n merchant: {\n name: "Grocery Mart",\n city: "Brooklyn",\n risk_level: "low",\n },\n tags: ["card", "groceries", "needs_review"],\n },\n ],\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "ending_balance",\n schema: {\n type: "number",\n title: "Ending balance",\n description: "Final account balance at the end of the statement period.",\n },\n actual: 12840.18,\n expected: 12858.18,\n location: {\n page: 1,\n area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n },\n },\n {\n key: "overdraft_protection_enabled",\n schema: {\n type: "boolean",\n title: "Overdraft protection enabled",\n description: "Whether overdraft protection is enabled for the account.",\n },\n actual: false,\n expected: true,\n location: {\n page: 2,\n area: { left: 9.5, top: 12, width: 81, height: 11.5 },\n },\n },\n {\n key: "account_details",\n schema: {\n type: "object",\n title: "Account details",\n description: "Account owner and identifying details from the statement.",\n properties: {\n holder_name: {\n type: "string",\n title: "Holder name",\n },\n account_last_four: {\n type: "string",\n title: "Account last four",\n },\n account_type: {\n type: "string",\n title: "Account type",\n },\n mailing_address: {\n type: "object",\n title: "Mailing address",\n properties: {\n line_1: {\n type: "string",\n title: "Line 1",\n },\n city: {\n type: "string",\n title: "City",\n },\n state: {\n type: "string",\n title: "State",\n },\n },\n },\n linked_accounts: {\n type: "array",\n title: "Linked accounts",\n items: {\n type: "object",\n properties: {\n nickname: {\n type: "string",\n title: "Nickname",\n },\n last_four: {\n type: "string",\n title: "Last four",\n },\n },\n },\n },\n },\n },\n actual: {\n holder_name: "Jordan Lee",\n account_last_four: "4821",\n account_type: "Checking",\n mailing_address: {\n line_1: "42 Market Street",\n city: "Brooklyn",\n state: "NY",\n },\n linked_accounts: [\n {\n nickname: "Operations reserve",\n last_four: "1842",\n },\n ],\n },\n expected: {\n holder_name: "Jordan Lee",\n account_last_four: "4821",\n account_type: "Premier Checking",\n mailing_address: {\n line_1: "42 Market Street",\n city: "New York",\n state: "NY",\n },\n linked_accounts: [\n {\n nickname: "Operations reserve",\n last_four: "1842",\n },\n {\n nickname: "Payroll sweep",\n last_four: "9174",\n },\n ],\n },\n },\n]\n\nfunction getCitationLocation(\n citation: ReviewCitation\n): ReviewLocation | undefined {\n const polygon = citation.polygon\n if (!polygon?.length || !citation.pageWidth || !citation.pageHeight) {\n return undefined\n }\n\n const xs = polygon.map((point) => point.x)\n const ys = polygon.map((point) => point.y)\n const left = Math.min(...xs)\n const top = Math.min(...ys)\n const right = Math.max(...xs)\n const bottom = Math.max(...ys)\n\n return {\n page: citation.page,\n area: {\n left: (left / citation.pageWidth) * 100,\n top: (top / citation.pageHeight) * 100,\n width: ((right - left) / citation.pageWidth) * 100,\n height: ((bottom - top) / citation.pageHeight) * 100,\n },\n }\n}\n\nexport function getMetadataLocation(\n metadata: Record<string, ReviewMetadataEntry> | undefined,\n metadataPath: string | undefined\n) {\n if (!metadata || !metadataPath) return undefined\n\n const citation = metadata[metadataPath]?.citations?.find(\n (candidate) => candidate.polygon?.length\n )\n\n return citation ? getCitationLocation(citation) : undefined\n}\n\nexport function getReviewFieldLocation(\n field: ReviewField | undefined,\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n) {\n if (!field) return undefined\n\n return (\n field.location ??\n resolveLocation?.(field.metadataPath ?? field.key) ??\n undefined\n )\n}\n\nexport function getReviewLocationKey(location: ReviewLocation | undefined) {\n if (!location) return null\n\n const { area } = location\n return [location.page, area.left, area.top, area.width, area.height].join(":")\n}\n\nfunction valuesFromFields(\n fields: ReviewField[],\n valueKey: "actual" | "expected"\n) {\n return fields.reduce<JsonObject>((values, field) => {\n values[field.key] = field[valueKey]\n return values\n }, {})\n}\n\nfunction formatJson(value: unknown) {\n return JSON.stringify(value, null, 2)\n}\n\nfunction isJsonObject(value: JsonValue): value is JsonObject {\n return typeof value === "object" && value !== null && !Array.isArray(value)\n}\n\nfunction isJsonArray(value: JsonValue): value is JsonArray {\n return Array.isArray(value)\n}\n\nfunction getObjectValue(value: JsonValue, key: string): JsonValue {\n if (!isJsonObject(value)) return null\n return value[key] ?? null\n}\n\nfunction setObjectValue(\n value: JsonValue,\n key: string,\n childValue: JsonValue\n): JsonObject {\n return {\n ...(isJsonObject(value) ? value : {}),\n [key]: childValue,\n }\n}\n\nfunction getArrayValue(value: JsonValue): JsonArray {\n return isJsonArray(value) ? value : []\n}\n\nfunction setArrayItemValue(\n value: JsonValue,\n index: number,\n childValue: JsonValue\n): JsonArray {\n const nextValue = getArrayValue(value).slice()\n nextValue[index] = childValue\n return nextValue\n}\n\nfunction getPrimitiveValue(value: JsonValue): JsonPrimitive {\n return isJsonObject(value) || isJsonArray(value) ? null : value\n}\n\nfunction jsonValuesEqual(left: JsonValue, right: JsonValue) {\n return formatJson(left) === formatJson(right)\n}\n\nexport function findReviewField(\n fields: ReviewField[],\n fieldKey: string | undefined\n): ReviewField | undefined {\n if (!fieldKey) return undefined\n\n for (const field of fields) {\n if (field.key === fieldKey) return field\n\n if (field.schema.type === "object") {\n const childFields = Object.entries(field.schema.properties ?? {}).map(\n ([key, schema]): ReviewField => ({\n key: `${field.key}.${key}`,\n schema,\n actual: getObjectValue(field.actual, key),\n expected: getObjectValue(field.expected, key),\n metadataPath: `${field.metadataPath ?? field.key}.${key}`,\n })\n )\n const childField = findReviewField(childFields, fieldKey)\n if (childField) return childField\n }\n }\n\n return undefined\n}\n\nfunction formatValue(value: JsonValue) {\n if (value === null) return "NULL"\n if (isJsonObject(value) || isJsonArray(value)) return formatJson(value)\n if (typeof value === "boolean") return value ? "true" : "false"\n return String(value)\n}\n\nfunction areGridRangesEqual(\n left: Readonly<Rectangle> | undefined,\n right: Readonly<Rectangle> | undefined\n) {\n return (\n left === right ||\n (left !== undefined &&\n right !== undefined &&\n left.x === right.x &&\n left.y === right.y &&\n left.width === right.width &&\n left.height === right.height)\n )\n}\n\nfunction areGridRangeStacksEqual(\n left: readonly Readonly<Rectangle>[] | undefined,\n right: readonly Readonly<Rectangle>[] | undefined\n) {\n if (left === right) return true\n if (!left || !right || left.length !== right.length) return false\n\n return left.every((range, index) => areGridRangesEqual(range, right[index]))\n}\n\nfunction areGridSelectionsEqual(left: GridSelection, right: GridSelection) {\n const leftCurrent = left.current\n const rightCurrent = right.current\n\n return (\n leftCurrent?.cell[0] === rightCurrent?.cell[0] &&\n leftCurrent?.cell[1] === rightCurrent?.cell[1] &&\n areGridRangesEqual(leftCurrent?.range, rightCurrent?.range) &&\n areGridRangeStacksEqual(\n leftCurrent?.rangeStack,\n rightCurrent?.rangeStack\n ) &&\n left.columns.equals(right.columns) &&\n left.rows.equals(right.rows)\n )\n}\n\nfunction getGridSelectionRanges(selection: GridSelection | undefined) {\n const current = selection?.current\n if (!current) return []\n\n return [...(current.rangeStack ?? []), current.range]\n}\n\nfunction areArrayNestedViewsEqual(\n left: ArrayNestedView[],\n right: ArrayNestedView[]\n) {\n if (left === right) return true\n if (left.length !== right.length) return false\n\n return left.every((view, index) => {\n const other = right[index]\n\n return (\n view.rowIndex === other?.rowIndex &&\n view.columnId === other.columnId &&\n view.title === other.title &&\n view.schema === other.schema &&\n Object.is(view.value, other.value)\n )\n })\n}\n\ntype HumanReviewOverlayCell = TextCell | NumberCell\n\ntype HumanReviewTextOverlayEditorProps = React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n> & {\n overlayOpenRef: React.RefObject<boolean>\n readOnly?: boolean\n}\n\nfunction HumanReviewTextOverlayEditor({\n isHighlighted,\n onFinishedEditing,\n overlayOpenRef,\n readOnly = false,\n validatedSelection,\n value,\n}: HumanReviewTextOverlayEditorProps) {\n const initialValue =\n value.kind === GridCellKind.Number ? value.displayData : value.data\n const [entryValue, setEntryValue] = React.useState(initialValue)\n const latestValueRef = React.useRef(initialValue)\n const finishedRef = React.useRef(false)\n\n const finishEditing = React.useCallback(\n (\n shouldSave: boolean,\n movement: readonly [-1 | 0 | 1, -1 | 0 | 1] = [0, 0]\n ) => {\n if (finishedRef.current) return\n\n finishedRef.current = true\n overlayOpenRef.current = false\n\n if (!shouldSave || readOnly) {\n onFinishedEditing(undefined, movement)\n return\n }\n\n if (value.kind === GridCellKind.Number) {\n const numericValue = Number(latestValueRef.current)\n\n onFinishedEditing(\n {\n ...value,\n data: Number.isFinite(numericValue) ? numericValue : value.data,\n displayData: latestValueRef.current,\n },\n movement\n )\n return\n }\n\n onFinishedEditing(\n {\n ...value,\n data: latestValueRef.current,\n displayData: latestValueRef.current,\n },\n movement\n )\n },\n [onFinishedEditing, overlayOpenRef, readOnly, value]\n )\n\n const handleEntryChange = React.useCallback(\n (event: React.ChangeEvent<HTMLTextAreaElement>) => {\n event.stopPropagation()\n latestValueRef.current = event.target.value\n setEntryValue(event.target.value)\n },\n []\n )\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n event.stopPropagation()\n\n if (event.key === "Escape") {\n event.preventDefault()\n finishEditing(false)\n return\n }\n\n if (event.key === "Tab") {\n event.preventDefault()\n finishEditing(true, [event.shiftKey ? -1 : 1, 0])\n return\n }\n\n if (event.key === "Enter" && !event.shiftKey) {\n event.preventDefault()\n finishEditing(true, [0, 1])\n }\n },\n [finishEditing]\n )\n\n React.useEffect(() => {\n overlayOpenRef.current = true\n\n return () => {\n overlayOpenRef.current = false\n }\n }, [overlayOpenRef])\n\n React.useEffect(() => {\n const handlePointerOutside = (event: PointerEvent | MouseEvent) => {\n const input = document.querySelector<HTMLTextAreaElement>(".gdg-input")\n const overlayRoot = input?.closest(".gdg-clip-region")\n\n if (!overlayRoot || overlayRoot.contains(event.target as Node | null)) {\n return\n }\n\n finishEditing(true)\n }\n\n document.addEventListener("pointerdown", handlePointerOutside, true)\n document.addEventListener("contextmenu", handlePointerOutside, true)\n\n return () => {\n document.removeEventListener("pointerdown", handlePointerOutside, true)\n document.removeEventListener("contextmenu", handlePointerOutside, true)\n }\n }, [finishEditing])\n\n return (\n <TextCellEntry\n autoFocus={!readOnly}\n disabled={readOnly}\n highlight={isHighlighted}\n value={entryValue}\n validatedSelection={validatedSelection}\n altNewline\n onChange={handleEntryChange}\n onKeyDown={handleKeyDown}\n />\n )\n}\n\nfunction getFieldIcon(type: SchemaPropertyType) {\n if (type === "number" || type === "integer") return InputNumericGlyph\n if (type === "boolean") return TextCheckGlyph\n if (type === "array") return SecondBracketGlyph\n if (type === "object") return SourceCodeSquareGlyph\n return InputTextGlyph\n}\n\nfunction HumanReviewValueInput({\n readOnly = false,\n schema,\n value,\n onChange,\n}: {\n readOnly?: boolean\n schema: ReviewFieldSchema\n value: JsonPrimitive\n onChange: (value: JsonPrimitive) => void\n}) {\n if (schema.enum?.length) {\n return (\n <span className="relative inline-flex w-full rounded-lg border border-input bg-background text-sm text-foreground shadow-xs/5 dark:bg-input/32">\n <select\n disabled={readOnly}\n value={value === null ? "" : String(value)}\n onChange={(event) => onChange(event.target.value)}\n className="h-8.5 w-full appearance-none rounded-[inherit] bg-transparent px-3 text-sm outline-none sm:h-7.5"\n >\n {schema.enum.map((option) => (\n <option key={String(option)} value={String(option)}>\n {String(option)}\n </option>\n ))}\n </select>\n </span>\n )\n }\n\n if (schema.type === "number" || schema.type === "integer") {\n return (\n <Input\n nativeInput\n readOnly={readOnly}\n type="number"\n value={value === null ? "" : String(value)}\n onChange={(event) => {\n const nextValue = event.currentTarget.value\n onChange(nextValue === "" ? null : Number(nextValue))\n }}\n />\n )\n }\n\n if (schema.type === "boolean") {\n return (\n <div className="grid grid-cols-2 gap-1 rounded-lg bg-muted p-0.5">\n {[true, false].map((option) => (\n <Button\n key={String(option)}\n type="button"\n size="sm"\n variant={value === option ? "outline" : "ghost"}\n className={cn(\n "h-7 shadow-none",\n value === option && "bg-background dark:bg-input"\n )}\n disabled={readOnly}\n onClick={() => onChange(option)}\n >\n {option ? "True" : "False"}\n </Button>\n ))}\n </div>\n )\n }\n\n return (\n <Input\n nativeInput\n readOnly={readOnly}\n value={value === null ? "" : String(value)}\n onChange={(event) => onChange(event.currentTarget.value)}\n />\n )\n}\n\nfunction getArrayItemSchema(schema: ReviewFieldSchema): ReviewFieldSchema {\n return schema.items ?? { type: "string" }\n}\n\nfunction isComplexSchema(schema: ReviewFieldSchema) {\n return schema.type === "object" || schema.type === "array"\n}\n\nfunction summarizeComplexValue(value: JsonValue) {\n if (isJsonArray(value)) return `${value.length} items`\n if (isJsonObject(value)) return `${Object.keys(value).length} fields`\n return formatValue(value)\n}\n\nfunction getCellValueForArrayColumn(\n rowValue: JsonValue,\n itemSchema: ReviewFieldSchema,\n columnId: string\n) {\n if (itemSchema.type === "object") {\n return getObjectValue(rowValue, columnId)\n }\n\n return rowValue\n}\n\nfunction getCellSchemaForArrayColumn(\n itemSchema: ReviewFieldSchema,\n columnId: string\n) {\n if (itemSchema.type === "object") {\n return itemSchema.properties?.[columnId] ?? { type: "string" }\n }\n\n return itemSchema\n}\n\nfunction applyPrimitiveEdit(\n schema: ReviewFieldSchema,\n value: EditableGridCell\n): JsonValue | undefined {\n if (schema.type === "boolean" && value.kind === GridCellKind.Boolean) {\n return value.data\n }\n\n if (\n (schema.type === "number" || schema.type === "integer") &&\n value.kind === GridCellKind.Number\n ) {\n return value.data ?? null\n }\n\n if (value.kind === GridCellKind.Text) {\n if (schema.type === "number" || schema.type === "integer") {\n return value.data.trim() === "" ? null : Number(value.data)\n }\n\n return value.data\n }\n\n return undefined\n}\n\ntype ArrayNestedView = {\n rowIndex: number\n columnId: string\n title: string\n schema: ReviewFieldSchema\n value: JsonValue\n}\n\ntype ArrayReviewSide = "actual" | "expected"\n\ntype SyncedArrayNestedView = {\n activeSide: ArrayReviewSide | null\n stack: ArrayNestedView[]\n}\n\ntype SyncedArraySelection = {\n activeSide: ArrayReviewSide | null\n depth: number\n gridSelection: GridSelection\n}\n\nexport type HumanReviewTheme = "light" | "dark"\n\nconst EMPTY_SYNCED_ARRAY_NESTED_VIEW: SyncedArrayNestedView = {\n activeSide: null,\n stack: [],\n}\n\nconst EMPTY_SYNCED_ARRAY_SELECTION: SyncedArraySelection = {\n activeSide: null,\n depth: 0,\n gridSelection: emptyGridSelection,\n}\n\nfunction setNestedArrayValue({\n value,\n schema,\n nestedStack,\n nextNestedValue,\n}: {\n value: JsonValue\n schema: ReviewFieldSchema\n nestedStack: ArrayNestedView[]\n nextNestedValue: JsonValue\n}): JsonValue {\n const [currentView, ...remainingViews] = nestedStack\n\n if (!currentView) return nextNestedValue\n\n const itemSchema = getArrayItemSchema(schema)\n const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n const cellSchema = getCellSchemaForArrayColumn(\n itemSchema,\n currentView.columnId\n )\n const currentCellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n currentView.columnId\n )\n const nextCellValue: JsonValue = remainingViews.length\n ? setNestedArrayValue({\n value: currentCellValue,\n schema: cellSchema,\n nestedStack: remainingViews,\n nextNestedValue,\n })\n : nextNestedValue\n const nextRowValue: JsonValue =\n itemSchema.type === "object"\n ? setObjectValue(rowValue, currentView.columnId, nextCellValue)\n : nextCellValue\n\n return setArrayItemValue(value, currentView.rowIndex, nextRowValue)\n}\n\nfunction getNestedArrayValue({\n value,\n schema,\n nestedStack,\n}: {\n value: JsonValue\n schema: ReviewFieldSchema\n nestedStack: ArrayNestedView[]\n}): JsonValue {\n const [currentView, ...remainingViews] = nestedStack\n\n if (!currentView) return value\n\n const itemSchema = getArrayItemSchema(schema)\n const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n const cellSchema = getCellSchemaForArrayColumn(\n itemSchema,\n currentView.columnId\n )\n const cellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n currentView.columnId\n )\n\n if (!remainingViews.length) return cellValue\n\n return getNestedArrayValue({\n value: cellValue,\n schema: cellSchema,\n nestedStack: remainingViews,\n })\n}\n\nfunction HumanReviewArrayValueGrid({\n activeNestedSide = null,\n activeSelectionSide = null,\n label,\n nestedStackBaseDepth = 0,\n readOnly = false,\n schema,\n selectionDepth = 0,\n sharedGridSelection,\n sharedNestedStack,\n value,\n viewSide = "expected",\n metadataPath,\n onChange,\n onGridSelectionChange,\n onLocationHover,\n onNestedStackChange,\n resolveArrayItemMetadataPath,\n resolveLocation,\n}: {\n activeNestedSide?: ArrayReviewSide | null\n activeSelectionSide?: ArrayReviewSide | null\n label: string\n nestedStackBaseDepth?: number\n readOnly?: boolean\n schema: ReviewFieldSchema\n selectionDepth?: number\n sharedGridSelection?: GridSelection\n sharedNestedStack?: ArrayNestedView[]\n value: JsonValue\n viewSide?: ArrayReviewSide\n metadataPath?: string\n onChange?: (value: JsonValue) => void\n onGridSelectionChange?: (\n selection: GridSelection,\n side: ArrayReviewSide,\n depth: number\n ) => void\n onNestedStackChange?: (\n stack: ArrayNestedView[],\n side: ArrayReviewSide\n ) => void\n onLocationHover?: (location?: ReviewLocation) => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n}) {\n const rows = getArrayValue(value)\n const itemSchema = getArrayItemSchema(schema)\n const gridTheme = useHumanReviewGridTheme()\n const isDark = useIsDarkTheme()\n const [localNestedStack, setLocalNestedStack] = React.useState<\n ArrayNestedView[]\n >([])\n const [localGridSelection, setLocalGridSelection] =\n React.useState<GridSelection>(emptyGridSelection)\n const fastTextOverlayOpenRef = React.useRef(false)\n const nestedStack = sharedNestedStack ?? localNestedStack\n const visibleNestedStack = nestedStack.slice(nestedStackBaseDepth)\n const activeNestedView = visibleNestedStack[0] ?? null\n const activeNestedValue = activeNestedView\n ? getNestedArrayValue({\n value,\n schema,\n nestedStack: [activeNestedView],\n })\n : null\n const isActiveNestedSource =\n Boolean(activeNestedView) && activeNestedSide === viewSide\n const isMirroredNestedTarget =\n Boolean(activeNestedView) &&\n activeNestedSide !== null &&\n activeNestedSide !== viewSide\n const blueCellText = isDark ? "rgb(147, 197, 253)" : "rgb(37, 99, 235)"\n const selectedCellBackground = isDark\n ? "rgba(37, 99, 235, 0.2)"\n : "rgba(219, 234, 254, 0.85)"\n const mirroredCellBackground = isDark\n ? "rgba(167, 139, 250, 0.18)"\n : "rgba(237, 233, 254, 0.9)"\n const mirroredHighlightRegions = React.useMemo<\n React.ComponentProps<typeof DataEditor>["highlightRegions"]\n >(() => {\n if (\n !activeSelectionSide ||\n activeSelectionSide === viewSide ||\n selectionDepth !== nestedStackBaseDepth\n ) {\n return undefined\n }\n\n const ranges = getGridSelectionRanges(sharedGridSelection)\n if (!ranges.length) return undefined\n\n return ranges.map((range) => ({\n color: mirroredCellBackground,\n range,\n style: "dashed" as const,\n }))\n }, [\n activeSelectionSide,\n mirroredCellBackground,\n nestedStackBaseDepth,\n selectionDepth,\n sharedGridSelection,\n viewSide,\n ])\n\n const setNestedStack = React.useCallback(\n (\n updater:\n | ArrayNestedView[]\n | ((current: ArrayNestedView[]) => ArrayNestedView[])\n ) => {\n if (onNestedStackChange) {\n const nextStack =\n typeof updater === "function" ? updater(nestedStack) : updater\n\n onNestedStackChange(nextStack, viewSide)\n return\n }\n\n setLocalNestedStack(updater)\n },\n [nestedStack, onNestedStackChange, viewSide]\n )\n\n const handleGridSelectionChange = React.useCallback(\n (selection: GridSelection) => {\n flushSync(() => {\n setLocalGridSelection((current) =>\n areGridSelectionsEqual(current, selection) ? current : selection\n )\n })\n\n if (onGridSelectionChange) {\n if (\n activeSelectionSide === viewSide &&\n sharedGridSelection &&\n areGridSelectionsEqual(sharedGridSelection, selection)\n ) {\n return\n }\n\n React.startTransition(() => {\n onGridSelectionChange(selection, viewSide, nestedStackBaseDepth)\n })\n return\n }\n },\n [\n activeSelectionSide,\n nestedStackBaseDepth,\n onGridSelectionChange,\n sharedGridSelection,\n viewSide,\n ]\n )\n\n const columns = React.useMemo<GridColumn[]>(() => {\n if (itemSchema.type === "object") {\n const propertyEntries = Object.entries(itemSchema.properties ?? {})\n\n if (propertyEntries.length) {\n return propertyEntries.map(([key, propertySchema]) => ({\n id: key,\n title: propertySchema.title ?? key,\n width: isComplexSchema(propertySchema) ? 148 : 132,\n }))\n }\n }\n\n return [\n {\n id: "value",\n title: itemSchema.title ?? "Value",\n width: isComplexSchema(itemSchema) ? 148 : 180,\n },\n ]\n }, [itemSchema])\n\n const getCellContent = React.useCallback(\n ([col, row]: Item): GridCell => {\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n const cellValue = getCellValueForArrayColumn(\n rowValue,\n itemSchema,\n columnId\n )\n const matchedNestedCell =\n activeNestedView?.rowIndex === row &&\n activeNestedView.columnId === columnId\n const nestedCellTheme: Partial<Theme> | undefined = matchedNestedCell\n ? {\n bgCell: isMirroredNestedTarget\n ? mirroredCellBackground\n : selectedCellBackground,\n textDark: blueCellText,\n }\n : undefined\n\n if (isComplexSchema(cellSchema)) {\n return {\n kind: GridCellKind.Text,\n data: summarizeComplexValue(cellValue),\n displayData: summarizeComplexValue(cellValue),\n allowOverlay: false,\n readonly: true,\n cursor: "pointer",\n activationBehaviorOverride: "double-click",\n themeOverride: {\n textDark: blueCellText,\n ...(nestedCellTheme ?? {}),\n },\n }\n }\n\n if (cellSchema.type === "boolean") {\n return {\n kind: GridCellKind.Boolean,\n data: typeof cellValue === "boolean" ? cellValue : false,\n allowOverlay: false,\n readonly: readOnly,\n }\n }\n\n if (cellSchema.type === "number" || cellSchema.type === "integer") {\n return {\n kind: GridCellKind.Number,\n data: typeof cellValue === "number" ? cellValue : undefined,\n displayData: typeof cellValue === "number" ? String(cellValue) : "",\n allowOverlay: true,\n readonly: false,\n }\n }\n\n return {\n kind: GridCellKind.Text,\n data:\n cellValue === null ||\n isJsonObject(cellValue) ||\n isJsonArray(cellValue)\n ? ""\n : String(cellValue),\n displayData:\n cellValue === null ||\n isJsonObject(cellValue) ||\n isJsonArray(cellValue)\n ? ""\n : String(cellValue),\n allowOverlay: true,\n readonly: false,\n }\n },\n [\n activeNestedView,\n blueCellText,\n columns,\n isMirroredNestedTarget,\n itemSchema,\n mirroredCellBackground,\n readOnly,\n rows,\n selectedCellBackground,\n ]\n )\n\n const updateCellValue = React.useCallback(\n ([col, row]: Item, nextCell: EditableGridCell) => {\n if (readOnly || !onChange) return\n\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n const nextValue = applyPrimitiveEdit(cellSchema, nextCell)\n\n if (nextValue === undefined) return\n\n const nextRowValue =\n itemSchema.type === "object"\n ? setObjectValue(rowValue, columnId, nextValue)\n : nextValue\n\n onChange(setArrayItemValue(value, row, nextRowValue))\n },\n [columns, itemSchema, onChange, readOnly, rows, value]\n )\n const provideEditor = React.useCallback<\n NonNullable<React.ComponentProps<typeof DataEditor>["provideEditor"]>\n >(\n (cell) => {\n if (\n cell.kind !== GridCellKind.Text &&\n cell.kind !== GridCellKind.Number\n ) {\n return undefined\n }\n\n return {\n editor: (props) => {\n if (\n props.value.kind !== GridCellKind.Text &&\n props.value.kind !== GridCellKind.Number\n ) {\n return null\n }\n\n return (\n <HumanReviewTextOverlayEditor\n {...(props as React.ComponentProps<\n ProvideEditorComponent<HumanReviewOverlayCell>\n >)}\n overlayOpenRef={fastTextOverlayOpenRef}\n readOnly={readOnly}\n />\n )\n },\n }\n },\n [readOnly]\n )\n const handleOutsideClick = React.useCallback(\n () => !fastTextOverlayOpenRef.current,\n []\n )\n const handleItemHovered = React.useCallback(\n (args: GridMouseEventArgs) => {\n if (!onLocationHover || !resolveLocation || !metadataPath) return\n\n if (args.kind !== "cell") {\n onLocationHover(undefined)\n return\n }\n\n const [col, row] = args.location\n const column = columns[col]\n const rowValue = rows[row]\n if (!column || rowValue === undefined) {\n onLocationHover(undefined)\n return\n }\n\n const columnId = String(column.id ?? "value")\n const rowMetadataPath = resolveArrayItemMetadataPath\n ? resolveArrayItemMetadataPath(metadataPath, row, rowValue)\n : `${metadataPath}[${row}]`\n if (!rowMetadataPath) {\n onLocationHover(undefined)\n return\n }\n\n const propertyMetadataPath =\n itemSchema.type === "object"\n ? `${rowMetadataPath}.${columnId}`\n : rowMetadataPath\n\n onLocationHover(\n resolveLocation(propertyMetadataPath) ??\n resolveLocation(rowMetadataPath)\n )\n },\n [\n columns,\n itemSchema.type,\n metadataPath,\n onLocationHover,\n resolveArrayItemMetadataPath,\n resolveLocation,\n rows,\n ]\n )\n\n const openNestedCell = React.useCallback(\n ([col, row]: Item) => {\n const column = columns[col]\n const columnId = String(column?.id ?? "value")\n const rowValue = rows[row] ?? null\n const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n\n if (!isComplexSchema(cellSchema)) return\n\n setNestedStack((current) => {\n const nextView = {\n rowIndex: row,\n columnId,\n title: `${column?.title ?? columnId} / row ${row + 1}`,\n schema: cellSchema,\n value: getCellValueForArrayColumn(rowValue, itemSchema, columnId),\n }\n const currentView = current[nestedStackBaseDepth]\n\n if (\n currentView?.rowIndex === nextView.rowIndex &&\n currentView.columnId === nextView.columnId\n ) {\n return current\n }\n\n return [...current.slice(0, nestedStackBaseDepth), nextView]\n })\n },\n [columns, itemSchema, nestedStackBaseDepth, rows, setNestedStack]\n )\n\n const updateNestedValue = React.useCallback(\n (nextNestedValue: JsonValue) => {\n if (!activeNestedView || readOnly || !onChange) return\n\n onChange(\n setNestedArrayValue({\n value,\n schema,\n nestedStack: visibleNestedStack.slice(0, 1),\n nextNestedValue,\n })\n )\n setNestedStack((current) =>\n current.map((view, index) =>\n index === nestedStackBaseDepth\n ? { ...view, value: nextNestedValue }\n : view\n )\n )\n },\n [\n activeNestedView,\n nestedStackBaseDepth,\n onChange,\n readOnly,\n schema,\n setNestedStack,\n value,\n visibleNestedStack,\n ]\n )\n\n return (\n <div\n onMouseLeave={() => onLocationHover?.(undefined)}\n className={cn(\n "relative overflow-hidden rounded-md border bg-background transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:shadow-[0_0_0_1px_rgb(59_130_246_/_8%)] hover:border-blue-500/50",\n isActiveNestedSource &&\n "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_10%)]"\n )}\n >\n <div>\n <div className="flex h-8 items-center justify-between gap-2 border-b px-2 text-[11px] font-medium text-muted-foreground">\n <span>{label}</span>\n <span>{rows.length} rows</span>\n </div>\n <div className="h-[220px]">\n <DataEditor\n columns={columns}\n rows={rows.length}\n getCellContent={getCellContent}\n cellActivationBehavior="double-click"\n gridSelection={localGridSelection}\n highlightRegions={mirroredHighlightRegions}\n onCellEdited={updateCellValue}\n onCellActivated={openNestedCell}\n onGridSelectionChange={handleGridSelectionChange}\n onItemHovered={handleItemHovered}\n provideEditor={provideEditor}\n isOutsideClick={handleOutsideClick}\n rowMarkers="number"\n smoothScrollX\n smoothScrollY\n theme={gridTheme}\n width="100%"\n height="100%"\n rowHeight={32}\n headerHeight={34}\n />\n </div>\n </div>\n {activeNestedView ? (\n <div className="absolute inset-0 z-10 flex flex-col bg-background">\n <div className="flex h-8 items-center gap-2 border-b px-2">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="size-6 text-muted-foreground"\n onClick={() =>\n setNestedStack((current) =>\n current.slice(\n 0,\n Math.max(nestedStackBaseDepth, current.length - 1)\n )\n )\n }\n aria-label="Back to parent array"\n >\n <IconPlaceholder\n lucide="ChevronLeft"\n tabler="IconChevronLeft"\n hugeicons="ArrowLeft01Icon"\n phosphor="CaretLeftIcon"\n remixicon="RiArrowLeftSLine"\n className="size-3.5"\n />\n </Button>\n <div className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">\n {activeNestedView.title}\n </div>\n </div>\n <div className="min-h-0 flex-1 overflow-auto p-2">\n {activeNestedView.schema.type === "array" ? (\n <HumanReviewArrayValueGrid\n label={\n activeNestedView.schema.title ?? activeNestedView.columnId\n }\n nestedStackBaseDepth={nestedStackBaseDepth + 1}\n readOnly={readOnly}\n schema={activeNestedView.schema}\n sharedGridSelection={sharedGridSelection}\n sharedNestedStack={sharedNestedStack}\n value={activeNestedValue}\n viewSide={viewSide}\n activeNestedSide={activeNestedSide}\n activeSelectionSide={activeSelectionSide}\n selectionDepth={selectionDepth}\n onChange={updateNestedValue}\n onGridSelectionChange={onGridSelectionChange}\n onNestedStackChange={onNestedStackChange}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n ) : (\n <HumanReviewObjectValueEditor\n schema={activeNestedView.schema}\n value={activeNestedValue}\n originalValue={activeNestedValue}\n readOnly={readOnly}\n onChange={updateNestedValue}\n />\n )}\n </div>\n </div>\n ) : null}\n </div>\n )\n}\n\nfunction HumanReviewObjectValueEditor({\n schema,\n value,\n originalValue,\n readOnly = false,\n onChange,\n}: {\n schema: ReviewFieldSchema\n value: JsonValue\n originalValue: JsonValue\n readOnly?: boolean\n onChange: (value: JsonValue) => void\n}) {\n const propertyEntries = Object.entries(schema.properties ?? {})\n\n if (!propertyEntries.length) {\n return (\n <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n No properties\n </div>\n )\n }\n\n return (\n <div className="space-y-2">\n {propertyEntries.map(([propertyKey, propertySchema]) => (\n <HumanReviewFieldCard\n key={propertyKey}\n field={{\n key: propertyKey,\n schema: propertySchema,\n actual: getObjectValue(originalValue, propertyKey),\n expected: getObjectValue(originalValue, propertyKey),\n }}\n value={getObjectValue(value, propertyKey)}\n originalValue={getObjectValue(originalValue, propertyKey)}\n readOnly={readOnly}\n onChange={(childValue) =>\n !readOnly &&\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onUndo={() =>\n !readOnly &&\n onChange(\n setObjectValue(\n value,\n propertyKey,\n getObjectValue(originalValue, propertyKey)\n )\n )\n }\n onSetNull={() =>\n !readOnly && onChange(setObjectValue(value, propertyKey, null))\n }\n />\n ))}\n </div>\n )\n}\n\ntype HumanReviewFieldCardProps = {\n field: ReviewField\n value: JsonValue\n originalValue: JsonValue\n active?: boolean\n activeFieldKey?: string\n readOnly?: boolean\n showExpected?: boolean\n onChange: (value: JsonValue) => void\n onFieldFocus?: (field: ReviewField) => void\n onLocationHover?: (location?: ReviewLocation) => void\n onUndo: () => void\n onSetNull: () => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n}\n\nfunction areHumanReviewFieldCardPropsEqual(\n previous: HumanReviewFieldCardProps,\n next: HumanReviewFieldCardProps\n) {\n return (\n previous.field === next.field &&\n Object.is(previous.value, next.value) &&\n Object.is(previous.originalValue, next.originalValue) &&\n previous.active === next.active &&\n previous.activeFieldKey === next.activeFieldKey &&\n previous.readOnly === next.readOnly &&\n previous.showExpected === next.showExpected &&\n previous.onFieldFocus === next.onFieldFocus &&\n previous.onLocationHover === next.onLocationHover &&\n previous.resolveArrayItemMetadataPath ===\n next.resolveArrayItemMetadataPath &&\n previous.resolveLocation === next.resolveLocation\n )\n}\n\nconst HumanReviewFieldCard = React.memo(\n HumanReviewFieldCardBase,\n areHumanReviewFieldCardPropsEqual\n)\n\nfunction HumanReviewFieldCardBase({\n field,\n value,\n originalValue,\n active,\n activeFieldKey,\n readOnly = false,\n showExpected = true,\n onChange,\n onFieldFocus,\n onLocationHover,\n onUndo,\n onSetNull,\n resolveArrayItemMetadataPath,\n resolveLocation,\n}: HumanReviewFieldCardProps) {\n const isExpectedEditable = showExpected && !readOnly\n const modified = showExpected && !jsonValuesEqual(value, originalValue)\n const fieldTypeIcon = React.createElement(getFieldIcon(field.schema.type), {\n className: "size-3.5",\n })\n const propertyEntries = Object.entries(field.schema.properties ?? {})\n const [syncedArrayNestedView, setSyncedArrayNestedView] =\n React.useState<SyncedArrayNestedView>(EMPTY_SYNCED_ARRAY_NESTED_VIEW)\n const [syncedArraySelection, setSyncedArraySelection] =\n React.useState<SyncedArraySelection>(EMPTY_SYNCED_ARRAY_SELECTION)\n const updateSyncedArrayNestedView = React.useCallback(\n (stack: ArrayNestedView[], side: ArrayReviewSide) => {\n const activeSide = stack.length ? side : null\n\n setSyncedArrayNestedView((current) =>\n current.activeSide === activeSide &&\n areArrayNestedViewsEqual(current.stack, stack)\n ? current\n : {\n activeSide,\n stack,\n }\n )\n },\n []\n )\n const updateSyncedArraySelection = React.useCallback(\n (gridSelection: GridSelection, side: ArrayReviewSide, depth: number) => {\n const activeSide = gridSelection.current ? side : null\n\n setSyncedArraySelection((current) =>\n current.activeSide === activeSide &&\n current.depth === depth &&\n areGridSelectionsEqual(current.gridSelection, gridSelection)\n ? current\n : {\n activeSide,\n depth,\n gridSelection,\n }\n )\n },\n []\n )\n const focusAndHoverField = React.useCallback(() => {\n onFieldFocus?.(field)\n onLocationHover?.(getReviewFieldLocation(field, resolveLocation))\n }, [field, onFieldFocus, onLocationHover, resolveLocation])\n\n return (\n <div\n tabIndex={0}\n onFocusCapture={focusAndHoverField}\n onMouseEnter={focusAndHoverField}\n onMouseLeave={() => onLocationHover?.(undefined)}\n className={cn(\n "rounded-lg border bg-background p-3 transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:bg-blue-500/5 hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",\n active &&\n "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_8%)]"\n )}\n >\n <div className="mb-3 flex min-h-8 items-start justify-between gap-3">\n <div className="min-w-0">\n <div className="flex min-w-0 items-center gap-2">\n <div className="min-w-0">\n <div className="truncate text-sm font-medium">\n {field.schema.title ?? field.key}\n </div>\n </div>\n <span\n className={cn(\n "size-2 shrink-0 rounded-full bg-amber-400",\n !modified && "opacity-0"\n )}\n />\n </div>\n <div className="truncate text-xs text-muted-foreground">\n {field.key}\n </div>\n </div>\n <div className="flex shrink-0 items-center gap-1">\n {isExpectedEditable && modified ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="text-muted-foreground"\n onClick={onUndo}\n aria-label={`Undo ${field.key}`}\n >\n <IconPlaceholder\n lucide="Undo2"\n tabler="IconArrowBackUp"\n hugeicons="Undo02Icon"\n phosphor="ArrowUUpLeftIcon"\n remixicon="RiArrowGoBackLine"\n className="size-4"\n />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Revert changes</TooltipContent>\n </Tooltip>\n ) : null}\n {isExpectedEditable ? (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n className="text-muted-foreground"\n onClick={onSetNull}\n aria-label={`Set ${field.key} to null`}\n >\n <IconPlaceholder\n lucide="CircleX"\n tabler="IconCircleX"\n hugeicons="CancelCircleIcon"\n phosphor="XCircleIcon"\n remixicon="RiCloseCircleLine"\n className="size-4"\n />\n </Button>\n </TooltipTrigger>\n <TooltipContent>Set to NULL</TooltipContent>\n </Tooltip>\n ) : null}\n <div className="flex h-6 items-center gap-1 rounded-md border bg-muted/50 px-1.5 text-xs text-muted-foreground">\n {fieldTypeIcon}\n {field.schema.type}\n </div>\n </div>\n </div>\n {field.schema.type === "object" ? (\n <div className="rounded-md border bg-muted/25 p-2">\n <div className="mb-2 flex items-center justify-between gap-3 text-[11px] font-medium text-muted-foreground">\n <span>Properties</span>\n <span>{propertyEntries.length} fields</span>\n </div>\n <div className="space-y-2">\n {propertyEntries.length ? (\n propertyEntries.map(([propertyKey, schema]) => {\n const childField: ReviewField = {\n key: `${field.key}.${propertyKey}`,\n schema,\n actual: getObjectValue(field.actual, propertyKey),\n expected: getObjectValue(originalValue, propertyKey),\n metadataPath: `${field.metadataPath ?? field.key}.${propertyKey}`,\n }\n\n return (\n <HumanReviewFieldCard\n key={childField.key}\n field={childField}\n value={getObjectValue(value, propertyKey)}\n originalValue={childField.expected}\n active={childField.key === activeFieldKey}\n activeFieldKey={activeFieldKey}\n readOnly={readOnly}\n showExpected={showExpected}\n onChange={(childValue) =>\n onChange(setObjectValue(value, propertyKey, childValue))\n }\n onFieldFocus={onFieldFocus}\n onLocationHover={onLocationHover}\n onUndo={() =>\n onChange(\n setObjectValue(value, propertyKey, childField.expected)\n )\n }\n onSetNull={() =>\n onChange(setObjectValue(value, propertyKey, null))\n }\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n )\n })\n ) : (\n <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n No properties\n </div>\n )}\n </div>\n </div>\n ) : field.schema.type === "array" ? (\n <div className="grid gap-2">\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Actual"\n metadataPath={field.metadataPath ?? field.key}\n readOnly\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n schema={field.schema}\n selectionDepth={syncedArraySelection.depth}\n sharedGridSelection={syncedArraySelection.gridSelection}\n sharedNestedStack={syncedArrayNestedView.stack}\n value={field.actual}\n viewSide="actual"\n onGridSelectionChange={updateSyncedArraySelection}\n onLocationHover={onLocationHover}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n {showExpected ? (\n <HumanReviewArrayValueGrid\n activeNestedSide={syncedArrayNestedView.activeSide}\n activeSelectionSide={syncedArraySelection.activeSide}\n label="Expected"\n metadataPath={field.metadataPath ?? field.key}\n readOnly={readOnly}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n schema={field.schema}\n selectionDepth={syncedArraySelection.depth}\n sharedGridSelection={syncedArraySelection.gridSelection}\n sharedNestedStack={syncedArrayNestedView.stack}\n value={value}\n viewSide="expected"\n onChange={onChange}\n onGridSelectionChange={updateSyncedArraySelection}\n onLocationHover={onLocationHover}\n onNestedStackChange={updateSyncedArrayNestedView}\n />\n ) : null}\n </div>\n ) : (\n <div className={cn("grid gap-2", showExpected && "sm:grid-cols-2")}>\n <div className="rounded-md border bg-muted/30 p-2">\n {field.schema.description ? (\n <p className="mb-2 text-xs text-muted-foreground">\n {field.schema.description}\n </p>\n ) : null}\n <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n Actual\n </div>\n <div className="min-h-7 rounded-md bg-background px-2 py-1.5 text-sm">\n {formatValue(field.actual)}\n </div>\n </div>\n {showExpected ? (\n <div className="rounded-md border bg-muted/30 p-2">\n <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n Expected\n </div>\n <HumanReviewValueInput\n readOnly={readOnly}\n schema={field.schema}\n value={getPrimitiveValue(value)}\n onChange={onChange}\n />\n </div>\n ) : null}\n </div>\n )}\n </div>\n )\n}\n\nexport function HumanReviewHighlight({\n location,\n}: {\n location: ReviewLocation\n}) {\n const area = location.area\n\n return (\n <div\n className={cn(\n "pointer-events-none absolute z-10 border",\n REVIEW_HIGHLIGHT_STYLE\n )}\n style={{\n left: `${area.left}%`,\n top: `${area.top}%`,\n width: `${area.width}%`,\n height: `${area.height}%`,\n }}\n />\n )\n}\n\nexport function JsonDiffView({\n actual,\n expected,\n theme = "light",\n}: {\n actual: JsonObject\n expected: JsonObject\n theme?: HumanReviewTheme\n}) {\n const oldFile = React.useMemo(\n () => ({\n name: "actual.json",\n contents: formatJson(actual),\n lang: "json",\n }),\n [actual]\n )\n const newFile = React.useMemo(\n () => ({\n name: "expected.json",\n contents: formatJson(expected),\n lang: "json",\n }),\n [expected]\n )\n\n return (\n <ScrollAreaVirtualizer\n className="h-full bg-surface/60"\n contentClassName="min-w-full"\n >\n <div className="bounding-box-citations-diff h-full text-xs">\n <MultiFileDiff\n className="block min-w-full"\n oldFile={oldFile}\n newFile={newFile}\n options={{\n diffStyle: "split",\n disableFileHeader: true,\n diffIndicators: "bars",\n hunkSeparators: "line-info-basic",\n overflow: "wrap",\n themeType: theme,\n theme: {\n light: "pierre-light-soft",\n dark: "pierre-dark-soft",\n },\n }}\n />\n </div>\n </ScrollAreaVirtualizer>\n )\n}\n\nexport function JsonCodeView({\n name = "actual.json",\n theme = "light",\n value,\n}: {\n name?: string\n theme?: HumanReviewTheme\n value: JsonValue\n}) {\n const file = React.useMemo(() => {\n const contents = formatJson(value)\n\n return {\n name,\n contents,\n lang: "json" as const,\n cacheKey: contents,\n }\n }, [name, value])\n\n return (\n <div\n data-rehype-pretty-code-figure\n className="relative m-0! h-full overflow-hidden rounded-none! bg-code text-code-foreground"\n >\n <WorkerPoolContextProvider\n poolOptions={CODE_WORKER_POOL_OPTIONS}\n highlighterOptions={CODE_HIGHLIGHTER_OPTIONS}\n >\n <ScrollAreaVirtualizer\n key={`${file.cacheKey}:${theme}`}\n className="h-full min-w-0"\n contentClassName="min-w-full"\n >\n <File\n key={`${file.cacheKey}:${theme}`}\n className="block min-w-full"\n file={file}\n metrics={CODE_VIRTUAL_FILE_METRICS}\n style={CODE_FILE_THEME}\n options={{\n disableFileHeader: true,\n overflow: "scroll",\n themeType: theme,\n theme: {\n light: "pierre-light-soft",\n dark: "pierre-dark-soft",\n },\n }}\n />\n </ScrollAreaVirtualizer>\n </WorkerPoolContextProvider>\n </div>\n )\n}\n\nexport function HumanReviewPanel({\n fields = REVIEW_FIELDS,\n activeFieldKey,\n className,\n onFieldFocus,\n onLocationHover,\n resolveArrayItemMetadataPath,\n resolveLocation,\n showExpected = true,\n theme = "light",\n}: {\n fields?: ReviewField[]\n activeFieldKey?: string\n className?: string\n onFieldFocus?: (field: ReviewField) => void\n onLocationHover?: (location?: ReviewLocation) => void\n resolveArrayItemMetadataPath?: (\n metadataPath: string,\n rowIndex: number,\n rowValue: JsonValue\n ) => string | undefined\n resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n showExpected?: boolean\n theme?: HumanReviewTheme\n} = {}) {\n const [activeTab, setActiveTab] = React.useState("form")\n const actualValues = React.useMemo(\n () => valuesFromFields(fields, "actual"),\n [fields]\n )\n const initialExpectedValues = React.useMemo(\n () => valuesFromFields(fields, "expected"),\n [fields]\n )\n const [expected, setExpected] = React.useState<JsonObject>(\n initialExpectedValues\n )\n\n const [previousExpectedValues, setPreviousExpectedValues] = React.useState(\n initialExpectedValues\n )\n if (!Object.is(previousExpectedValues, initialExpectedValues)) {\n setPreviousExpectedValues(initialExpectedValues)\n setExpected(initialExpectedValues)\n }\n\n const updateValue = React.useCallback((key: string, value: JsonValue) => {\n setExpected((current) =>\n Object.is(current[key], value) ? current : { ...current, [key]: value }\n )\n }, [])\n\n return (\n <TooltipProvider delay={200}>\n <Tabs\n value={activeTab}\n onValueChange={setActiveTab}\n className={cn("flex h-[560px] flex-col gap-0 bg-background", className)}\n >\n <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">\n <TabsList className="h-8 sm:h-7">\n <TabsTrigger value="form" className="h-7 sm:h-6">\n <IconPlaceholder\n lucide="CaptionsIcon"\n tabler="IconTextCaption"\n hugeicons="TextCheckIcon"\n phosphor="TextTIcon"\n remixicon="RiTextWrap"\n className="size-4"\n />\n Form\n </TabsTrigger>\n <TabsTrigger value="json" className="h-7 sm:h-6">\n <IconPlaceholder\n lucide="SquareCode"\n tabler="IconSourceCode"\n hugeicons="SourceCodeSquareIcon"\n phosphor="CodeIcon"\n remixicon="RiCodeBlock"\n className="size-4"\n />\n JSON\n </TabsTrigger>\n </TabsList>\n </div>\n <TabsContent value="form" keepMounted className="min-h-0 flex-1">\n <ScrollArea className="h-full" scrollFade>\n <div className="space-y-3 p-3">\n {fields.map((field) => (\n <HumanReviewFieldCard\n key={field.key}\n field={field}\n value={\n showExpected ? (expected[field.key] ?? null) : field.actual\n }\n originalValue={showExpected ? field.expected : field.actual}\n active={\n field.key === activeFieldKey ||\n activeFieldKey?.startsWith(`${field.key}.`)\n }\n activeFieldKey={activeFieldKey}\n showExpected={showExpected}\n onChange={(value) => updateValue(field.key, value)}\n onFieldFocus={onFieldFocus}\n onLocationHover={onLocationHover}\n onUndo={() => updateValue(field.key, field.expected)}\n onSetNull={() => updateValue(field.key, null)}\n resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n resolveLocation={resolveLocation}\n />\n ))}\n </div>\n </ScrollArea>\n </TabsContent>\n <TabsContent value="json" className="min-h-0 flex-1">\n {showExpected ? (\n <JsonDiffView\n actual={actualValues}\n expected={expected}\n theme={theme}\n />\n ) : (\n <JsonCodeView value={actualValues} theme={theme} />\n )}\n </TabsContent>\n </Tabs>\n </TooltipProvider>\n )\n}\n'export function HumanReviewSource() {return (diff --git a/apps/v4/components/docx-viewer-docs.tsx b/apps/v4/components/docx-viewer-docs.tsxindex 275fc4d..db03063 100644--- a/apps/v4/components/docx-viewer-docs.tsx+++ b/apps/v4/components/docx-viewer-docs.tsx@@ -71,7 +71,7 @@ export function DocxViewerExample() {}`const docxViewerSourceCode =- '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n useDocxComments,\n useDocxEditor,\n useDocxPageLayout,\n useDocxTrackChanges,\n useDocxViewerThumbnails,\n type DocxDocumentTheme,\n type DocxEditorController,\n type DocxPageThumbnailItem,\n type ViewerZoomLevel,\n type ViewerZoomState,\n} from "@extend-ai/react-docx"\nimport { useVirtualizer } from "@tanstack/react-virtual"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { Input } from "@/components/ui/input"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/extend/document-viewer-sidebar"\nimport {\n createDocxCommentCardRenderer,\n createDocxTrackedChangeCardRenderer,\n} from "@/components/extend/docx-annotation-card"\nimport { FileThumbnail } from "@/components/extend/file-thumbnail"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_THUMBNAIL_LIST_PADDING = 16\nconst DOCX_THUMBNAIL_ROW_ESTIMATE = 172\nconst DEFAULT_ZOOM = 50\nconst ZOOM_OPTIONS = [50, 75, 100, 125, 150, 175, 200] as const\nconst ZOOM_MODE_LABELS = {\n "fit-page": "Fit page",\n "fit-width": "Fit width",\n automatic: "Automatic",\n} satisfies Record<Exclude<ViewerZoomLevel, number>, string>\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\nconst DOCX_THUMBNAIL_FOCUS_RING_CLASS =\n "group-focus-visible/docx-thumbnail-sidebar:ring-2 group-focus-visible/docx-thumbnail-sidebar:ring-ring group-focus-visible/docx-thumbnail-sidebar:ring-offset-1 group-focus-visible/docx-thumbnail-sidebar:ring-offset-background"\nconst DOCX_THUMBNAIL_PREFETCH_ROWS = 4\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n sourceUrl: string | undefined\n}\n\ntype DocxActivePageStore = {\n getSnapshot: () => number\n setActivePage: React.Dispatch<React.SetStateAction<number>>\n subscribe: (listener: () => void) => () => void\n}\n\ntype DocxThumbnailRenderWindowState = {\n visiblePageIndexes: number[]\n prefetchPageIndexes: number[]\n}\n\nfunction createDocxActivePageStore(): DocxActivePageStore {\n let activePage = 1\n const listeners = new Set<() => void>()\n\n return {\n getSnapshot: () => activePage,\n setActivePage: (nextPage) => {\n const value =\n typeof nextPage === "function" ? nextPage(activePage) : nextPage\n const normalizedValue = Math.max(1, Math.round(value || 1))\n\n if (normalizedValue === activePage) return\n\n activePage = normalizedValue\n listeners.forEach((listener) => listener())\n },\n subscribe: (listener) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n }\n}\n\nfunction useDocxActivePage(activePageStore: DocxActivePageStore) {\n return React.useSyncExternalStore(\n activePageStore.subscribe,\n activePageStore.getSnapshot,\n activePageStore.getSnapshot\n )\n}\n\nfunction areNumberArraysEqual(left: number[], right: number[]) {\n return (\n left.length === right.length &&\n left.every((value, index) => value === right[index])\n )\n}\n\nasync function loadDocxFile(\n url: string,\n displayFileName: string\n): Promise<File> {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n return new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n}\n\nfunction formatDocumentName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "document.docx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction ensureDocxExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(".docx")\n ? fileName\n : `${fileName}.docx`\n}\n\nfunction downloadBlob(blob: Blob, fileName: string) {\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = fileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nasync function downloadDocxFile({\n file,\n fileName,\n url,\n}: {\n file?: File\n fileName: string\n url?: string\n}) {\n if (file) {\n downloadBlob(file, ensureDocxExtension(fileName))\n return\n }\n\n if (!url) return\n\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to download DOCX (${response.status})`)\n }\n\n downloadBlob(await response.blob(), ensureDocxExtension(fileName))\n}\n\nfunction getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {\n if (direction > 0) {\n return (\n ZOOM_OPTIONS.find((value) => value > currentZoomScale) ?? currentZoomScale\n )\n }\n\n for (let index = ZOOM_OPTIONS.length - 1; index >= 0; index -= 1) {\n const value = ZOOM_OPTIONS[index]\n if (value < currentZoomScale) return value\n }\n\n return currentZoomScale\n}\n\nfunction normalizeDocxZoomLevel(\n value: ViewerZoomLevel | undefined\n): ViewerZoomLevel {\n return value ?? DEFAULT_ZOOM\n}\n\nfunction isZoomMode(value: string): value is Exclude<ViewerZoomLevel, number> {\n return value in ZOOM_MODE_LABELS\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n const [previousIsLoading, setPreviousIsLoading] = React.useState(isLoading)\n\n if (previousIsLoading !== isLoading) {\n setPreviousIsLoading(isLoading)\n setShowSpinner(false)\n }\n\n React.useEffect(() => {\n if (!isLoading) return\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return isLoading && showSpinner\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction isInteractiveViewerTarget(target: EventTarget | null) {\n return (\n target instanceof Element &&\n Boolean(\n target.closest(\n \'a[href], button, input, select, textarea, [contenteditable="true"], [role="button"], [role="link"]\'\n )\n )\n )\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction ViewerLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction DocxFileActionsMenu({\n controlsDisabled,\n downloadDisabled,\n isPreparingDownload,\n isDark,\n onDownload,\n onShowCommentsChange,\n onShowTrackedChangesChange,\n onIsDarkChange,\n onUploadClick,\n showComments,\n showDownloadButton,\n showNightRenderToggle,\n showTrackedChanges,\n showUploadButton,\n}: {\n controlsDisabled: boolean\n downloadDisabled: boolean\n isPreparingDownload: boolean\n isDark: boolean\n onDownload: () => void\n onShowCommentsChange: (checked: boolean) => void\n onShowTrackedChangesChange: (checked: boolean) => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n showComments: boolean\n showDownloadButton: boolean\n showNightRenderToggle: boolean\n showTrackedChanges: boolean\n showUploadButton: boolean\n}) {\n const showFileActions = showDownloadButton || showUploadButton\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open DOCX actions"\n >\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className="size-4"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-52">\n {showNightRenderToggle ? (\n <>\n <DropdownMenuCheckboxItem\n checked={isDark}\n disabled={controlsDisabled}\n variant="switch"\n onCheckedChange={(checked) => onIsDarkChange(checked === true)}\n >\n <span className="flex min-w-0 items-center gap-2">\n <IconPlaceholder\n lucide="Moon"\n tabler="IconMoon"\n hugeicons="Moon02Icon"\n phosphor="MoonIcon"\n remixicon="RiMoonLine"\n className="size-4"\n />\n Dark mode\n </span>\n </DropdownMenuCheckboxItem>\n <DropdownMenuSeparator />\n </>\n ) : null}\n <DropdownMenuCheckboxItem\n checked={showComments}\n disabled={controlsDisabled}\n variant="switch"\n onCheckedChange={(checked) => onShowCommentsChange(checked === true)}\n >\n <span className="flex min-w-0 items-center gap-2">\n <IconPlaceholder\n lucide="MessageSquare"\n tabler="IconMessage"\n hugeicons="Comment01Icon"\n phosphor="ChatIcon"\n remixicon="RiChat1Line"\n className="size-4"\n />\n Comments\n </span>\n </DropdownMenuCheckboxItem>\n <DropdownMenuCheckboxItem\n checked={showTrackedChanges}\n disabled={controlsDisabled}\n variant="switch"\n onCheckedChange={(checked) =>\n onShowTrackedChangesChange(checked === true)\n }\n >\n <span className="flex min-w-0 items-center gap-2">\n <IconPlaceholder\n lucide="FileDiff"\n tabler="IconFileDiff"\n hugeicons="FileDiffIcon"\n phosphor="GitDiffIcon"\n remixicon="RiFileHistoryLine"\n className="size-4"\n />\n Edits\n </span>\n </DropdownMenuCheckboxItem>\n {showFileActions ? <DropdownMenuSeparator /> : null}\n {showDownloadButton ? (\n <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>\n {isPreparingDownload ? (\n <Spinner className="size-4" />\n ) : (\n <IconPlaceholder\n lucide="Download"\n tabler="IconDownload"\n hugeicons="Download01Icon"\n phosphor="DownloadSimpleIcon"\n remixicon="RiDownload2Line"\n className="size-4"\n />\n )}\n Download\n </DropdownMenuItem>\n ) : null}\n {showUploadButton ? (\n <DropdownMenuItem onClick={onUploadClick}>\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction DocxPageNumberControl({\n activePageStore,\n controlsDisabled,\n onPageChange,\n pageCount,\n}: {\n activePageStore: DocxActivePageStore\n controlsDisabled: boolean\n onPageChange: (pageNumber: number) => void\n pageCount: number\n}) {\n const activePage = useDocxActivePage(activePageStore)\n const inputRef = React.useRef<HTMLInputElement>(null)\n const displayPage = pageCount ? activePage : 1\n const [isEditing, setIsEditing] = React.useState(false)\n const [draftPage, setDraftPage] = React.useState(() => String(displayPage))\n\n React.useEffect(() => {\n if (!isEditing) return\n\n inputRef.current?.focus()\n inputRef.current?.select()\n }, [isEditing])\n\n const applyPageDraft = React.useCallback(\n (value: string) => {\n const trimmedValue = value.trim()\n\n if (!trimmedValue) return\n\n const parsedPage = Number(trimmedValue)\n\n if (!Number.isInteger(parsedPage)) return\n\n onPageChange(Math.min(Math.max(parsedPage, 1), Math.max(pageCount, 1)))\n },\n [onPageChange, pageCount]\n )\n\n return (\n <div className="flex items-center text-sm whitespace-nowrap text-primary">\n <span>Page</span>\n {isEditing ? (\n <Input\n ref={inputRef}\n aria-label="Page number"\n inputMode="numeric"\n pattern="[0-9]*"\n size="sm"\n value={draftPage}\n className="mx-1 w-14 min-w-14 rounded-md [&_[data-slot=input]]:text-center"\n onBlur={() => setIsEditing(false)}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) => {\n const nextValue = event.target.value\n\n setDraftPage(nextValue)\n applyPageDraft(nextValue)\n }}\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === "Enter" || event.key === "Escape") {\n event.currentTarget.blur()\n }\n }}\n />\n ) : (\n <Button\n type="button"\n variant="ghost"\n size="sm"\n className="font-normal"\n aria-label={`Current page ${displayPage}. Edit page number`}\n disabled={controlsDisabled || !pageCount}\n onClick={() => {\n setDraftPage(String(displayPage))\n setIsEditing(true)\n }}\n >\n {displayPage}\n </Button>\n )}\n <span>of {pageCount || "-"}</span>\n </div>\n )\n}\n\nfunction DocxToolbar({\n activePageStore,\n controlsDisabled,\n isDark,\n isPreparingDownload,\n onDownload,\n onIsDarkChange,\n onPageChange,\n onShowCommentsChange,\n onShowTrackedChangesChange,\n onToggleSidebar,\n onUploadClick,\n onZoomChange,\n pageCount,\n resolvedZoom,\n showComments,\n showDownloadButton = true,\n showNightRenderToggle,\n showTrackedChanges,\n showUploadButton = true,\n toolbarActions,\n zoomLevel,\n}: {\n activePageStore: DocxActivePageStore\n controlsDisabled: boolean\n isDark: boolean\n isPreparingDownload: boolean\n onDownload: () => void\n onIsDarkChange: (checked: boolean) => void\n onPageChange: (pageNumber: number) => void\n onShowCommentsChange: (checked: boolean) => void\n onShowTrackedChangesChange: (checked: boolean) => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n onZoomChange: (zoomLevel: ViewerZoomLevel) => void\n pageCount: number\n resolvedZoom: number\n showComments: boolean\n showDownloadButton?: boolean\n showNightRenderToggle: boolean\n showTrackedChanges: boolean\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n zoomLevel: ViewerZoomLevel\n}) {\n const canZoomIn = resolvedZoom < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = resolvedZoom > ZOOM_OPTIONS[0]\n const selectValue =\n typeof zoomLevel === "number" ? zoomLevel.toString() : zoomLevel\n const roundedZoom = Number(resolvedZoom.toFixed(2))\n const zoomOptions = ZOOM_OPTIONS.includes(\n roundedZoom as (typeof ZOOM_OPTIONS)[number]\n )\n ? ZOOM_OPTIONS\n : [...ZOOM_OPTIONS, roundedZoom].sort((left, right) => left - right)\n\n return (\n <div className="flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2">\n <TooltipProvider>\n <div className="flex min-w-0 flex-wrap items-center gap-2">\n <ToolbarTooltip label="Toggle thumbnails">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Toggle thumbnails"\n disabled={controlsDisabled}\n onClick={onToggleSidebar}\n >\n <IconPlaceholder\n lucide="PanelLeft"\n tabler="IconLayoutSidebar"\n hugeicons="SidebarLeftIcon"\n phosphor="SidebarIcon"\n remixicon="RiLayoutLeftLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <DocxPageNumberControl\n activePageStore={activePageStore}\n controlsDisabled={controlsDisabled}\n onPageChange={onPageChange}\n pageCount={pageCount}\n />\n </div>\n <div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled || !canZoomOut}\n aria-label="Zoom out"\n onClick={() => onZoomChange(getNextZoomScale(resolvedZoom, -1))}\n >\n <IconPlaceholder\n lucide="CircleMinus"\n tabler="IconCircleMinus"\n hugeicons="MinusSignCircleIcon"\n phosphor="MinusCircleIcon"\n remixicon="RiIndeterminateCircleLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={selectValue}\n onValueChange={(value) => {\n if (value === null) return\n onZoomChange(isZoomMode(value) ? value : Number(value))\n }}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[104px] min-w-[104px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(resolvedZoom)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align="end" alignItemWithTrigger={false}>\n {Object.entries(ZOOM_MODE_LABELS).map(([value, label]) => (\n <SelectItem key={value} value={value}>\n {label}\n </SelectItem>\n ))}\n {zoomOptions.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled || !canZoomIn}\n aria-label="Zoom in"\n onClick={() => onZoomChange(getNextZoomScale(resolvedZoom, 1))}\n >\n <IconPlaceholder\n lucide="CirclePlusIcon"\n tabler="IconCirclePlusFilled"\n hugeicons="PlusSignCircleIcon"\n phosphor="PlusCircleIcon"\n remixicon="RiAddCircleFill"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <DocxFileActionsMenu\n controlsDisabled={controlsDisabled}\n downloadDisabled={controlsDisabled || isPreparingDownload}\n isPreparingDownload={isPreparingDownload}\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onShowCommentsChange={onShowCommentsChange}\n onShowTrackedChangesChange={onShowTrackedChangesChange}\n onUploadClick={onUploadClick}\n showComments={showComments}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showTrackedChanges={showTrackedChanges}\n showUploadButton={showUploadButton}\n />\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="rounded-md bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n isLoading={isLoading}\n hasError={hasError}\n className={cn(\n "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",\n isActive && "shadow-sm"\n )}\n />\n )\n}\n\nfunction DocxThumbnailSidebarList({\n activePage,\n displayFileName,\n isLoadingDocument,\n onSelectPage,\n onThumbnailRenderWindowChange,\n pageCount,\n sidebarOpen,\n thumbnails,\n}: {\n activePage: number\n displayFileName: string\n isLoadingDocument: boolean\n onSelectPage: (pageNumber: number) => void\n onThumbnailRenderWindowChange: (\n renderWindow: DocxThumbnailRenderWindowState\n ) => void\n pageCount: number\n sidebarOpen: boolean\n thumbnails: DocxPageThumbnailItem[]\n}) {\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const thumbnailListboxId = React.useId()\n const visibleThumbnails = React.useMemo(\n () => thumbnails.slice(0, pageCount || 0),\n [pageCount, thumbnails]\n )\n const activeDescendantId =\n activePage > 0 && visibleThumbnails.length\n ? `${thumbnailListboxId}-page-${activePage}`\n : undefined\n const virtualizer = useVirtualizer({\n count: visibleThumbnails.length,\n estimateSize: () => DOCX_THUMBNAIL_ROW_ESTIMATE,\n getItemKey: (index) => visibleThumbnails[index]?.pageIndex ?? index,\n getScrollElement: () => viewportRef.current,\n overscan: 3,\n })\n const virtualItems = virtualizer.getVirtualItems()\n const renderWindowSignature = virtualItems\n .map((virtualRow) => virtualRow.index)\n .join(",")\n\n React.useEffect(() => {\n if (!sidebarOpen || isLoadingDocument || !visibleThumbnails.length) {\n onThumbnailRenderWindowChange({\n prefetchPageIndexes: [],\n visiblePageIndexes: [],\n })\n return\n }\n\n const visiblePageIndexes = virtualItems\n .map((virtualRow) => visibleThumbnails[virtualRow.index]?.pageIndex)\n .filter((pageIndex): pageIndex is number => pageIndex !== undefined)\n\n const firstVirtualIndex = virtualItems[0]?.index ?? 0\n const lastVirtualIndex =\n virtualItems[virtualItems.length - 1]?.index ?? firstVirtualIndex\n const firstPrefetchIndex = Math.max(\n 0,\n firstVirtualIndex - DOCX_THUMBNAIL_PREFETCH_ROWS\n )\n const lastPrefetchIndex = Math.min(\n visibleThumbnails.length - 1,\n lastVirtualIndex + DOCX_THUMBNAIL_PREFETCH_ROWS\n )\n const visiblePageIndexSet = new Set(visiblePageIndexes)\n const prefetchPageIndexes: number[] = []\n\n for (\n let index = firstPrefetchIndex;\n index <= lastPrefetchIndex;\n index += 1\n ) {\n const pageIndex = visibleThumbnails[index]?.pageIndex\n\n if (pageIndex !== undefined && !visiblePageIndexSet.has(pageIndex)) {\n prefetchPageIndexes.push(pageIndex)\n }\n }\n\n onThumbnailRenderWindowChange({\n prefetchPageIndexes,\n visiblePageIndexes,\n })\n }, [\n isLoadingDocument,\n onThumbnailRenderWindowChange,\n renderWindowSignature,\n sidebarOpen,\n visibleThumbnails,\n virtualItems,\n ])\n\n React.useEffect(() => {\n if (!sidebarOpen || activePage < 1 || !visibleThumbnails.length) return\n\n virtualizer.scrollToIndex(\n Math.min(activePage - 1, visibleThumbnails.length - 1),\n { align: "auto" }\n )\n }, [activePage, sidebarOpen, virtualizer, visibleThumbnails.length])\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (pageCount < 1) return\n\n const currentPage = activePage > 0 ? activePage : 1\n let nextPage: number | null = null\n\n if (event.key === "ArrowDown") {\n nextPage = Math.min(pageCount, currentPage + 1)\n } else if (event.key === "ArrowUp") {\n nextPage = Math.max(1, currentPage - 1)\n } else if (event.key === "Home") {\n nextPage = 1\n } else if (event.key === "End") {\n nextPage = pageCount\n }\n\n if (nextPage === null) return\n\n event.preventDefault()\n onSelectPage(nextPage)\n },\n [activePage, onSelectPage, pageCount]\n )\n\n return (\n <ScrollArea\n className="h-full"\n scrollFade\n viewportClassName="group/docx-thumbnail-sidebar focus-visible:ring-0 focus-visible:ring-offset-0"\n viewportProps={{\n "aria-activedescendant": activeDescendantId,\n "aria-busy": isLoadingDocument || undefined,\n "aria-label": "DOCX pages",\n onKeyDown: handleKeyDown,\n onMouseDown: (event) => {\n event.currentTarget.focus({ preventScroll: true })\n },\n role: "listbox",\n tabIndex: 0,\n }}\n viewportRef={viewportRef}\n >\n {isLoadingDocument ? (\n <div className="p-4">\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </div>\n ) : visibleThumbnails.length ? (\n <div\n className="relative"\n style={{\n height:\n virtualizer.getTotalSize() + DOCX_THUMBNAIL_LIST_PADDING * 2,\n }}\n >\n {virtualItems.map((virtualRow) => {\n const thumbnail = visibleThumbnails[virtualRow.index]\n if (!thumbnail) return null\n\n return (\n <div\n key={virtualRow.key}\n ref={virtualizer.measureElement}\n data-index={virtualRow.index}\n className={cn(\n "absolute top-0 right-3 left-3 pb-3 [contain:layout]",\n thumbnail.pageNumber === activePage && "z-10"\n )}\n style={{\n transform: `translateY(${\n virtualRow.start + DOCX_THUMBNAIL_LIST_PADDING\n }px)`,\n }}\n >\n <div\n id={`${thumbnailListboxId}-page-${thumbnail.pageNumber}`}\n role="option"\n aria-current={\n thumbnail.pageNumber === activePage ? "page" : undefined\n }\n aria-label={`Page ${thumbnail.pageNumber}`}\n aria-posinset={thumbnail.pageNumber}\n aria-selected={thumbnail.pageNumber === activePage}\n aria-setsize={pageCount}\n data-docx-viewer-thumbnail-option={thumbnail.pageNumber}\n className={cn(\n "flex h-auto w-full cursor-default flex-col items-center gap-2 rounded-md p-2 text-xs transition-shadow outline-none select-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground",\n thumbnail.pageNumber === activePage &&\n DOCX_THUMBNAIL_FOCUS_RING_CLASS\n )}\n onClick={() => onSelectPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </div>\n </div>\n )\n })}\n </div>\n ) : null}\n </ScrollArea>\n )\n}\n\nfunction DocxThumbnailSidebarContent({\n activePageStore,\n displayFileName,\n editor,\n isLoadingDocument,\n onSelectPage,\n pageCount,\n reportedPageCount,\n sidebarOpen,\n}: {\n activePageStore: DocxActivePageStore\n displayFileName: string\n editor: DocxEditorController\n isLoadingDocument: boolean\n onSelectPage: (pageNumber: number) => void\n pageCount: number\n reportedPageCount: number\n sidebarOpen: boolean\n}) {\n const [thumbnailRenderWindow, setThumbnailRenderWindow] =\n React.useState<DocxThumbnailRenderWindowState>({\n prefetchPageIndexes: [],\n visiblePageIndexes: [],\n })\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n // Detached thumbnail rendering handles offscreen pages; keep the raster\n // queue dormant while the sidebar is closed.\n disabled: !sidebarOpen,\n pixelRatio: 2,\n renderWindow: thumbnailRenderWindow,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n [sidebarOpen, thumbnailRenderWindow]\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const activePage = useDocxActivePage(activePageStore)\n const handleThumbnailRenderWindowChange = React.useCallback(\n (nextRenderWindow: DocxThumbnailRenderWindowState) => {\n setThumbnailRenderWindow((currentRenderWindow) => {\n if (\n areNumberArraysEqual(\n currentRenderWindow.visiblePageIndexes,\n nextRenderWindow.visiblePageIndexes\n ) &&\n areNumberArraysEqual(\n currentRenderWindow.prefetchPageIndexes,\n nextRenderWindow.prefetchPageIndexes\n )\n ) {\n return currentRenderWindow\n }\n\n return nextRenderWindow\n })\n },\n []\n )\n\n if (!sidebarOpen) return null\n\n return (\n <DocxThumbnailSidebarList\n activePage={activePage}\n displayFileName={displayFileName}\n isLoadingDocument={isLoadingDocument}\n onSelectPage={onSelectPage}\n onThumbnailRenderWindowChange={handleThumbnailRenderWindowChange}\n pageCount={pageCount}\n sidebarOpen={sidebarOpen}\n thumbnails={thumbnails}\n />\n )\n}\n\nexport function DocxViewerPreview({\n className,\n defaultZoom = DEFAULT_ZOOM,\n fileName,\n isDark,\n onIsDarkChange,\n showDownload = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n}: {\n className?: string\n defaultZoom?: ViewerZoomLevel\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n showDownload?: boolean\n showToolbar?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n}) {\n return (\n <DocxViewerContent\n className={className}\n defaultZoom={defaultZoom}\n effectiveIsDark={isDark}\n fileName={fileName}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n showDownload={showDownload}\n showToolbar={showToolbar}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n url={src}\n />\n )\n}\n\nfunction DocxViewerContent({\n className,\n defaultZoom,\n effectiveIsDark,\n fileName,\n setNightRenderEnabled,\n shouldRenderNightMode,\n showDownload,\n showToolbar = true,\n showUpload,\n toolbarActions,\n url,\n}: {\n className?: string\n defaultZoom?: ViewerZoomLevel\n effectiveIsDark: boolean\n fileName?: string\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n showDownload: boolean\n showToolbar?: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewportElement, setViewportElement] =\n React.useState<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const activePageStore = React.useMemo(() => createDocxActivePageStore(), [])\n const resolvedDefaultZoomLevel = normalizeDocxZoomLevel(defaultZoom)\n const activeUploadedDocxFile =\n uploadedDocxFile?.sourceUrl === url ? uploadedDocxFile : null\n const documentKey = activeUploadedDocxFile?.identity ?? url ?? ""\n const setActivePage = activePageStore.setActivePage\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n activeUploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [activeUploadedDocxFile?.file.name, fileName, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { layout: pageLayout } = useDocxPageLayout(editor)\n const { importDocxFile, setDocumentTheme, status } = editor\n const { showComments, setShowComments } = useDocxComments(editor)\n const { showTrackedChanges, setShowTrackedChanges } =\n useDocxTrackChanges(editor)\n const [reportedPageCount, setReportedPageCount] = React.useState(0)\n const [zoomState, setZoomState] = React.useState({\n documentKey: "",\n level: resolvedDefaultZoomLevel,\n resolvedZoom:\n typeof resolvedDefaultZoomLevel === "number"\n ? resolvedDefaultZoomLevel\n : DEFAULT_ZOOM,\n })\n const activeZoomState =\n zoomState.documentKey === documentKey\n ? zoomState\n : {\n documentKey,\n level: resolvedDefaultZoomLevel,\n resolvedZoom:\n typeof resolvedDefaultZoomLevel === "number"\n ? resolvedDefaultZoomLevel\n : DEFAULT_ZOOM,\n }\n const setZoomLevel = React.useCallback(\n (level: ViewerZoomLevel) => {\n setZoomState({\n documentKey,\n level,\n resolvedZoom:\n typeof level === "number" ? level : activeZoomState.resolvedZoom,\n })\n },\n [activeZoomState.resolvedZoom, documentKey]\n )\n const handleZoomChange = React.useCallback(\n (state: ViewerZoomState) => {\n setZoomState({ documentKey, ...state })\n },\n [documentKey]\n )\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <ViewerLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const documentTheme = effectiveIsDark ? "dark" : "light"\n const renderTrackedChangeCard = React.useMemo(\n () => createDocxTrackedChangeCardRenderer(documentTheme),\n [documentTheme]\n )\n const renderCommentCard = React.useMemo(\n () => createDocxCommentCardRenderer(documentTheme),\n [documentTheme]\n )\n const hasDocument = Boolean(url || activeUploadedDocxFile)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const thumbnailSidebarVisible = Boolean(\n sidebarOpen && (pageCount || isLoadingDocument)\n )\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n const setViewportRef = React.useCallback((element: HTMLDivElement | null) => {\n viewportRef.current = element\n setViewportElement(element)\n }, [])\n const pageVirtualization = React.useMemo(\n () => ({\n enabled: true,\n overscan: 1,\n scrollElement: viewportElement,\n }),\n [viewportElement]\n )\n const handleDownload = React.useCallback(async () => {\n if (isPreparingDownload) return\n if (!activeUploadedDocxFile && !url) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadDocxFile({\n file: activeUploadedDocxFile?.file,\n fileName: displayFileName,\n url,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [activeUploadedDocxFile, displayFileName, isPreparingDownload, url])\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [documentKey, setActivePage])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n const frame = window.requestAnimationFrame(() => {\n setLoadError(status)\n setIsLoadingDocument(false)\n })\n\n return () => window.cancelAnimationFrame(frame)\n }\n }, [status])\n\n // Imports mutate the shared editor instance; concurrent calls (effect\n // re-runs, StrictMode double-invoke) race inside the parser and surface as\n // bogus "Invalid DOCX ZIP" errors, so every import is chained through here.\n const importQueueRef = React.useRef<Promise<void>>(Promise.resolve())\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n // Superseded while queued — let the newest import run instead.\n if (!isCurrent) return\n if (!activeUploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n activeUploadedDocxFile?.file ??\n (url ? await loadDocxFile(url, displayFileName) : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : "Unknown DOCX load error"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n importQueueRef.current = importQueueRef.current.then(load)\n\n return () => {\n isCurrent = false\n }\n }, [\n activeUploadedDocxFile,\n displayFileName,\n importDocxFile,\n setActivePage,\n url,\n ])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n \'[data-docx-page-wrapper="true"][data-index]\'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n activePageStore.setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [activePageStore, pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback(\n (pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport) return\n\n if (!page) {\n const pageStridePx =\n (pageLayout.pageHeightPx + pageLayout.viewportDefaults.pageGapPx) *\n (activeZoomState.resolvedZoom / 100)\n\n viewport.scrollTo({\n top: Math.max(0, targetPageIndex * pageStridePx - 24),\n behavior: "auto",\n })\n return\n }\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n },\n [\n pageLayout.pageHeightPx,\n pageLayout.viewportDefaults.pageGapPx,\n setActivePage,\n activeZoomState.resolvedZoom,\n ]\n )\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomLevel(resolvedDefaultZoomLevel)\n setActivePage(1)\n setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n sourceUrl: url,\n })\n }\n\n return (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n {showToolbar ? (\n <DocxToolbar\n activePageStore={activePageStore}\n controlsDisabled={controlsDisabled}\n isDark={effectiveIsDark}\n isPreparingDownload={isPreparingDownload}\n onDownload={handleDownload}\n onIsDarkChange={setNightRenderEnabled}\n onPageChange={scrollToPage}\n onShowCommentsChange={setShowComments}\n onShowTrackedChangesChange={setShowTrackedChanges}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n onZoomChange={setZoomLevel}\n showComments={showComments}\n showDownloadButton={showDownload}\n showNightRenderToggle={shouldRenderNightMode}\n showTrackedChanges={showTrackedChanges}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n resolvedZoom={activeZoomState.resolvedZoom}\n zoomLevel={activeZoomState.level}\n />\n ) : null}\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={thumbnailSidebarVisible}\n >\n <DocxThumbnailSidebarContent\n activePageStore={activePageStore}\n displayFileName={displayFileName}\n editor={editor}\n isLoadingDocument={isLoadingDocument}\n onSelectPage={scrollToPage}\n pageCount={pageCount}\n reportedPageCount={reportedPageCount}\n sidebarOpen={thumbnailSidebarVisible}\n />\n </DocumentViewerThumbnailSidebar>\n <ScrollArea\n className="min-h-0 flex-1"\n style={{ backgroundColor: viewerBackgroundColor }}\n viewportClassName="px-4 py-6"\n viewportProps={{\n "aria-label": "DOCX document",\n onMouseDown: (event) => {\n if (isInteractiveViewerTarget(event.target)) return\n event.currentTarget.focus({ preventScroll: true })\n },\n tabIndex: 0,\n }}\n viewportRef={setViewportRef}\n >\n {!url && !activeUploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">\n Upload a Word document to preview\n </div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <div className="mt-1 text-muted-foreground">\n Legacy <code>.doc</code> support is limited and experimental;\n convert to DOCX for best fidelity.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload Word document\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to display DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="flex min-h-full w-max min-w-full justify-center">\n <div className={cn(effectiveIsDark && "docx-night-reader-shell")}>\n <DocxEditorViewer\n editor={editor}\n mode="read-only"\n zoom={activeZoomState.level}\n onZoomChange={handleZoomChange}\n showTrackedChanges={showTrackedChanges}\n renderTrackedChangeCard={renderTrackedChangeCard}\n showComments={showComments}\n renderCommentCard={renderCommentCard}\n loadingState={loadingState}\n pageBackgroundColor={effectiveIsDark ? "#0a0a0a" : undefined}\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={pageVirtualization}\n deferInitialPaginationPaint={false}\n onPageCountChange={handlePageCountChange}\n />\n </div>\n </div>\n )}\n </ScrollArea>\n </div>\n </div>\n )\n}\n'+ '"use client"\n\nimport * as React from "react"\nimport {\n DocxEditorViewer,\n useDocxComments,\n useDocxEditor,\n useDocxPageLayout,\n useDocxTrackChanges,\n useDocxViewerThumbnails,\n type DocxDocumentTheme,\n type DocxEditorController,\n type DocxPageThumbnailItem,\n type ViewerZoomLevel,\n type ViewerZoomState,\n} from "@extend-ai/react-docx"\nimport { useVirtualizer } from "@tanstack/react-virtual"\n\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu"\nimport { Input } from "@/components/ui/input"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select"\nimport { Separator } from "@/components/ui/separator"\nimport { Spinner } from "@/components/ui/spinner"\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport {\n DocumentViewerThumbnailSidebar,\n useElementWidth,\n useInlineThumbnailSidebar,\n} from "@/components/extend/document-viewer-sidebar"\nimport {\n createDocxCommentCardRenderer,\n createDocxTrackedChangeCardRenderer,\n} from "@/components/extend/docx-annotation-card"\nimport { FileThumbnail } from "@/components/extend/file-thumbnail"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nconst DOCX_MIME_TYPE =\n "application/vnd.openxmlformats-officedocument.wordprocessingml.document"\nconst DOCX_LOADING_INDICATOR_DELAY_MS = 300\nconst DOCX_THUMBNAIL_WIDTH = 92\nconst DOCX_THUMBNAIL_LIST_PADDING = 16\nconst DOCX_THUMBNAIL_ROW_ESTIMATE = 172\nconst DEFAULT_ZOOM = 50\nconst ZOOM_OPTIONS = [50, 75, 100, 125, 150, 175, 200] as const\nconst ZOOM_MODE_LABELS = {\n "fit-page": "Fit page",\n "fit-width": "Fit width",\n automatic: "Automatic",\n} satisfies Record<Exclude<ViewerZoomLevel, number>, string>\nconst DOCX_PADDING_WARNING_TEXT = "a style property during rerender"\nconst DOCX_THUMBNAIL_FOCUS_RING_CLASS =\n "group-focus-visible/docx-thumbnail-sidebar:ring-2 group-focus-visible/docx-thumbnail-sidebar:ring-ring group-focus-visible/docx-thumbnail-sidebar:ring-offset-1 group-focus-visible/docx-thumbnail-sidebar:ring-offset-background"\nconst DOCX_THUMBNAIL_PREFETCH_ROWS = 4\n\ntype UploadedDocxFile = {\n file: File\n identity: string\n sourceUrl: string | undefined\n}\n\ntype DocxActivePageStore = {\n getSnapshot: () => number\n setActivePage: React.Dispatch<React.SetStateAction<number>>\n subscribe: (listener: () => void) => () => void\n}\n\ntype DocxThumbnailRenderWindowState = {\n visiblePageIndexes: number[]\n prefetchPageIndexes: number[]\n}\n\nfunction createDocxActivePageStore(): DocxActivePageStore {\n let activePage = 1\n const listeners = new Set<() => void>()\n\n return {\n getSnapshot: () => activePage,\n setActivePage: (nextPage) => {\n const value =\n typeof nextPage === "function" ? nextPage(activePage) : nextPage\n const normalizedValue = Math.max(1, Math.round(value || 1))\n\n if (normalizedValue === activePage) return\n\n activePage = normalizedValue\n listeners.forEach((listener) => listener())\n },\n subscribe: (listener) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n }\n}\n\nfunction useDocxActivePage(activePageStore: DocxActivePageStore) {\n return React.useSyncExternalStore(\n activePageStore.subscribe,\n activePageStore.getSnapshot,\n activePageStore.getSnapshot\n )\n}\n\nfunction areNumberArraysEqual(left: number[], right: number[]) {\n return (\n left.length === right.length &&\n left.every((value, index) => value === right[index])\n )\n}\n\nasync function loadDocxFile(\n url: string,\n displayFileName: string\n): Promise<File> {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch DOCX (${response.status})`)\n }\n\n const blob = await response.blob()\n return new File([blob], displayFileName, {\n type: blob.type || DOCX_MIME_TYPE,\n })\n}\n\nfunction formatDocumentName(fileName: string | undefined, url: string) {\n if (fileName?.trim()) return fileName\n\n const pathname = url.split("?")[0] ?? ""\n const rawName = pathname.split("/").pop() ?? "document.docx"\n\n try {\n return decodeURIComponent(rawName)\n } catch {\n return rawName\n }\n}\n\nfunction ensureDocxExtension(fileName: string) {\n return fileName.toLowerCase().endsWith(".docx")\n ? fileName\n : `${fileName}.docx`\n}\n\nfunction downloadBlob(blob: Blob, fileName: string) {\n const url = URL.createObjectURL(blob)\n const anchor = document.createElement("a")\n\n anchor.href = url\n anchor.download = fileName\n anchor.rel = "noopener"\n document.body.append(anchor)\n anchor.click()\n anchor.remove()\n window.setTimeout(() => URL.revokeObjectURL(url), 0)\n}\n\nasync function downloadDocxFile({\n file,\n fileName,\n url,\n}: {\n file?: File\n fileName: string\n url?: string\n}) {\n if (file) {\n downloadBlob(file, ensureDocxExtension(fileName))\n return\n }\n\n if (!url) return\n\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to download DOCX (${response.status})`)\n }\n\n downloadBlob(await response.blob(), ensureDocxExtension(fileName))\n}\n\nfunction getNextZoomScale(currentZoomScale: number, direction: 1 | -1) {\n if (direction > 0) {\n return (\n ZOOM_OPTIONS.find((value) => value > currentZoomScale) ?? currentZoomScale\n )\n }\n\n for (let index = ZOOM_OPTIONS.length - 1; index >= 0; index -= 1) {\n const value = ZOOM_OPTIONS[index]\n if (value < currentZoomScale) return value\n }\n\n return currentZoomScale\n}\n\nfunction normalizeDocxZoomLevel(\n value: ViewerZoomLevel | undefined\n): ViewerZoomLevel {\n return value ?? DEFAULT_ZOOM\n}\n\nfunction isZoomMode(value: string): value is Exclude<ViewerZoomLevel, number> {\n return value in ZOOM_MODE_LABELS\n}\n\nfunction useDelayedLoadingIndicator(isLoading: boolean, delayMs: number) {\n const [showSpinner, setShowSpinner] = React.useState(false)\n const [previousIsLoading, setPreviousIsLoading] = React.useState(isLoading)\n\n if (previousIsLoading !== isLoading) {\n setPreviousIsLoading(isLoading)\n setShowSpinner(false)\n }\n\n React.useEffect(() => {\n if (!isLoading) return\n\n const timeoutId = window.setTimeout(() => {\n setShowSpinner(true)\n }, delayMs)\n\n return () => window.clearTimeout(timeoutId)\n }, [delayMs, isLoading])\n\n return isLoading && showSpinner\n}\n\nfunction isDocxPaddingWarning(args: unknown[]) {\n return (\n typeof args[0] === "string" &&\n args[0].includes(DOCX_PADDING_WARNING_TEXT) &&\n args.some((arg) => String(arg).includes("padding"))\n )\n}\n\nfunction useSuppressDocxPaddingWarning(enabled: boolean) {\n React.useEffect(() => {\n if (!enabled) return\n\n const originalConsoleError = console.error\n\n console.error = (...args: unknown[]) => {\n if (isDocxPaddingWarning(args)) return\n originalConsoleError(...args)\n }\n\n return () => {\n console.error = originalConsoleError\n }\n }, [enabled])\n}\n\nfunction isInteractiveViewerTarget(target: EventTarget | null) {\n return (\n target instanceof Element &&\n Boolean(\n target.closest(\n \'a[href], button, input, select, textarea, [contenteditable="true"], [role="button"], [role="link"]\'\n )\n )\n )\n}\n\nfunction ToolbarTooltip({\n label,\n children,\n}: {\n label: string\n children: React.ReactNode\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <span className="inline-flex">{children}</span>\n </TooltipTrigger>\n <TooltipContent side="bottom">{label}</TooltipContent>\n </Tooltip>\n )\n}\n\nfunction ViewerLoadingSurface({\n showSpinner = true,\n}: {\n showSpinner?: boolean\n}) {\n return (\n <div className="grid h-full min-h-52 place-items-center bg-transparent">\n {showSpinner ? <Spinner className="size-4" /> : null}\n </div>\n )\n}\n\nfunction DocxFileActionsMenu({\n controlsDisabled,\n downloadDisabled,\n isPreparingDownload,\n isDark,\n onDownload,\n onShowCommentsChange,\n onShowTrackedChangesChange,\n onIsDarkChange,\n onUploadClick,\n showComments,\n showDownloadButton,\n showNightRenderToggle,\n showTrackedChanges,\n showUploadButton,\n}: {\n controlsDisabled: boolean\n downloadDisabled: boolean\n isPreparingDownload: boolean\n isDark: boolean\n onDownload: () => void\n onShowCommentsChange: (checked: boolean) => void\n onShowTrackedChangesChange: (checked: boolean) => void\n onIsDarkChange: (checked: boolean) => void\n onUploadClick: () => void\n showComments: boolean\n showDownloadButton: boolean\n showNightRenderToggle: boolean\n showTrackedChanges: boolean\n showUploadButton: boolean\n}) {\n const showFileActions = showDownloadButton || showUploadButton\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Open DOCX actions"\n >\n <IconPlaceholder\n lucide="Ellipsis"\n tabler="IconDots"\n hugeicons="MoreHorizontalIcon"\n phosphor="DotsThreeIcon"\n remixicon="RiMoreLine"\n className="size-4"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-52">\n {showNightRenderToggle ? (\n <>\n <DropdownMenuCheckboxItem\n checked={isDark}\n disabled={controlsDisabled}\n variant="switch"\n onCheckedChange={(checked) => onIsDarkChange(checked === true)}\n >\n <span className="flex min-w-0 items-center gap-2">\n <IconPlaceholder\n lucide="Moon"\n tabler="IconMoon"\n hugeicons="Moon02Icon"\n phosphor="MoonIcon"\n remixicon="RiMoonLine"\n className="size-4"\n />\n Dark mode\n </span>\n </DropdownMenuCheckboxItem>\n <DropdownMenuSeparator />\n </>\n ) : null}\n <DropdownMenuCheckboxItem\n checked={showComments}\n disabled={controlsDisabled}\n variant="switch"\n onCheckedChange={(checked) => onShowCommentsChange(checked === true)}\n >\n <span className="flex min-w-0 items-center gap-2">\n <IconPlaceholder\n lucide="MessageSquare"\n tabler="IconMessage"\n hugeicons="Comment01Icon"\n phosphor="ChatIcon"\n remixicon="RiChat1Line"\n className="size-4"\n />\n Comments\n </span>\n </DropdownMenuCheckboxItem>\n <DropdownMenuCheckboxItem\n checked={showTrackedChanges}\n disabled={controlsDisabled}\n variant="switch"\n onCheckedChange={(checked) =>\n onShowTrackedChangesChange(checked === true)\n }\n >\n <span className="flex min-w-0 items-center gap-2">\n <IconPlaceholder\n lucide="FileDiff"\n tabler="IconFileDiff"\n hugeicons="FileDiffIcon"\n phosphor="GitDiffIcon"\n remixicon="RiFileHistoryLine"\n className="size-4"\n />\n Edits\n </span>\n </DropdownMenuCheckboxItem>\n {showFileActions ? <DropdownMenuSeparator /> : null}\n {showDownloadButton ? (\n <DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>\n {isPreparingDownload ? (\n <Spinner className="size-4" />\n ) : (\n <IconPlaceholder\n lucide="Download"\n tabler="IconDownload"\n hugeicons="Download01Icon"\n phosphor="DownloadSimpleIcon"\n remixicon="RiDownload2Line"\n className="size-4"\n />\n )}\n Download\n </DropdownMenuItem>\n ) : null}\n {showUploadButton ? (\n <DropdownMenuItem onClick={onUploadClick}>\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload\n </DropdownMenuItem>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\nfunction DocxPageNumberControl({\n activePageStore,\n controlsDisabled,\n onPageChange,\n pageCount,\n}: {\n activePageStore: DocxActivePageStore\n controlsDisabled: boolean\n onPageChange: (pageNumber: number) => void\n pageCount: number\n}) {\n const activePage = useDocxActivePage(activePageStore)\n const inputRef = React.useRef<HTMLInputElement>(null)\n const displayPage = pageCount ? activePage : 1\n const [isEditing, setIsEditing] = React.useState(false)\n const [draftPage, setDraftPage] = React.useState(() => String(displayPage))\n\n React.useEffect(() => {\n if (!isEditing) return\n\n inputRef.current?.focus()\n inputRef.current?.select()\n }, [isEditing])\n\n const applyPageDraft = React.useCallback(\n (value: string) => {\n const trimmedValue = value.trim()\n\n if (!trimmedValue) return\n\n const parsedPage = Number(trimmedValue)\n\n if (!Number.isInteger(parsedPage)) return\n\n onPageChange(Math.min(Math.max(parsedPage, 1), Math.max(pageCount, 1)))\n },\n [onPageChange, pageCount]\n )\n\n return (\n <div className="flex items-center text-sm whitespace-nowrap text-primary">\n <span>Page</span>\n {isEditing ? (\n <Input\n ref={inputRef}\n aria-label="Page number"\n inputMode="numeric"\n pattern="[0-9]*"\n size="sm"\n value={draftPage}\n className="mx-1 w-14 min-w-14 rounded-md [&_[data-slot=input]]:text-center"\n onBlur={() => setIsEditing(false)}\n onChange={(event: React.ChangeEvent<HTMLInputElement>) => {\n const nextValue = event.target.value\n\n setDraftPage(nextValue)\n applyPageDraft(nextValue)\n }}\n onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === "Enter" || event.key === "Escape") {\n event.currentTarget.blur()\n }\n }}\n />\n ) : (\n <Button\n type="button"\n variant="ghost"\n size="sm"\n className="font-normal"\n aria-label={`Current page ${displayPage}. Edit page number`}\n disabled={controlsDisabled || !pageCount}\n onClick={() => {\n setDraftPage(String(displayPage))\n setIsEditing(true)\n }}\n >\n {displayPage}\n </Button>\n )}\n <span>of {pageCount || "-"}</span>\n </div>\n )\n}\n\nfunction DocxToolbar({\n activePageStore,\n controlsDisabled,\n isDark,\n isPreparingDownload,\n onDownload,\n onIsDarkChange,\n onPageChange,\n onShowCommentsChange,\n onShowTrackedChangesChange,\n onToggleSidebar,\n onUploadClick,\n onZoomChange,\n pageCount,\n resolvedZoom,\n showComments,\n showDownloadButton = true,\n showNightRenderToggle,\n showTrackedChanges,\n showUploadButton = true,\n toolbarActions,\n zoomLevel,\n}: {\n activePageStore: DocxActivePageStore\n controlsDisabled: boolean\n isDark: boolean\n isPreparingDownload: boolean\n onDownload: () => void\n onIsDarkChange: (checked: boolean) => void\n onPageChange: (pageNumber: number) => void\n onShowCommentsChange: (checked: boolean) => void\n onShowTrackedChangesChange: (checked: boolean) => void\n onToggleSidebar: () => void\n onUploadClick: () => void\n onZoomChange: (zoomLevel: ViewerZoomLevel) => void\n pageCount: number\n resolvedZoom: number\n showComments: boolean\n showDownloadButton?: boolean\n showNightRenderToggle: boolean\n showTrackedChanges: boolean\n showUploadButton?: boolean\n toolbarActions?: React.ReactNode\n zoomLevel: ViewerZoomLevel\n}) {\n const canZoomIn = resolvedZoom < ZOOM_OPTIONS[ZOOM_OPTIONS.length - 1]\n const canZoomOut = resolvedZoom > ZOOM_OPTIONS[0]\n const selectValue =\n typeof zoomLevel === "number" ? zoomLevel.toString() : zoomLevel\n const roundedZoom = Number(resolvedZoom.toFixed(2))\n const zoomOptions = ZOOM_OPTIONS.includes(\n roundedZoom as (typeof ZOOM_OPTIONS)[number]\n )\n ? ZOOM_OPTIONS\n : [...ZOOM_OPTIONS, roundedZoom].sort((left, right) => left - right)\n\n return (\n <div className="flex min-h-12 flex-wrap items-center justify-between gap-2 border-b bg-background px-3 py-2">\n <TooltipProvider>\n <div className="flex min-w-0 flex-wrap items-center gap-2">\n <ToolbarTooltip label="Toggle thumbnails">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n aria-label="Toggle thumbnails"\n disabled={controlsDisabled}\n onClick={onToggleSidebar}\n >\n <IconPlaceholder\n lucide="PanelLeft"\n tabler="IconLayoutSidebar"\n hugeicons="SidebarLeftIcon"\n phosphor="SidebarIcon"\n remixicon="RiLayoutLeftLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <DocxPageNumberControl\n activePageStore={activePageStore}\n controlsDisabled={controlsDisabled}\n onPageChange={onPageChange}\n pageCount={pageCount}\n />\n </div>\n <div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1">\n <div className="flex flex-none items-center gap-1">\n <ToolbarTooltip label="Zoom out">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled || !canZoomOut}\n aria-label="Zoom out"\n onClick={() => onZoomChange(getNextZoomScale(resolvedZoom, -1))}\n >\n <IconPlaceholder\n lucide="CircleMinus"\n tabler="IconCircleMinus"\n hugeicons="MinusSignCircleIcon"\n phosphor="MinusCircleIcon"\n remixicon="RiIndeterminateCircleLine"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n <Select\n value={selectValue}\n onValueChange={(value) => {\n if (value === null) return\n onZoomChange(isZoomMode(value) ? value : Number(value))\n }}\n disabled={controlsDisabled}\n modal={false}\n >\n <SelectTrigger\n size="sm"\n className="w-[104px] min-w-[104px]"\n aria-label="Zoom level"\n >\n <SelectValue>{Math.round(resolvedZoom)}%</SelectValue>\n </SelectTrigger>\n <SelectContent align="end" alignItemWithTrigger={false}>\n {Object.entries(ZOOM_MODE_LABELS).map(([value, label]) => (\n <SelectItem key={value} value={value}>\n {label}\n </SelectItem>\n ))}\n {zoomOptions.map((value) => (\n <SelectItem key={value} value={value.toString()}>\n {value}%\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <ToolbarTooltip label="Zoom in">\n <Button\n type="button"\n variant="ghost"\n size="icon-sm"\n disabled={controlsDisabled || !canZoomIn}\n aria-label="Zoom in"\n onClick={() => onZoomChange(getNextZoomScale(resolvedZoom, 1))}\n >\n <IconPlaceholder\n lucide="CirclePlusIcon"\n tabler="IconCirclePlusFilled"\n hugeicons="PlusSignCircleIcon"\n phosphor="PlusCircleIcon"\n remixicon="RiAddCircleFill"\n className="size-4"\n />\n </Button>\n </ToolbarTooltip>\n </div>\n {toolbarActions ? (\n <>\n <Separator\n orientation="vertical"\n className="mx-1 h-4 self-center"\n />\n {toolbarActions}\n </>\n ) : null}\n <Separator orientation="vertical" className="mx-1 h-4 self-center" />\n <DocxFileActionsMenu\n controlsDisabled={controlsDisabled}\n downloadDisabled={controlsDisabled || isPreparingDownload}\n isPreparingDownload={isPreparingDownload}\n isDark={isDark}\n onDownload={onDownload}\n onIsDarkChange={onIsDarkChange}\n onShowCommentsChange={onShowCommentsChange}\n onShowTrackedChangesChange={onShowTrackedChangesChange}\n onUploadClick={onUploadClick}\n showComments={showComments}\n showDownloadButton={showDownloadButton}\n showNightRenderToggle={showNightRenderToggle}\n showTrackedChanges={showTrackedChanges}\n showUploadButton={showUploadButton}\n />\n </div>\n </TooltipProvider>\n </div>\n )\n}\n\nfunction DocxSidebarThumbnail({\n canvasRef,\n displayFileName,\n hasError,\n isActive,\n isLoading,\n pageNumber,\n pixelHeightPx,\n pixelWidthPx,\n previewAspectRatio,\n}: {\n canvasRef: React.RefCallback<HTMLCanvasElement>\n displayFileName: string\n hasError: boolean\n isActive: boolean\n isLoading: boolean\n pageNumber: number\n pixelHeightPx: number\n pixelWidthPx: number\n previewAspectRatio: number\n}) {\n return (\n <FileThumbnail\n file={{\n name: `${displayFileName} page ${pageNumber}`,\n type: DOCX_MIME_TYPE,\n }}\n previewAspectRatio={previewAspectRatio}\n previewClassName="rounded-md bg-white"\n previewContent={\n <canvas\n ref={canvasRef}\n width={pixelWidthPx}\n height={pixelHeightPx}\n className="!size-full bg-white object-cover object-top"\n />\n }\n isLoading={isLoading}\n hasError={hasError}\n className={cn(\n "w-[92px] rounded-md border-0 shadow-xs ring-0 transition-shadow duration-150",\n isActive && "shadow-sm"\n )}\n />\n )\n}\n\nfunction DocxThumbnailSidebarList({\n activePage,\n displayFileName,\n isLoadingDocument,\n onSelectPage,\n onThumbnailRenderWindowChange,\n pageCount,\n sidebarOpen,\n thumbnails,\n}: {\n activePage: number\n displayFileName: string\n isLoadingDocument: boolean\n onSelectPage: (pageNumber: number) => void\n onThumbnailRenderWindowChange: (\n renderWindow: DocxThumbnailRenderWindowState\n ) => void\n pageCount: number\n sidebarOpen: boolean\n thumbnails: DocxPageThumbnailItem[]\n}) {\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const thumbnailListboxId = React.useId()\n const visibleThumbnails = React.useMemo(\n () => thumbnails.slice(0, pageCount || 0),\n [pageCount, thumbnails]\n )\n const activeDescendantId =\n activePage > 0 && visibleThumbnails.length\n ? `${thumbnailListboxId}-page-${activePage}`\n : undefined\n const virtualizer = useVirtualizer({\n count: visibleThumbnails.length,\n estimateSize: () => DOCX_THUMBNAIL_ROW_ESTIMATE,\n getItemKey: (index) => visibleThumbnails[index]?.pageIndex ?? index,\n getScrollElement: () => viewportRef.current,\n overscan: 3,\n })\n const virtualItems = virtualizer.getVirtualItems()\n const renderWindowSignature = virtualItems\n .map((virtualRow) => virtualRow.index)\n .join(",")\n\n React.useEffect(() => {\n if (!sidebarOpen || isLoadingDocument || !visibleThumbnails.length) {\n onThumbnailRenderWindowChange({\n prefetchPageIndexes: [],\n visiblePageIndexes: [],\n })\n return\n }\n\n const visiblePageIndexes = virtualItems\n .map((virtualRow) => visibleThumbnails[virtualRow.index]?.pageIndex)\n .filter((pageIndex): pageIndex is number => pageIndex !== undefined)\n\n const firstVirtualIndex = virtualItems[0]?.index ?? 0\n const lastVirtualIndex =\n virtualItems[virtualItems.length - 1]?.index ?? firstVirtualIndex\n const firstPrefetchIndex = Math.max(\n 0,\n firstVirtualIndex - DOCX_THUMBNAIL_PREFETCH_ROWS\n )\n const lastPrefetchIndex = Math.min(\n visibleThumbnails.length - 1,\n lastVirtualIndex + DOCX_THUMBNAIL_PREFETCH_ROWS\n )\n const visiblePageIndexSet = new Set(visiblePageIndexes)\n const prefetchPageIndexes: number[] = []\n\n for (\n let index = firstPrefetchIndex;\n index <= lastPrefetchIndex;\n index += 1\n ) {\n const pageIndex = visibleThumbnails[index]?.pageIndex\n\n if (pageIndex !== undefined && !visiblePageIndexSet.has(pageIndex)) {\n prefetchPageIndexes.push(pageIndex)\n }\n }\n\n onThumbnailRenderWindowChange({\n prefetchPageIndexes,\n visiblePageIndexes,\n })\n }, [\n isLoadingDocument,\n onThumbnailRenderWindowChange,\n renderWindowSignature,\n sidebarOpen,\n visibleThumbnails,\n virtualItems,\n ])\n\n React.useEffect(() => {\n if (!sidebarOpen || activePage < 1 || !visibleThumbnails.length) return\n\n virtualizer.scrollToIndex(\n Math.min(activePage - 1, visibleThumbnails.length - 1),\n { align: "auto" }\n )\n }, [activePage, sidebarOpen, virtualizer, visibleThumbnails.length])\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (pageCount < 1) return\n\n const currentPage = activePage > 0 ? activePage : 1\n let nextPage: number | null = null\n\n if (event.key === "ArrowDown") {\n nextPage = Math.min(pageCount, currentPage + 1)\n } else if (event.key === "ArrowUp") {\n nextPage = Math.max(1, currentPage - 1)\n } else if (event.key === "Home") {\n nextPage = 1\n } else if (event.key === "End") {\n nextPage = pageCount\n }\n\n if (nextPage === null) return\n\n event.preventDefault()\n onSelectPage(nextPage)\n },\n [activePage, onSelectPage, pageCount]\n )\n\n return (\n <ScrollArea\n className="h-full"\n scrollFade\n viewportClassName="group/docx-thumbnail-sidebar focus-visible:ring-0 focus-visible:ring-offset-0"\n viewportProps={{\n "aria-activedescendant": activeDescendantId,\n "aria-busy": isLoadingDocument || undefined,\n "aria-label": "DOCX pages",\n onKeyDown: handleKeyDown,\n onMouseDown: (event) => {\n event.currentTarget.focus({ preventScroll: true })\n },\n role: "listbox",\n tabIndex: 0,\n }}\n viewportRef={viewportRef}\n >\n {isLoadingDocument ? (\n <div className="p-4">\n <div className="mx-auto h-28 w-20 overflow-hidden rounded-md bg-background shadow-xs">\n <div className="h-full animate-pulse bg-muted" />\n </div>\n <div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" />\n </div>\n ) : visibleThumbnails.length ? (\n <div\n className="relative"\n style={{\n height:\n virtualizer.getTotalSize() + DOCX_THUMBNAIL_LIST_PADDING * 2,\n }}\n >\n {virtualItems.map((virtualRow) => {\n const thumbnail = visibleThumbnails[virtualRow.index]\n if (!thumbnail) return null\n\n return (\n <div\n key={virtualRow.key}\n ref={virtualizer.measureElement}\n data-index={virtualRow.index}\n className={cn(\n "absolute top-0 right-3 left-3 pb-3 [contain:layout]",\n thumbnail.pageNumber === activePage && "z-10"\n )}\n style={{\n transform: `translateY(${\n virtualRow.start + DOCX_THUMBNAIL_LIST_PADDING\n }px)`,\n }}\n >\n <div\n id={`${thumbnailListboxId}-page-${thumbnail.pageNumber}`}\n role="option"\n aria-current={\n thumbnail.pageNumber === activePage ? "page" : undefined\n }\n aria-label={`Page ${thumbnail.pageNumber}`}\n aria-posinset={thumbnail.pageNumber}\n aria-selected={thumbnail.pageNumber === activePage}\n aria-setsize={pageCount}\n data-docx-viewer-thumbnail-option={thumbnail.pageNumber}\n className={cn(\n "flex h-auto w-full cursor-default flex-col items-center gap-2 rounded-md p-2 text-xs transition-shadow outline-none select-none hover:bg-sidebar-accent",\n thumbnail.pageNumber === activePage &&\n "bg-sidebar-accent text-foreground",\n thumbnail.pageNumber !== activePage &&\n "text-muted-foreground",\n thumbnail.pageNumber === activePage &&\n DOCX_THUMBNAIL_FOCUS_RING_CLASS\n )}\n onClick={() => onSelectPage(thumbnail.pageNumber)}\n >\n <DocxSidebarThumbnail\n canvasRef={thumbnail.canvasRef}\n displayFileName={displayFileName}\n hasError={thumbnail.status === "error"}\n isActive={thumbnail.pageNumber === activePage}\n isLoading={\n thumbnail.status !== "ready" &&\n thumbnail.status !== "error"\n }\n pageNumber={thumbnail.pageNumber}\n pixelHeightPx={thumbnail.pixelHeightPx}\n pixelWidthPx={thumbnail.pixelWidthPx}\n previewAspectRatio={thumbnail.aspectRatio}\n />\n {thumbnail.pageNumber}\n </div>\n </div>\n )\n })}\n </div>\n ) : null}\n </ScrollArea>\n )\n}\n\nfunction DocxThumbnailSidebarContent({\n activePageStore,\n displayFileName,\n editor,\n isLoadingDocument,\n onSelectPage,\n pageCount,\n reportedPageCount,\n sidebarOpen,\n}: {\n activePageStore: DocxActivePageStore\n displayFileName: string\n editor: DocxEditorController\n isLoadingDocument: boolean\n onSelectPage: (pageNumber: number) => void\n pageCount: number\n reportedPageCount: number\n sidebarOpen: boolean\n}) {\n const [thumbnailRenderWindow, setThumbnailRenderWindow] =\n React.useState<DocxThumbnailRenderWindowState>({\n prefetchPageIndexes: [],\n visiblePageIndexes: [],\n })\n const thumbnailEditor = React.useMemo<DocxEditorController>(\n () => ({\n ...editor,\n totalPages: Math.max(editor.totalPages, reportedPageCount),\n }),\n [editor, reportedPageCount]\n )\n const thumbnailOptions = React.useMemo(\n () => ({\n // Detached thumbnail rendering handles offscreen pages; keep the raster\n // queue dormant while the sidebar is closed.\n disabled: !sidebarOpen,\n pixelRatio: 2,\n renderWindow: thumbnailRenderWindow,\n resolution: {\n maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,\n maxWidth: DOCX_THUMBNAIL_WIDTH,\n },\n }),\n [sidebarOpen, thumbnailRenderWindow]\n )\n const { thumbnails } = useDocxViewerThumbnails(\n thumbnailEditor,\n thumbnailOptions\n )\n const activePage = useDocxActivePage(activePageStore)\n const handleThumbnailRenderWindowChange = React.useCallback(\n (nextRenderWindow: DocxThumbnailRenderWindowState) => {\n setThumbnailRenderWindow((currentRenderWindow) => {\n if (\n areNumberArraysEqual(\n currentRenderWindow.visiblePageIndexes,\n nextRenderWindow.visiblePageIndexes\n ) &&\n areNumberArraysEqual(\n currentRenderWindow.prefetchPageIndexes,\n nextRenderWindow.prefetchPageIndexes\n )\n ) {\n return currentRenderWindow\n }\n\n return nextRenderWindow\n })\n },\n []\n )\n\n if (!sidebarOpen) return null\n\n return (\n <DocxThumbnailSidebarList\n activePage={activePage}\n displayFileName={displayFileName}\n isLoadingDocument={isLoadingDocument}\n onSelectPage={onSelectPage}\n onThumbnailRenderWindowChange={handleThumbnailRenderWindowChange}\n pageCount={pageCount}\n sidebarOpen={sidebarOpen}\n thumbnails={thumbnails}\n />\n )\n}\n\nexport type DocxViewerLayoutProps = {\n children: React.ReactNode\n model?: DocxEditorController["model"]\n viewportRef: React.RefObject<HTMLDivElement | null>\n isLoading: boolean\n loadError?: string\n}\n\nexport function DocxViewerPreview({\n className,\n layout: Layout,\n defaultZoom = DEFAULT_ZOOM,\n fileName,\n isDark,\n onIsDarkChange,\n showDownload = true,\n showToolbar = true,\n showUpload = true,\n src,\n toolbarActions,\n}: {\n className?: string\n layout?: React.ComponentType<DocxViewerLayoutProps>\n defaultZoom?: ViewerZoomLevel\n fileName?: string\n isDark: boolean\n onIsDarkChange: (isDark: boolean) => void\n showDownload?: boolean\n showToolbar?: boolean\n showUpload?: boolean\n src?: string\n toolbarActions?: React.ReactNode\n}) {\n return (\n <DocxViewerContent\n layout={Layout}\n className={className}\n defaultZoom={defaultZoom}\n effectiveIsDark={isDark}\n fileName={fileName}\n setNightRenderEnabled={onIsDarkChange}\n shouldRenderNightMode\n showDownload={showDownload}\n showToolbar={showToolbar}\n showUpload={showUpload}\n toolbarActions={toolbarActions}\n url={src}\n />\n )\n}\n\nfunction DocxViewerContent({\n className,\n layout: Layout,\n defaultZoom,\n effectiveIsDark,\n fileName,\n setNightRenderEnabled,\n shouldRenderNightMode,\n showDownload,\n showToolbar = true,\n showUpload,\n toolbarActions,\n url,\n}: {\n className?: string\n layout?: React.ComponentType<DocxViewerLayoutProps>\n defaultZoom?: ViewerZoomLevel\n effectiveIsDark: boolean\n fileName?: string\n setNightRenderEnabled: (checked: boolean) => void\n shouldRenderNightMode: boolean\n showDownload: boolean\n showToolbar?: boolean\n showUpload: boolean\n toolbarActions?: React.ReactNode\n url?: string\n}) {\n const fileInputRef = React.useRef<HTMLInputElement>(null)\n const viewportRef = React.useRef<HTMLDivElement | null>(null)\n const [viewportElement, setViewportElement] =\n React.useState<HTMLDivElement | null>(null)\n const [viewerShellRef, viewerShellWidth] = useElementWidth<HTMLDivElement>()\n const [uploadedDocxFile, setUploadedDocxFile] =\n React.useState<UploadedDocxFile | null>(null)\n const [sidebarOpen, setSidebarOpen] = React.useState(false)\n const activePageStore = React.useMemo(() => createDocxActivePageStore(), [])\n const resolvedDefaultZoomLevel = normalizeDocxZoomLevel(defaultZoom)\n const activeUploadedDocxFile =\n uploadedDocxFile?.sourceUrl === url ? uploadedDocxFile : null\n const documentKey = activeUploadedDocxFile?.identity ?? url ?? ""\n const setActivePage = activePageStore.setActivePage\n const sidebarInline = useInlineThumbnailSidebar(viewerShellWidth)\n const viewerBackgroundColor =\n "color-mix(in oklab, var(--muted) 40%, transparent)"\n const displayFileName = React.useMemo(\n () =>\n activeUploadedDocxFile?.file.name ??\n (url ? formatDocumentName(fileName, url) : (fileName ?? "document.docx")),\n [activeUploadedDocxFile?.file.name, fileName, url]\n )\n const [initialDocumentTheme] = React.useState<DocxDocumentTheme>(() =>\n effectiveIsDark ? "dark" : "light"\n )\n const editorOptions = React.useMemo(\n () => ({\n initialDocumentTheme,\n initialFileName: displayFileName,\n }),\n [displayFileName, initialDocumentTheme]\n )\n const editor = useDocxEditor(editorOptions)\n const { layout: pageLayout } = useDocxPageLayout(editor)\n const { importDocxFile, setDocumentTheme, status } = editor\n const { showComments, setShowComments } = useDocxComments(editor)\n const { showTrackedChanges, setShowTrackedChanges } =\n useDocxTrackChanges(editor)\n const [reportedPageCount, setReportedPageCount] = React.useState(0)\n const [zoomState, setZoomState] = React.useState({\n documentKey: "",\n level: resolvedDefaultZoomLevel,\n resolvedZoom:\n typeof resolvedDefaultZoomLevel === "number"\n ? resolvedDefaultZoomLevel\n : DEFAULT_ZOOM,\n })\n const activeZoomState =\n zoomState.documentKey === documentKey\n ? zoomState\n : {\n documentKey,\n level: resolvedDefaultZoomLevel,\n resolvedZoom:\n typeof resolvedDefaultZoomLevel === "number"\n ? resolvedDefaultZoomLevel\n : DEFAULT_ZOOM,\n }\n const setZoomLevel = React.useCallback(\n (level: ViewerZoomLevel) => {\n setZoomState({\n documentKey,\n level,\n resolvedZoom:\n typeof level === "number" ? level : activeZoomState.resolvedZoom,\n })\n },\n [activeZoomState.resolvedZoom, documentKey]\n )\n const handleZoomChange = React.useCallback(\n (state: ViewerZoomState) => {\n setZoomState({ documentKey, ...state })\n },\n [documentKey]\n )\n const [loadError, setLoadError] = React.useState<string>()\n const [isLoadingDocument, setIsLoadingDocument] = React.useState(true)\n const [isPreparingDownload, setIsPreparingDownload] = React.useState(false)\n const shouldShowDocumentSpinner = useDelayedLoadingIndicator(\n isLoadingDocument,\n DOCX_LOADING_INDICATOR_DELAY_MS\n )\n const loadingState = (\n <ViewerLoadingSurface showSpinner={shouldShowDocumentSpinner} />\n )\n const documentTheme = effectiveIsDark ? "dark" : "light"\n const renderTrackedChangeCard = React.useMemo(\n () => createDocxTrackedChangeCardRenderer(documentTheme),\n [documentTheme]\n )\n const renderCommentCard = React.useMemo(\n () => createDocxCommentCardRenderer(documentTheme),\n [documentTheme]\n )\n const hasDocument = Boolean(url || activeUploadedDocxFile)\n const pageCount =\n hasDocument && !isLoadingDocument && !loadError\n ? Math.max(1, reportedPageCount || editor.totalPages)\n : 0\n const thumbnailSidebarVisible = Boolean(\n sidebarOpen && (pageCount || isLoadingDocument)\n )\n const controlsDisabled =\n !hasDocument || isLoadingDocument || Boolean(loadError)\n const handlePageCountChange = React.useCallback((nextPageCount: number) => {\n setReportedPageCount(Math.max(1, Math.round(nextPageCount || 1)))\n }, [])\n const setViewportRef = React.useCallback((element: HTMLDivElement | null) => {\n viewportRef.current = element\n setViewportElement(element)\n }, [])\n const pageVirtualization = React.useMemo(\n () => ({\n enabled: true,\n overscan: 1,\n scrollElement: viewportElement,\n }),\n [viewportElement]\n )\n const handleDownload = React.useCallback(async () => {\n if (isPreparingDownload) return\n if (!activeUploadedDocxFile && !url) return\n\n setIsPreparingDownload(true)\n\n try {\n await downloadDocxFile({\n file: activeUploadedDocxFile?.file,\n fileName: displayFileName,\n url,\n })\n } catch (error) {\n console.error(error)\n } finally {\n setIsPreparingDownload(false)\n }\n }, [activeUploadedDocxFile, displayFileName, isPreparingDownload, url])\n useSuppressDocxPaddingWarning(!isLoadingDocument && !loadError)\n\n React.useEffect(() => {\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }, [documentKey, setActivePage])\n\n React.useEffect(() => {\n setDocumentTheme(effectiveIsDark ? "dark" : "light")\n }, [effectiveIsDark, setDocumentTheme])\n\n React.useEffect(() => {\n if (\n status.startsWith("Failed to load file") ||\n status === "Only .docx files are supported"\n ) {\n const frame = window.requestAnimationFrame(() => {\n setLoadError(status)\n setIsLoadingDocument(false)\n })\n\n return () => window.cancelAnimationFrame(frame)\n }\n }, [status])\n\n // Imports mutate the shared editor instance; concurrent calls (effect\n // re-runs, StrictMode double-invoke) race inside the parser and surface as\n // bogus "Invalid DOCX ZIP" errors, so every import is chained through here.\n const importQueueRef = React.useRef<Promise<void>>(Promise.resolve())\n\n React.useEffect(() => {\n let isCurrent = true\n\n async function load() {\n // Superseded while queued — let the newest import run instead.\n if (!isCurrent) return\n if (!activeUploadedDocxFile && !url) {\n setIsLoadingDocument(false)\n setLoadError(undefined)\n setReportedPageCount(0)\n return\n }\n\n setIsLoadingDocument(true)\n setLoadError(undefined)\n setReportedPageCount(0)\n\n try {\n const docxFile =\n activeUploadedDocxFile?.file ??\n (url ? await loadDocxFile(url, displayFileName) : null)\n if (!docxFile) return\n await importDocxFile(docxFile)\n\n if (isCurrent) {\n setIsLoadingDocument(false)\n setActivePage(1)\n viewportRef.current?.scrollTo({ top: 0, left: 0 })\n }\n } catch (error) {\n if (isCurrent) {\n setLoadError(\n error instanceof Error ? error.message : "Unknown DOCX load error"\n )\n setIsLoadingDocument(false)\n }\n }\n }\n\n importQueueRef.current = importQueueRef.current.then(load)\n\n return () => {\n isCurrent = false\n }\n }, [\n activeUploadedDocxFile,\n displayFileName,\n importDocxFile,\n setActivePage,\n url,\n ])\n\n const updateActivePageFromViewport = React.useCallback(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n const viewportRect = viewport.getBoundingClientRect()\n const viewportCenter = viewportRect.top + viewportRect.height / 2\n let closestPage = 1\n let closestDistance = Number.POSITIVE_INFINITY\n\n viewport\n .querySelectorAll<HTMLElement>(\n \'[data-docx-page-wrapper="true"][data-index]\'\n )\n .forEach((page) => {\n const pageIndex = Number(page.dataset.index)\n if (!Number.isFinite(pageIndex)) return\n\n const pageRect = page.getBoundingClientRect()\n const pageCenter = pageRect.top + pageRect.height / 2\n const distance = Math.abs(pageCenter - viewportCenter)\n\n if (distance < closestDistance) {\n closestDistance = distance\n closestPage = pageIndex + 1\n }\n })\n\n activePageStore.setActivePage((currentPage) =>\n currentPage === closestPage ? currentPage : closestPage\n )\n }, [activePageStore, pageCount])\n\n React.useEffect(() => {\n const viewport = viewportRef.current\n if (!viewport || !pageCount) return\n\n let frameId = 0\n const handleScroll = () => {\n window.cancelAnimationFrame(frameId)\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n }\n\n frameId = window.requestAnimationFrame(updateActivePageFromViewport)\n viewport.addEventListener("scroll", handleScroll, { passive: true })\n\n return () => {\n window.cancelAnimationFrame(frameId)\n viewport.removeEventListener("scroll", handleScroll)\n }\n }, [pageCount, updateActivePageFromViewport])\n\n const scrollToPage = React.useCallback(\n (pageNumber: number) => {\n const viewport = viewportRef.current\n const targetPageIndex = pageNumber - 1\n const page = viewport?.querySelector<HTMLElement>(\n `[data-docx-page-wrapper="true"][data-index="${targetPageIndex}"]`\n )\n\n setActivePage(pageNumber)\n\n if (!viewport) return\n\n if (!page) {\n const pageStridePx =\n (pageLayout.pageHeightPx + pageLayout.viewportDefaults.pageGapPx) *\n (activeZoomState.resolvedZoom / 100)\n\n viewport.scrollTo({\n top: Math.max(0, targetPageIndex * pageStridePx - 24),\n behavior: "auto",\n })\n return\n }\n\n viewport.scrollTo({\n top:\n page.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop -\n 24,\n behavior: "auto",\n })\n },\n [\n pageLayout.pageHeightPx,\n pageLayout.viewportDefaults.pageGapPx,\n setActivePage,\n activeZoomState.resolvedZoom,\n ]\n )\n\n async function handleUpload(event: React.ChangeEvent<HTMLInputElement>) {\n const file = event.target.files?.[0]\n event.target.value = ""\n\n if (!file) return\n\n setZoomLevel(resolvedDefaultZoomLevel)\n setActivePage(1)\n setReportedPageCount(0)\n setUploadedDocxFile({\n file,\n identity: `${file.name}-${file.size}-${file.lastModified}`,\n sourceUrl: url,\n })\n }\n\n const content = (\n <div\n className={cn(\n "flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",\n className\n )}\n >\n <input\n ref={fileInputRef}\n type="file"\n accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"\n className="hidden"\n onChange={handleUpload}\n />\n {showToolbar ? (\n <DocxToolbar\n activePageStore={activePageStore}\n controlsDisabled={controlsDisabled}\n isDark={effectiveIsDark}\n isPreparingDownload={isPreparingDownload}\n onDownload={handleDownload}\n onIsDarkChange={setNightRenderEnabled}\n onPageChange={scrollToPage}\n onShowCommentsChange={setShowComments}\n onShowTrackedChangesChange={setShowTrackedChanges}\n onToggleSidebar={() => setSidebarOpen((open) => !open)}\n onUploadClick={() => fileInputRef.current?.click()}\n pageCount={pageCount}\n onZoomChange={setZoomLevel}\n showComments={showComments}\n showDownloadButton={showDownload}\n showNightRenderToggle={shouldRenderNightMode}\n showTrackedChanges={showTrackedChanges}\n showUploadButton={showUpload}\n toolbarActions={toolbarActions}\n resolvedZoom={activeZoomState.resolvedZoom}\n zoomLevel={activeZoomState.level}\n />\n ) : null}\n <div\n ref={viewerShellRef}\n className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/30"\n >\n <DocumentViewerThumbnailSidebar\n inline={sidebarInline}\n open={thumbnailSidebarVisible}\n >\n <DocxThumbnailSidebarContent\n activePageStore={activePageStore}\n displayFileName={displayFileName}\n editor={editor}\n isLoadingDocument={isLoadingDocument}\n onSelectPage={scrollToPage}\n pageCount={pageCount}\n reportedPageCount={reportedPageCount}\n sidebarOpen={thumbnailSidebarVisible}\n />\n </DocumentViewerThumbnailSidebar>\n <ScrollArea\n className="min-h-0 flex-1"\n style={{ backgroundColor: viewerBackgroundColor }}\n viewportClassName="px-4 py-6"\n viewportProps={{\n "aria-label": "DOCX document",\n onMouseDown: (event) => {\n if (isInteractiveViewerTarget(event.target)) return\n event.currentTarget.focus({ preventScroll: true })\n },\n tabIndex: 0,\n }}\n viewportRef={setViewportRef}\n >\n {!url && !activeUploadedDocxFile ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm shadow-xs">\n <div className="font-medium">\n Upload a Word document to preview\n </div>\n <div className="mt-1 text-muted-foreground">\n Pass a DOCX URL with the <code>src</code> prop or upload a\n file.\n </div>\n <div className="mt-1 text-muted-foreground">\n Legacy <code>.doc</code> support is limited and experimental;\n convert to DOCX for best fidelity.\n </div>\n <Button\n type="button"\n variant="outline"\n size="sm"\n className="mt-4"\n onClick={() => fileInputRef.current?.click()}\n >\n <IconPlaceholder\n lucide="Upload"\n tabler="IconUpload"\n hugeicons="Upload01Icon"\n phosphor="UploadSimpleIcon"\n remixicon="RiUpload2Line"\n className="size-4"\n />\n Upload Word document\n </Button>\n </div>\n </div>\n ) : loadError ? (\n <div className="grid h-full min-h-96 place-items-center p-6 text-center">\n <div className="max-w-md rounded-lg border bg-background p-4 text-sm text-destructive shadow-xs">\n <div className="font-medium">Unable to display DOCX</div>\n <div className="mt-1 text-muted-foreground">{loadError}</div>\n </div>\n </div>\n ) : isLoadingDocument ? (\n loadingState\n ) : (\n <div className="flex min-h-full w-max min-w-full justify-center">\n <div className={cn(effectiveIsDark && "docx-night-reader-shell")}>\n <DocxEditorViewer\n editor={editor}\n mode="read-only"\n zoom={activeZoomState.level}\n onZoomChange={handleZoomChange}\n showTrackedChanges={showTrackedChanges}\n renderTrackedChangeCard={renderTrackedChangeCard}\n showComments={showComments}\n renderCommentCard={renderCommentCard}\n loadingState={loadingState}\n pageBackgroundColor={effectiveIsDark ? "#0a0a0a" : undefined}\n pageGapBackgroundColor={viewerBackgroundColor}\n pageVirtualization={pageVirtualization}\n deferInitialPaginationPaint={false}\n onPageCountChange={handlePageCountChange}\n />\n </div>\n </div>\n )}\n </ScrollArea>\n </div>\n </div>\n )\n\n return Layout ? (\n <Layout\n model={controlsDisabled ? undefined : editor.model}\n viewportRef={viewportRef}\n isLoading={isLoadingDocument}\n loadError={loadError}\n >\n {content}\n </Layout>\n ) : (\n content\n )\n}\n'export function DocxViewerSource() {return (diff --git a/apps/v4/components/extend/bounding-box-citations.tsx b/apps/v4/components/extend/bounding-box-citations.tsxindex 6eb0993..8da8be2 100644--- a/apps/v4/components/extend/bounding-box-citations.tsx+++ b/apps/v4/components/extend/bounding-box-citations.tsx@@ -271,6 +271,7 @@ const CODE_HIGHLIGHTER_OPTIONS = {} satisfies WorkerInitializationRenderOptionsconst CODE_WORKER_POOL_OPTIONS = {+ poolSize: 2,workerFactory: () =>new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), {type: "module",@@ -2420,7 +2421,7 @@ export function HumanReviewPanel({</div></ScrollArea></TabsContent>- <TabsContent value="json" keepMounted className="min-h-0 flex-1">+ <TabsContent value="json" className="min-h-0 flex-1">{showExpected ? (<JsonDiffViewactual={actualValues}diff --git a/apps/v4/components/extend/docx-editor.tsx b/apps/v4/components/extend/docx-editor.tsxindex 30941f4..9a5d8c2 100644--- a/apps/v4/components/extend/docx-editor.tsx+++ b/apps/v4/components/extend/docx-editor.tsx@@ -1867,6 +1867,79 @@ function DocxEditorToolbar({)}+function DocxEditorThumbnails({+ editor,+ pageCount,+ activePage,+ displayFileName,+ scrollToPage,+}: {+ editor: DocxEditorController+ pageCount: number+ activePage: number+ displayFileName: string+ scrollToPage: (page: number) => void+}) {+ const thumbnailEditor = React.useMemo<DocxEditorController>(+ () => ({+ ...editor,+ totalPages: Math.max(editor.totalPages, pageCount),+ }),+ [editor, pageCount]+ )+ const thumbnailOptions = React.useMemo(+ () => ({+ pixelRatio: 2,+ resolution: {+ maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,+ maxWidth: DOCX_THUMBNAIL_WIDTH,+ },+ }),+ []+ )+ const { thumbnails } = useDocxViewerThumbnails(+ thumbnailEditor,+ thumbnailOptions+ )+ return (+ <div className="flex flex-col items-center gap-3">+ {thumbnails.slice(0, pageCount).map((thumbnail) => (+ <Button+ key={thumbnail.pageIndex}+ type="button"+ variant="ghost"+ size="sm"+ className={cn(+ "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",+ thumbnail.pageNumber === activePage &&+ "bg-sidebar-accent text-foreground",+ thumbnail.pageNumber !== activePage && "text-muted-foreground"+ )}+ onFocus={(event) => event.currentTarget.blur()}+ onClick={() => scrollToPage(thumbnail.pageNumber)}+ >+ <DocxSidebarThumbnail+ canvasRef={thumbnail.canvasRef}+ displayFileName={displayFileName}+ hasError={thumbnail.status === "error"}+ isActive={thumbnail.pageNumber === activePage}+ isLoading={+ !thumbnail.isMounted &&+ thumbnail.status !== "ready" &&+ thumbnail.status !== "error"+ }+ pageNumber={thumbnail.pageNumber}+ pixelHeightPx={thumbnail.pixelHeightPx}+ pixelWidthPx={thumbnail.pixelWidthPx}+ previewAspectRatio={thumbnail.aspectRatio}+ />+ {thumbnail.pageNumber}+ </Button>+ ))}+ </div>+ )+}+export function DocxEditorPreview({className,defaultZoomScale = DOCX_EDITOR_DEFAULT_ZOOM_SCALE,@@ -1954,27 +2027,6 @@ function DocxEditorContent({const { layout: pageLayout } = useDocxPageLayout(editor)const { importDocxFile, setDocumentTheme, status } = editorconst [reportedPageCount, setReportedPageCount] = React.useState(0)- const thumbnailEditor = React.useMemo<DocxEditorController>(- () => ({- ...editor,- totalPages: Math.max(editor.totalPages, reportedPageCount),- }),- [editor, reportedPageCount]- )- const thumbnailOptions = React.useMemo(- () => ({- pixelRatio: 2,- resolution: {- maxHeight: DOCX_THUMBNAIL_WIDTH * 1.35,- maxWidth: DOCX_THUMBNAIL_WIDTH,- },- }),- []- )- const { thumbnails } = useDocxViewerThumbnails(- thumbnailEditor,- thumbnailOptions- )const shouldShowDocumentSpinner = useDelayedLoadingIndicator(isLoadingDocument,DOCX_LOADING_INDICATOR_DELAY_MS@@ -2299,42 +2351,15 @@ function DocxEditorContent({<div className="mx-auto mt-3 h-3 w-10 rounded-full bg-muted" /></>) : (- <div className="flex flex-col items-center gap-3">- {thumbnails.slice(0, pageCount || 0).map((thumbnail) => (- <Button- key={thumbnail.pageIndex}- type="button"- variant="ghost"- size="sm"- className={cn(- "!h-auto w-full flex-col items-center gap-2 p-2 text-xs shadow-none hover:bg-sidebar-accent",- thumbnail.pageNumber === activePage &&- "bg-sidebar-accent text-foreground",- thumbnail.pageNumber !== activePage &&- "text-muted-foreground"- )}- onFocus={(event) => event.currentTarget.blur()}- onClick={() => scrollToPage(thumbnail.pageNumber)}- >- <DocxSidebarThumbnail- canvasRef={thumbnail.canvasRef}- displayFileName={displayFileName}- hasError={thumbnail.status === "error"}- isActive={thumbnail.pageNumber === activePage}- isLoading={- !thumbnail.isMounted &&- thumbnail.status !== "ready" &&- thumbnail.status !== "error"- }- pageNumber={thumbnail.pageNumber}- pixelHeightPx={thumbnail.pixelHeightPx}- pixelWidthPx={thumbnail.pixelWidthPx}- previewAspectRatio={thumbnail.aspectRatio}- />- {thumbnail.pageNumber}- </Button>- ))}- </div>+ thumbnailSidebarOpen && (+ <DocxEditorThumbnails+ editor={editor}+ pageCount={pageCount}+ activePage={activePage}+ displayFileName={displayFileName}+ scrollToPage={scrollToPage}+ />+ ))}</div></ScrollArea>@@ -2404,7 +2429,6 @@ function DocxEditorContent({}pageGapBackgroundColor={viewerBackgroundColor}pageVirtualization={pageVirtualization}- deferInitialPaginationPaint={false}onPageCountChange={handlePageCountChange}/></div>diff --git a/apps/v4/components/extend/docx-viewer.tsx b/apps/v4/components/extend/docx-viewer.tsxindex 30a1189..1c61e4c 100644--- a/apps/v4/components/extend/docx-viewer.tsx+++ b/apps/v4/components/extend/docx-viewer.tsx@@ -1097,8 +1097,17 @@ function DocxThumbnailSidebarContent({)}+export type DocxViewerLayoutProps = {+ children: React.ReactNode+ model?: DocxEditorController["model"]+ viewportRef: React.RefObject<HTMLDivElement | null>+ isLoading: boolean+ loadError?: string+}+export function DocxViewerPreview({className,+ layout: Layout,defaultZoom = DEFAULT_ZOOM,fileName,isDark,@@ -1110,6 +1119,7 @@ export function DocxViewerPreview({toolbarActions,}: {className?: string+ layout?: React.ComponentType<DocxViewerLayoutProps>defaultZoom?: ViewerZoomLevelfileName?: stringisDark: boolean@@ -1122,6 +1132,7 @@ export function DocxViewerPreview({}) {return (<DocxViewerContent+ layout={Layout}className={className}defaultZoom={defaultZoom}effectiveIsDark={isDark}@@ -1139,6 +1150,7 @@ export function DocxViewerPreview({function DocxViewerContent({className,+ layout: Layout,defaultZoom,effectiveIsDark,fileName,@@ -1151,6 +1163,7 @@ function DocxViewerContent({url,}: {className?: string+ layout?: React.ComponentType<DocxViewerLayoutProps>defaultZoom?: ViewerZoomLeveleffectiveIsDark: booleanfileName?: string@@ -1490,7 +1503,7 @@ function DocxViewerContent({})}- return (+ const content = (<divclassName={cn("flex h-[640px] min-h-0 flex-col overflow-hidden bg-background",@@ -1630,4 +1643,17 @@ function DocxViewerContent({</div></div>)++ return Layout ? (+ <Layout+ model={controlsDisabled ? undefined : editor.model}+ viewportRef={viewportRef}+ isLoading={isLoadingDocument}+ loadError={loadError}+ >+ {content}+ </Layout>+ ) : (+ content+ )}diff --git a/apps/v4/components/extend/layout-blocks-panel.tsx b/apps/v4/components/extend/layout-blocks-panel.tsxnew file mode 100644index 0000000..c85242b--- /dev/null+++ b/apps/v4/components/extend/layout-blocks-panel.tsx@@ -0,0 +1,452 @@+"use client"++import * as React from "react"+import { useVirtualizer } from "@tanstack/react-virtual"++import type { RegistryIconProps } from "@/lib/registry-icon-props"+import { cn } from "@/lib/utils"+import { ScrollArea } from "@/components/ui/scroll-area"+import { IconPlaceholder } from "@/components/icon-placeholder"++function AlignBoxBottomCenterGlyph(props: RegistryIconProps) {+ return (+ <IconPlaceholder+ lucide="AlignVerticalJustifyEnd"+ tabler="IconAlignBoxBottomCenter"+ hugeicons="AlignBoxBottomCenterIcon"+ phosphor="AlignBottomIcon"+ remixicon="RiAlignBottom"+ {...props}+ />+ )+}++function Heading01Glyph(props: RegistryIconProps) {+ return (+ <IconPlaceholder+ lucide="Heading1"+ tabler="IconH1"+ hugeicons="Heading01Icon"+ phosphor="TextHOneIcon"+ remixicon="RiH1"+ {...props}+ />+ )+}++function ImageCompositionGlyph(props: RegistryIconProps) {+ return (+ <IconPlaceholder+ lucide="Image"+ tabler="IconPhoto"+ hugeicons="ImageCompositionIcon"+ phosphor="ImageSquareIcon"+ remixicon="RiImageLine"+ {...props}+ />+ )+}++function LeftToRightListBulletGlyph(props: RegistryIconProps) {+ return (+ <IconPlaceholder+ lucide="Columns3Icon"+ tabler="IconLayoutColumns"+ hugeicons="LeftToRightListBulletIcon"+ phosphor="ColumnsIcon"+ remixicon="RiLayoutColumnLine"+ {...props}+ />+ )+}++function ParagraphGlyph(props: RegistryIconProps) {+ return (+ <IconPlaceholder+ lucide="Pilcrow"+ tabler="IconPilcrow"+ hugeicons="ParagraphIcon"+ phosphor="ParagraphIcon"+ remixicon="RiParagraph"+ {...props}+ />+ )+}++function Table01Glyph(props: RegistryIconProps) {+ return (+ <IconPlaceholder+ lucide="Table"+ tabler="IconTable"+ hugeicons="Table01Icon"+ phosphor="TableIcon"+ remixicon="RiTableLine"+ {...props}+ />+ )+}++function TextCenterlineCenterTopGlyph(props: RegistryIconProps) {+ return (+ <IconPlaceholder+ lucide="PanelTop"+ tabler="IconLayoutNavbar"+ hugeicons="TextCenterlineCenterTopIcon"+ phosphor="AlignTopSimpleIcon"+ remixicon="RiLayoutTopLine"+ {...props}+ />+ )+}++function TextNumberSignGlyph(props: RegistryIconProps) {+ return (+ <IconPlaceholder+ lucide="Hash"+ tabler="IconHash"+ hugeicons="TextNumberSignIcon"+ phosphor="HashIcon"+ remixicon="RiHashtag"+ {...props}+ />+ )+}++export type LayoutBlockType =+ | "heading"+ | "paragraph"+ | "list"+ | "table"+ | "figure"+ | "header"+ | "footer"+ | "page_number"++export type LayoutBlockItem = {+ id: string+ type: LayoutBlockType+ label?: string+ text: string+ page?: number+ confidence?: number+}++export const layoutBlockStyles: Record<+ LayoutBlockType,+ {+ label: string+ icon: React.ComponentType<RegistryIconProps>+ color: string+ overlay: string+ mutedOverlay: string+ ring: string+ badge: string+ }+> = {+ heading: {+ label: "Heading",+ icon: Heading01Glyph,+ color: "#8b5cf6",+ overlay:+ "border-violet-500/70 bg-violet-500/10 shadow-[0_4px_16px_rgb(139_92_246_/_12%)]",+ mutedOverlay: "border-violet-500/35 bg-violet-500/5",+ ring: "border-violet-500/60 bg-violet-500/5",+ badge:+ "bg-violet-50 text-violet-600 dark:bg-violet-300/10 dark:text-violet-300",+ },+ paragraph: {+ label: "Paragraph",+ icon: ParagraphGlyph,+ color: "#3b82f6",+ overlay:+ "border-blue-500/70 bg-blue-500/10 shadow-[0_4px_16px_rgb(59_130_246_/_12%)]",+ mutedOverlay: "border-blue-500/35 bg-blue-500/5",+ ring: "border-blue-500/60 bg-blue-500/5",+ badge: "bg-blue-50 text-blue-600 dark:bg-blue-300/10 dark:text-blue-300",+ },+ list: {+ label: "List",+ icon: LeftToRightListBulletGlyph,+ color: "#10b981",+ overlay:+ "border-emerald-500/70 bg-emerald-500/10 shadow-[0_4px_16px_rgb(16_185_129_/_12%)]",+ mutedOverlay: "border-emerald-500/35 bg-emerald-500/5",+ ring: "border-emerald-500/60 bg-emerald-500/5",+ badge:+ "bg-emerald-50 text-emerald-600 dark:bg-emerald-300/10 dark:text-emerald-300",+ },+ table: {+ label: "Table",+ icon: Table01Glyph,+ color: "#f59e0b",+ overlay:+ "border-amber-500/70 bg-amber-500/10 shadow-[0_4px_16px_rgb(245_158_11_/_12%)]",+ mutedOverlay: "border-amber-500/35 bg-amber-500/5",+ ring: "border-amber-500/60 bg-amber-500/5",+ badge:+ "bg-amber-50 text-amber-600 dark:bg-amber-300/10 dark:text-amber-300",+ },+ figure: {+ label: "Figure",+ icon: ImageCompositionGlyph,+ color: "#f43f5e",+ overlay:+ "border-rose-500/70 bg-rose-500/10 shadow-[0_4px_16px_rgb(244_63_94_/_12%)]",+ mutedOverlay: "border-rose-500/35 bg-rose-500/5",+ ring: "border-rose-500/60 bg-rose-500/5",+ badge: "bg-rose-50 text-rose-600 dark:bg-rose-300/10 dark:text-rose-300",+ },+ header: {+ label: "Header",+ icon: TextCenterlineCenterTopGlyph,+ color: "#06b6d4",+ overlay:+ "border-cyan-500/70 bg-cyan-500/10 shadow-[0_4px_16px_rgb(6_182_212_/_12%)]",+ mutedOverlay: "border-cyan-500/35 bg-cyan-500/5",+ ring: "border-cyan-500/60 bg-cyan-500/5",+ badge: "bg-cyan-50 text-cyan-600 dark:bg-cyan-300/10 dark:text-cyan-300",+ },+ footer: {+ label: "Footer",+ icon: AlignBoxBottomCenterGlyph,+ color: "#64748b",+ overlay:+ "border-slate-500/70 bg-slate-500/10 shadow-[0_4px_16px_rgb(100_116_139_/_12%)]",+ mutedOverlay: "border-slate-500/35 bg-slate-500/5",+ ring: "border-slate-500/60 bg-slate-500/5",+ badge:+ "bg-slate-50 text-slate-600 dark:bg-slate-300/10 dark:text-slate-300",+ },+ page_number: {+ label: "Page number",+ icon: TextNumberSignGlyph,+ color: "#71717a",+ overlay:+ "border-zinc-500/70 bg-zinc-500/10 shadow-[0_4px_16px_rgb(113_113_122_/_12%)]",+ mutedOverlay: "border-zinc-500/35 bg-zinc-500/5",+ ring: "border-zinc-500/60 bg-zinc-500/5",+ badge: "bg-zinc-50 text-zinc-600 dark:bg-zinc-300/10 dark:text-zinc-300",+ },+}++const BLOCK_ROW_MIN_ESTIMATE = 92+const BLOCK_ROW_VERTICAL_CHROME = 62+const BLOCK_LINE_HEIGHT = 20+const BLOCK_ESTIMATED_CHARS_PER_LINE = 42+const BLOCK_ROW_GAP = 8+const BLOCK_LIST_PADDING = 12+function estimateRowHeight(block: LayoutBlockItem, clampText: boolean) {+ const plainText = block.text+ .replace(/<[^>]*>/g, "")+ .replace(/\s+/g, " ")+ .trim()+ const explicitLineCount = block.text.split(/\n+/).filter(Boolean).length+ const wrappedLineCount = Math.max(+ explicitLineCount,+ Math.ceil(plainText.length / BLOCK_ESTIMATED_CHARS_PER_LINE)+ )+ const contentHeight =+ Math.max(1, clampText ? Math.min(3, wrappedLineCount) : wrappedLineCount) *+ BLOCK_LINE_HEIGHT+ const typeExtraHeight =+ block.type === "figure" ? 44 : block.type === "table" ? 28 : 0++ return Math.max(+ BLOCK_ROW_MIN_ESTIMATE,+ BLOCK_ROW_VERTICAL_CHROME + contentHeight + typeExtraHeight + BLOCK_ROW_GAP+ )+}++function LayoutBlockCard<Block extends LayoutBlockItem>({+ block,+ isActive,+ onFocusBlock,+ onBlurBlock,+ onSelectBlock,+ renderText,+}: {+ block: Block+ isActive: boolean+ onFocusBlock: (block: Block) => void+ onBlurBlock?: () => void+ onSelectBlock?: (block: Block) => void+ renderText?: (text: string) => React.ReactNode+}) {+ const style = layoutBlockStyles[block.type]++ return (+ <button+ type="button"+ aria-pressed={isActive}+ onMouseLeave={onBlurBlock}+ onBlur={onBlurBlock}+ onClick={() => {+ onFocusBlock(block)+ onSelectBlock?.(block)+ }}+ onMouseEnter={() => onFocusBlock(block)}+ onFocus={() => onFocusBlock(block)}+ className={cn(+ "w-full rounded-lg border bg-background p-3 text-left hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",+ isActive && cn("shadow-[0_0_0_1px_rgb(0_0_0_/_4%)]", style.ring)+ )}+ >+ <div className="min-w-0">+ <div className="flex items-center justify-between gap-2">+ <div className="flex min-w-0 items-center gap-2">+ <div+ className={cn(+ "inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium",+ style.badge+ )}+ >+ <style.icon className="size-3.5" />+ {block.label ?? style.label}+ </div>+ {block.confidence !== undefined && (+ <div className="truncate text-xs text-muted-foreground">+ {Math.round(block.confidence * 100)}%+ </div>+ )}+ </div>+ {block.page !== undefined && (+ <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">+ p. {block.page}+ </div>+ )}+ </div>+ <div className="mt-2 text-sm text-foreground/90">+ {renderText ? (+ renderText(block.text)+ ) : (+ <p className="line-clamp-3 text-[13px] leading-5 wrap-anywhere whitespace-pre-line">+ {block.text}+ </p>+ )}+ </div>+ </div>+ </button>+ )+}++export function LayoutBlocksPanel<Block extends LayoutBlockItem>({+ activeBlockId,+ blocks,+ className,+ heading,+ ariaLabel,+ emptyMessage = "No layout blocks found.",+ onBlockFocus,+ onBlockBlur,+ onBlockSelect,+ renderText,+}: {+ activeBlockId?: string+ blocks: readonly Block[]+ className?: string+ heading?: string+ ariaLabel?: string+ emptyMessage?: string+ onBlockFocus?: (block: Block) => void+ onBlockBlur?: () => void+ onBlockSelect?: (block: Block) => void+ renderText?: (text: string) => React.ReactNode+}) {+ const scrollViewportRef = React.useRef<HTMLDivElement | null>(null)+ const [localActiveBlockId, setLocalActiveBlockId] = React.useState<string>()+ const activeId = activeBlockId ?? localActiveBlockId+ const focusedBlockId = blocks.some((block) => block.id === activeId)+ ? activeId+ : blocks[0]?.id++ const estimateBlockSize = React.useCallback(+ (index: number) => {+ const block = blocks[index]+ return block+ ? estimateRowHeight(block, !renderText)+ : BLOCK_ROW_MIN_ESTIMATE+ },+ [blocks, renderText]+ )+ const virtualizer = useVirtualizer({+ count: blocks.length,+ estimateSize: estimateBlockSize,+ getItemKey: (index) => blocks[index]?.id ?? index,+ getScrollElement: () => scrollViewportRef.current,+ overscan: 6,+ })++ const focusBlock = React.useCallback(+ (block: Block) => {+ if (block.id === focusedBlockId) return+ setLocalActiveBlockId(block.id)+ onBlockFocus?.(block)+ },+ [focusedBlockId, onBlockFocus]+ )++ return (+ <aside+ aria-label={ariaLabel}+ className={cn("flex h-[420px] min-h-0 flex-col bg-background", className)}+ >+ {heading && (+ <div className="flex items-center justify-between border-b px-4 py-3 text-sm font-medium">+ {heading}+ <span className="text-xs text-muted-foreground">{blocks.length}</span>+ </div>+ )}+ <ScrollArea+ className="min-h-0 flex-1"+ scrollFade+ viewportRef={scrollViewportRef}+ >+ {blocks.length ? (+ <div+ className="relative"+ style={{+ height: virtualizer.getTotalSize() + BLOCK_LIST_PADDING * 2,+ }}+ >+ {virtualizer.getVirtualItems().map((virtualRow) => {+ const block = blocks[virtualRow.index]+ if (!block) return null++ return (+ <div+ key={virtualRow.key}+ ref={virtualizer.measureElement}+ data-index={virtualRow.index}+ className="absolute top-0 right-3 left-3 pb-2 [contain:layout_paint]"+ style={{+ transform: `translateY(${+ virtualRow.start + BLOCK_LIST_PADDING+ }px)`,+ }}+ >+ <LayoutBlockCard+ block={block}+ isActive={block.id === focusedBlockId}+ onFocusBlock={focusBlock}+ onBlurBlock={onBlockBlur}+ onSelectBlock={onBlockSelect}+ renderText={renderText}+ />+ </div>+ )+ })}+ </div>+ ) : (+ <div className="p-3">+ <div+ role="status"+ className="rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground"+ >+ {emptyMessage}+ </div>+ </div>+ )}+ </ScrollArea>+ </aside>+ )+}diff --git a/apps/v4/components/extend/layout-blocks.tsx b/apps/v4/components/extend/layout-blocks.tsxindex c6a281f..3792e5b 100644--- a/apps/v4/components/extend/layout-blocks.tsx+++ b/apps/v4/components/extend/layout-blocks.tsx@@ -1,120 +1,17 @@"use client"import * as React from "react"-import { useVirtualizer } from "@tanstack/react-virtual"import ReactMarkdown from "react-markdown"import rehypeRaw from "rehype-raw"import rehypeSanitize, { defaultSchema } from "rehype-sanitize"import remarkGfm from "remark-gfm"-import type { RegistryIconProps } from "@/lib/registry-icon-props"import { cn } from "@/lib/utils"-import { ScrollArea } from "@/components/ui/scroll-area"-import { IconPlaceholder } from "@/components/icon-placeholder"--function AlignBoxBottomCenterGlyph(props: RegistryIconProps) {- return (- <IconPlaceholder- lucide="AlignVerticalJustifyEnd"- tabler="IconAlignBoxBottomCenter"- hugeicons="AlignBoxBottomCenterIcon"- phosphor="AlignBottomIcon"- remixicon="RiAlignBottom"- {...props}- />- )-}--function Heading01Glyph(props: RegistryIconProps) {- return (- <IconPlaceholder- lucide="Heading1"- tabler="IconH1"- hugeicons="Heading01Icon"- phosphor="TextHOneIcon"- remixicon="RiH1"- {...props}- />- )-}--function ImageCompositionGlyph(props: RegistryIconProps) {- return (- <IconPlaceholder- lucide="Image"- tabler="IconPhoto"- hugeicons="ImageCompositionIcon"- phosphor="ImageSquareIcon"- remixicon="RiImageLine"- {...props}- />- )-}--function LeftToRightListBulletGlyph(props: RegistryIconProps) {- return (- <IconPlaceholder- lucide="Columns3Icon"- tabler="IconLayoutColumns"- hugeicons="LeftToRightListBulletIcon"- phosphor="ColumnsIcon"- remixicon="RiLayoutColumnLine"- {...props}- />- )-}--function ParagraphGlyph(props: RegistryIconProps) {- return (- <IconPlaceholder- lucide="Pilcrow"- tabler="IconPilcrow"- hugeicons="ParagraphIcon"- phosphor="ParagraphIcon"- remixicon="RiParagraph"- {...props}- />- )-}--function Table01Glyph(props: RegistryIconProps) {- return (- <IconPlaceholder- lucide="Table"- tabler="IconTable"- hugeicons="Table01Icon"- phosphor="TableIcon"- remixicon="RiTableLine"- {...props}- />- )-}--function TextCenterlineCenterTopGlyph(props: RegistryIconProps) {- return (- <IconPlaceholder- lucide="PanelTop"- tabler="IconLayoutNavbar"- hugeicons="TextCenterlineCenterTopIcon"- phosphor="AlignTopSimpleIcon"- remixicon="RiLayoutTopLine"- {...props}- />- )-}--function TextNumberSignGlyph(props: RegistryIconProps) {- return (- <IconPlaceholder- lucide="Hash"- tabler="IconHash"- hugeicons="TextNumberSignIcon"- phosphor="HashIcon"- remixicon="RiHashtag"- {...props}- />- )-}+import {+ LayoutBlocksPanel,+ layoutBlockStyles,+ type LayoutBlockType,+} from "@/components/extend/layout-blocks-panel"export type Point = {x: number@@ -128,15 +25,7 @@ export type BoundingBox = {bottom: number}-export type OcrBlockType =- | "heading"- | "paragraph"- | "list"- | "table"- | "figure"- | "header"- | "footer"- | "page_number"+export type OcrBlockType = LayoutBlockTypeexport type ParsedOcrBlock = {id: string@@ -182,12 +71,6 @@ export type HighlightArea = {}export const PDF_URL = "/samples/attention.pdf"-const OCR_BLOCK_ROW_MIN_ESTIMATE = 92-const OCR_BLOCK_ROW_VERTICAL_CHROME = 62-const OCR_BLOCK_LINE_HEIGHT = 20-const OCR_BLOCK_ESTIMATED_CHARS_PER_LINE = 42-const OCR_BLOCK_ROW_GAP = 8-const OCR_BLOCK_LIST_PADDING = 12const OCR_MARKDOWN_SCHEMA = {...defaultSchema,attributes: {@@ -209,30 +92,6 @@ const OCR_MARKDOWN_REMARK_PLUGINS: NonNullable<> = [remarkGfm]const OCR_MARKDOWN_FIGURE_CAPTION_PATTERN = /<\/?caption>/gi-function getEstimatedOcrBlockRowHeight(block: OcrBlock) {- const plainText = block.text- .replace(OCR_MARKDOWN_FIGURE_CAPTION_PATTERN, "")- .replace(/<[^>]*>/g, "")- .replace(/\s+/g, " ")- .trim()- const explicitLineCount = block.text.split(/\n+/).filter(Boolean).length- const wrappedLineCount = Math.max(- explicitLineCount,- Math.ceil(plainText.length / OCR_BLOCK_ESTIMATED_CHARS_PER_LINE)- )- const contentHeight = Math.max(1, wrappedLineCount) * OCR_BLOCK_LINE_HEIGHT- const typeExtraHeight =- block.type === "figure" ? 44 : block.type === "table" ? 28 : 0-- return Math.max(- OCR_BLOCK_ROW_MIN_ESTIMATE,- OCR_BLOCK_ROW_VERTICAL_CHROME +- contentHeight +- typeExtraHeight +- OCR_BLOCK_ROW_GAP- )-}-export const ATTENTION_OCR_OUTPUT = {chunks: [{@@ -8038,87 +7897,6 @@ export const ATTENTION_OCR_OUTPUT = {],} satisfies ParsedOcrOutput-const BLOCK_STYLES: Record<- OcrBlockType,- {- label: string- icon: React.ComponentType<RegistryIconProps>- overlay: string- mutedOverlay: string- ring: string- badge: string- }-> = {- heading: {- label: "Heading",- icon: Heading01Glyph,- overlay: "border-violet-500/70 bg-violet-500/10",- mutedOverlay: "border-violet-500/35 bg-violet-500/5",- ring: "border-violet-500/60 bg-violet-500/5 text-violet-600",- badge:- "bg-violet-50 text-violet-600 dark:bg-violet-300/10 dark:text-violet-300",- },- paragraph: {- label: "Paragraph",- icon: ParagraphGlyph,- overlay: "border-blue-500/70 bg-blue-500/10",- mutedOverlay: "border-blue-500/35 bg-blue-500/5",- ring: "border-blue-500/60 bg-blue-500/5 text-blue-600",- badge: "bg-blue-50 text-blue-600 dark:bg-blue-300/10 dark:text-blue-300",- },- list: {- label: "List",- icon: LeftToRightListBulletGlyph,- overlay: "border-emerald-500/70 bg-emerald-500/10",- mutedOverlay: "border-emerald-500/35 bg-emerald-500/5",- ring: "border-emerald-500/60 bg-emerald-500/5 text-emerald-600",- badge:- "bg-emerald-50 text-emerald-600 dark:bg-emerald-300/10 dark:text-emerald-300",- },- table: {- label: "Table",- icon: Table01Glyph,- overlay: "border-amber-500/70 bg-amber-500/10",- mutedOverlay: "border-amber-500/35 bg-amber-500/5",- ring: "border-amber-500/60 bg-amber-500/5 text-amber-700",- badge:- "bg-amber-50 text-amber-600 dark:bg-amber-300/10 dark:text-amber-300",- },- figure: {- label: "Figure",- icon: ImageCompositionGlyph,- overlay: "border-rose-500/70 bg-rose-500/10",- mutedOverlay: "border-rose-500/35 bg-rose-500/5",- ring: "border-rose-500/60 bg-rose-500/5 text-rose-600",- badge: "bg-rose-50 text-rose-600 dark:bg-rose-300/10 dark:text-rose-300",- },- header: {- label: "Header",- icon: TextCenterlineCenterTopGlyph,- overlay: "border-cyan-500/70 bg-cyan-500/10",- mutedOverlay: "border-cyan-500/35 bg-cyan-500/5",- ring: "border-cyan-500/60 bg-cyan-500/5 text-cyan-700",- badge: "bg-cyan-50 text-cyan-600 dark:bg-cyan-300/10 dark:text-cyan-300",- },- footer: {- label: "Footer",- icon: AlignBoxBottomCenterGlyph,- overlay: "border-slate-500/70 bg-slate-500/10",- mutedOverlay: "border-slate-500/35 bg-slate-500/5",- ring: "border-slate-500/60 bg-slate-500/5 text-slate-700",- badge:- "bg-slate-50 text-slate-600 dark:bg-slate-300/10 dark:text-slate-300",- },- page_number: {- label: "Page number",- icon: TextNumberSignGlyph,- overlay: "border-zinc-500/70 bg-zinc-500/10",- mutedOverlay: "border-zinc-500/35 bg-zinc-500/5",- ring: "border-zinc-500/60 bg-zinc-500/5 text-zinc-700",- badge: "bg-zinc-50 text-zinc-600 dark:bg-zinc-300/10 dark:text-zinc-300",- },-}-function getBlockType(block: ParsedOcrBlock): OcrBlockType | undefined {if (block.type === "heading" || block.type === "section_heading") {return "heading"@@ -8292,12 +8070,36 @@ const OcrBlockMarkdown = React.memo(function OcrBlockMarkdown({{...props}/>),+ h2: ({ node: _node, ...props }) => (+ <h2+ className="my-0 text-[15px] leading-5 font-semibold text-foreground"+ {...props}+ />+ ),+ h3: ({ node: _node, ...props }) => (+ <h3+ className="my-0 text-sm leading-5 font-semibold text-foreground"+ {...props}+ />+ ),p: ({ node: _node, ...props }) => (<p className="my-0 text-[13px] leading-5" {...props} />),+ strong: ({ node: _node, ...props }) => (+ <strong className="font-semibold text-foreground" {...props} />+ ),+ em: ({ node: _node, ...props }) => (+ <em className="text-foreground" {...props} />+ ),+ ul: ({ node: _node, ...props }) => (+ <ul className="my-0 list-disc space-y-0.5 pl-4" {...props} />+ ),ol: ({ node: _node, ...props }) => (<ol className="my-0 list-decimal space-y-0.5 pl-4" {...props} />),+ li: ({ node: _node, ...props }) => (+ <li className="pl-0.5 text-[13px] leading-5" {...props} />+ ),table: ({ node: _node, ...props }) => (<div className="overflow-hidden rounded-md border bg-background"><table className="w-full border-collapse text-xs" {...props} />@@ -8322,7 +8124,10 @@ const OcrBlockMarkdown = React.memo(function OcrBlockMarkdown({/>),th: ({ node: _node, ...props }) => (- <th className="border-b bg-muted px-2 py-1 text-left" {...props} />+ <th+ className="border-b bg-muted px-2 py-1 text-left font-medium"+ {...props}+ />),td: ({ node: _node, ...props }) => (<td className="border-t px-2 py-1" {...props} />@@ -8335,54 +8140,9 @@ const OcrBlockMarkdown = React.memo(function OcrBlockMarkdown({)})-const OcrBlockButton = React.memo(function OcrBlockButton({- block,- isActive,- onFocusBlock,-}: {- block: OcrBlock- isActive: boolean- onFocusBlock: (block: OcrBlock) => void-}) {- const style = BLOCK_STYLES[block.type]-- return (- <button- type="button"- onMouseEnter={() => onFocusBlock(block)}- onFocus={() => onFocusBlock(block)}- className={cn(- "w-full rounded-lg border bg-background p-3 text-left hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",- isActive && style.ring- )}- >- <div className="min-w-0">- <div className="flex items-center justify-between gap-2">- <div className="flex min-w-0 items-center gap-2">- <div- className={cn(- "inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium",- style.badge- )}- >- <style.icon className="size-3.5" />- {style.label}- </div>- <div className="truncate text-xs text-muted-foreground">- {Math.round(block.confidence * 100)}%- </div>- </div>- <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">- p. {block.page}- </div>- </div>- <div className="mt-2 text-sm text-foreground/90">- <OcrBlockMarkdown text={block.text} />- </div>- </div>- </button>- )-})+export function renderOcrBlockText(text: string) {+ return <OcrBlockMarkdown text={text} />+}export const OcrBlockOverlay = React.memo(function OcrBlockOverlay({block,@@ -8395,13 +8155,13 @@ export const OcrBlockOverlay = React.memo(function OcrBlockOverlay({pageHeight?: numberpageWidth?: number}) {- const style = BLOCK_STYLES[block.type]+ const style = layoutBlockStyles[block.type]return (<divclassName={cn(- "pointer-events-none absolute z-10 border",- isActive ? style.overlay : style.mutedOverlay+ "pointer-events-none absolute z-10 border transition-[opacity,box-shadow]",+ isActive ? style.overlay : cn("opacity-55", style.mutedOverlay))}style={blockToArea(block,@@ -8413,122 +8173,13 @@ export const OcrBlockOverlay = React.memo(function OcrBlockOverlay({)})-export function OcrBlocksPanel({- activeBlockId,- blocks,- className,- onBlockFocus,-}: {+export function OcrBlocksPanel(props: {activeBlockId?: stringblocks: OcrBlock[]className?: stringonBlockFocus?: (block: OcrBlock) => void}) {- const scrollViewportRef = React.useRef<HTMLDivElement | null>(null)- const [localActiveBlockId, setLocalActiveBlockId] = React.useState(- activeBlockId ?? blocks[0]?.id- )- const firstBlock = blocks[0]- const focusedBlockId = activeBlockId ?? localActiveBlockId- const activeBlock =- blocks.find((block) => block.id === focusedBlockId) ?? firstBlock- const focusedBlockIdRef = React.useRef(focusedBlockId)-- React.useEffect(() => {- focusedBlockIdRef.current = focusedBlockId- }, [focusedBlockId])-- const estimateBlockSize = React.useCallback(- (index: number) => {- const block = blocks[index]- return block- ? getEstimatedOcrBlockRowHeight(block)- : OCR_BLOCK_ROW_MIN_ESTIMATE- },- [blocks]- )- const virtualizer = useVirtualizer({- count: blocks.length,- estimateSize: estimateBlockSize,- getItemKey: (index) => blocks[index]?.id ?? index,- getScrollElement: () => scrollViewportRef.current,- overscan: 6,- })-- const focusBlock = React.useCallback(- (block: OcrBlock) => {- if (block.id === focusedBlockIdRef.current) return-- focusedBlockIdRef.current = block.id- setLocalActiveBlockId(block.id)- onBlockFocus?.(block)- },- [onBlockFocus]- )-- React.useEffect(() => {- if (!firstBlock) return- if (- activeBlockId ||- blocks.some((block) => block.id === localActiveBlockId)- ) {- return- }-- setLocalActiveBlockId(firstBlock.id)- }, [activeBlockId, blocks, firstBlock, localActiveBlockId])-- return (- <aside- className={cn("flex h-[420px] min-h-0 flex-col bg-background", className)}- >- <ScrollArea- className="min-h-0 flex-1"- scrollFade- viewportRef={scrollViewportRef}- >- {blocks.length ? (- <div- className="relative"- style={{- height: virtualizer.getTotalSize() + OCR_BLOCK_LIST_PADDING * 2,- }}- >- {virtualizer.getVirtualItems().map((virtualRow) => {- const block = blocks[virtualRow.index]- if (!block) return null-- return (- <div- key={virtualRow.key}- ref={virtualizer.measureElement}- data-index={virtualRow.index}- className="absolute top-0 right-3 left-3 pb-2 [contain:layout_paint]"- style={{- transform: `translateY(${- virtualRow.start + OCR_BLOCK_LIST_PADDING- }px)`,- }}- >- <OcrBlockButton- block={block}- isActive={block.id === activeBlock?.id}- onFocusBlock={focusBlock}- />- </div>- )- })}- </div>- ) : (- <div className="p-3">- <div className="rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground">- No layout blocks found.- </div>- </div>- )}- </ScrollArea>- </aside>- )+ return <LayoutBlocksPanel {...props} renderText={renderOcrBlockText} />}export function OcrBlocks() {diff --git a/apps/v4/components/file-system-docs.tsx b/apps/v4/components/file-system-docs.tsxindex 5960e53..97f6371 100644--- a/apps/v4/components/file-system-docs.tsx+++ b/apps/v4/components/file-system-docs.tsx@@ -311,6 +311,13 @@ function PdfThumbnailUrlGenerator({return null}+const thumbnailGeneratorsByKind = {+ docx: DocxThumbnailUrlGenerator,+ pdf: PdfThumbnailUrlGenerator,+ pptx: PptxThumbnailUrlGenerator,+ xlsx: XlsxThumbnailUrlGenerator,+}+type DemoThumbnails = {pageCount: numberurls: string[]@@ -323,7 +330,8 @@ const demoThumbnailCache = new Map<string, DemoThumbnails>()export function useFileSystemDemoItems({staticThumbnails = false,-}: { staticThumbnails?: boolean } = {}) {+ thumbnailPath,+}: { staticThumbnails?: boolean; thumbnailPath?: string | null } = {}) {const [thumbnails, setThumbnails] = React.useState<Record<string, DemoThumbnails>>(() => Object.fromEntries(demoThumbnailCache))@@ -353,6 +361,9 @@ export function useFileSystemDemoItems({const items = React.useMemo<FileSystemItem[]>(() => [...DEMO_SOURCES.map<FileSystemItem>((source) => {+ const generated = staticThumbnails ? undefined : thumbnails[source.path]+ const cover =+ source.thumbnail === "url" ? source.url : source.staticThumbnailUrlreturn {contentType: source.contentType,createdAt: source.createdAt,@@ -360,15 +371,8 @@ export function useFileSystemDemoItems({kind: "file",path: source.path,previewAspectRatio: source.previewAspectRatio,- previewImageUrls:- source.thumbnail === "url"- ? [source.url]- : staticThumbnails && source.staticThumbnailUrl- ? [source.staticThumbnailUrl]- : (thumbnails[source.path]?.urls ?? null),- previewPageCount: staticThumbnails- ? undefined- : thumbnails[source.path]?.pageCount,+ previewImageUrls: generated?.urls ?? (cover ? [cover] : null),+ previewPageCount: generated?.pageCount,size: source.size,updatedAt: source.updatedAt,url: source.url,@@ -426,56 +430,27 @@ export function useFileSystemDemoItems({[])- const thumbnailGenerators = !staticThumbnails && (- <>- {DEMO_SOURCES.filter(- (source) => source.thumbnail === "pdf" && !thumbnails[source.path]- ).map((source) => (- <PdfThumbnailUrlGenerator- key={source.path}- url={source.url}- onUrls={(dataUrls, pageCount) =>- setPathThumbnails(source.path, dataUrls, pageCount)- }- />- ))}- {DEMO_SOURCES.filter(- (source) => source.thumbnail === "docx" && !thumbnails[source.path]- ).map((source) => (- <DocxThumbnailUrlGenerator+ const thumbnailGenerators =+ !staticThumbnails &&+ DEMO_SOURCES.map((source) => {+ if (+ source.thumbnail === "url" ||+ thumbnails[source.path] ||+ (thumbnailPath !== undefined && source.path !== thumbnailPath)+ )+ return null+ const Generator = thumbnailGeneratorsByKind[source.thumbnail]+ return (+ <Generatorkey={source.path}- fileName={source.path.split("/").pop() ?? source.path}url={source.url}- onUrls={(dataUrls, pageCount) =>- setPathThumbnails(source.path, dataUrls, pageCount)- }- />- ))}- {DEMO_SOURCES.filter(- (source) => source.thumbnail === "xlsx" && !thumbnails[source.path]- ).map((source) => (- <XlsxThumbnailUrlGenerator- key={source.path}fileName={source.path.split("/").pop() ?? source.path}- url={source.url}- onUrls={(dataUrls, pageCount) =>- setPathThumbnails(source.path, dataUrls, pageCount)- }- />- ))}- {DEMO_SOURCES.filter(- (source) => source.thumbnail === "pptx" && !thumbnails[source.path]- ).map((source) => (- <PptxThumbnailUrlGenerator- key={source.path}- url={source.url}- onUrls={(dataUrls, pageCount) =>- setPathThumbnails(source.path, dataUrls, pageCount)+ onUrls={(urls, pageCount) =>+ setPathThumbnails(source.path, urls, pageCount)}/>- ))}- </>- )+ )+ })return { items, loadPreviewImageUrl, thumbnailGenerators }}@@ -512,8 +487,9 @@ export function FileSystemFinderBlock({heightClassName?: stringstaticThumbnails?: boolean}) {+ const [thumbnailPath, setThumbnailPath] = React.useState<string | null>(null)const { items, loadPreviewImageUrl, thumbnailGenerators } =- useFileSystemDemoItems({ staticThumbnails })+ useFileSystemDemoItems({ staticThumbnails, thumbnailPath })return (<div className="flex h-full min-h-0 bg-background">@@ -522,6 +498,9 @@ export function FileSystemFinderBlock({title="Documents"className={cn("min-h-0 flex-1 rounded-none border-0", heightClassName)}defaultView={defaultView}+ onSelectionChange={(item) =>+ setThumbnailPath(item?.kind === "file" ? item.path : null)+ }loadPreviewImageUrl={loadPreviewImageUrl}/>{thumbnailGenerators}diff --git a/apps/v4/components/highlighted-code-block.tsx b/apps/v4/components/highlighted-code-block.tsxindex 83c1359..5f3c374 100644--- a/apps/v4/components/highlighted-code-block.tsx+++ b/apps/v4/components/highlighted-code-block.tsx@@ -71,6 +71,7 @@ const CODE_HIGHLIGHTER_OPTIONS = {} satisfies WorkerInitializationRenderOptionsconst CODE_WORKER_POOL_OPTIONS = {+ poolSize: 2,workerFactory: () =>new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), {type: "module",diff --git a/apps/v4/components/layout-blocks-docs.tsx b/apps/v4/components/layout-blocks-docs.tsxindex a14023f..3db0ae7 100644--- a/apps/v4/components/layout-blocks-docs.tsx+++ b/apps/v4/components/layout-blocks-docs.tsx@@ -1,8660 +1,78 @@"use client"-import * as React from "react"-import {- AlignBoxBottomCenterIcon,- Heading01Icon,- ImageCompositionIcon,- LeftToRightListBulletIcon,- ParagraphIcon,- Table01Icon,- TextCenterlineCenterTopIcon,- TextNumberSignIcon,-} from "@hugeicons/core-free-icons"-import { HugeiconsIcon } from "@hugeicons/react"-import { useVirtualizer } from "@tanstack/react-virtual"-import ReactMarkdown from "react-markdown"-import rehypeRaw from "rehype-raw"-import rehypeSanitize, { defaultSchema } from "rehype-sanitize"-import remarkGfm from "remark-gfm"+import dynamic from "next/dynamic"-import { cn } from "@/lib/utils"import { withUiBasePath } from "@/lib/zone-path"-import { Button } from "@/components/ui/button"-import { ScrollArea } from "@/components/ui/scroll-area"import {- DocsSourceCodeBlock,- DocsViewCodeBlock,-} from "@/components/docs-code-block"-import { PdfBlockResizableShell } from "@/components/extend/pdf-block-resizable-shell"-import { PDFViewer, type PDFViewerHandle } from "@/components/extend/pdf-viewer"--type Point = {- x: number- y: number-}--type BoundingBox = {- left: number- top: number- right: number- bottom: number-}--type OcrBlockType =- | "heading"- | "paragraph"- | "list"- | "table"- | "figure"- | "header"- | "footer"- | "page_number"--type ParsedOcrBlock = {- id: string- type: string- content: string- metadata: {- page: {- number: number- width: number- height: number- }- layoutClass?: string- minOcrConfidence?: number- avgOcrConfidence?: number- }- polygon?: Point[]- boundingBox?: BoundingBox-}--type ParsedOcrOutput = {- chunks: {- blocks: ParsedOcrBlock[]- }[]-}--type OcrBlock = {- id: string- type: OcrBlockType- text: string- page: number- pageWidth: number- pageHeight: number- confidence: number- polygon?: Point[]- boundingBox?: BoundingBox-}--type HighlightArea = {- left: number- top: number- width: number- height: number-}--const PDF_URL = withUiBasePath("/samples/attention.pdf")-const DEFAULT_ZOOM = 1-const ROOT_OCR_PREVIEW_PAGE = 1-const OCR_BLOCK_ROW_MIN_ESTIMATE = 92-const OCR_BLOCK_ROW_VERTICAL_CHROME = 62-const OCR_BLOCK_LINE_HEIGHT = 20-const OCR_BLOCK_ESTIMATED_CHARS_PER_LINE = 42-const OCR_BLOCK_ROW_GAP = 8-const OCR_BLOCK_LIST_PADDING = 12-const OCR_MARKDOWN_SCHEMA = {- ...defaultSchema,- attributes: {- ...defaultSchema.attributes,- figure: [...(defaultSchema.attributes?.figure ?? []), "type"],- },- tagNames: [- ...(defaultSchema.tagNames ?? []),- "caption",- "figcaption",- "figure",- ],-}-const OCR_MARKDOWN_REHYPE_PLUGINS: NonNullable<- React.ComponentProps<typeof ReactMarkdown>["rehypePlugins"]-> = [rehypeRaw, [rehypeSanitize, OCR_MARKDOWN_SCHEMA]]-const OCR_MARKDOWN_REMARK_PLUGINS: NonNullable<- React.ComponentProps<typeof ReactMarkdown>["remarkPlugins"]-> = [remarkGfm]-const OCR_MARKDOWN_FIGURE_CAPTION_PATTERN = /<\/?caption>/gi--function getEstimatedOcrBlockRowHeight(block: OcrBlock) {- const plainText = block.text- .replace(OCR_MARKDOWN_FIGURE_CAPTION_PATTERN, "")- .replace(/<[^>]*>/g, "")- .replace(/\s+/g, " ")- .trim()- const explicitLineCount = block.text.split(/\n+/).filter(Boolean).length- const wrappedLineCount = Math.max(- explicitLineCount,- Math.ceil(plainText.length / OCR_BLOCK_ESTIMATED_CHARS_PER_LINE)- )- const contentHeight = Math.max(1, wrappedLineCount) * OCR_BLOCK_LINE_HEIGHT- const typeExtraHeight =- block.type === "figure" ? 44 : block.type === "table" ? 28 : 0-- return Math.max(- OCR_BLOCK_ROW_MIN_ESTIMATE,- OCR_BLOCK_ROW_VERTICAL_CHROME +- contentHeight +- typeExtraHeight +- OCR_BLOCK_ROW_GAP- )-}--const BLOCK_STYLES: Record<- OcrBlockType,- {- label: string- icon: typeof Heading01Icon- overlay: string- mutedOverlay: string- ring: string- badge: string- }-> = {- heading: {- label: "Heading",- icon: Heading01Icon,- overlay:- "border-violet-500/70 bg-violet-500/10 shadow-[0_4px_16px_rgb(139_92_246_/_12%)]",- mutedOverlay: "border-violet-500/35 bg-violet-500/5",- ring: "border-violet-500/60 bg-violet-500/5",- badge:- "bg-violet-50 text-violet-600 dark:bg-violet-300/10 dark:text-violet-300",- },- paragraph: {- label: "Paragraph",- icon: ParagraphIcon,- overlay:- "border-blue-500/70 bg-blue-500/10 shadow-[0_4px_16px_rgb(59_130_246_/_12%)]",- mutedOverlay: "border-blue-500/35 bg-blue-500/5",- ring: "border-blue-500/60 bg-blue-500/5",- badge: "bg-blue-50 text-blue-600 dark:bg-blue-300/10 dark:text-blue-300",- },- list: {- label: "List",- icon: LeftToRightListBulletIcon,- overlay:- "border-emerald-500/70 bg-emerald-500/10 shadow-[0_4px_16px_rgb(16_185_129_/_12%)]",- mutedOverlay: "border-emerald-500/35 bg-emerald-500/5",- ring: "border-emerald-500/60 bg-emerald-500/5",- badge:- "bg-emerald-50 text-emerald-600 dark:bg-emerald-300/10 dark:text-emerald-300",- },- table: {- label: "Table",- icon: Table01Icon,- overlay:- "border-amber-500/70 bg-amber-500/10 shadow-[0_4px_16px_rgb(245_158_11_/_12%)]",- mutedOverlay: "border-amber-500/35 bg-amber-500/5",- ring: "border-amber-500/60 bg-amber-500/5",- badge:- "bg-amber-50 text-amber-600 dark:bg-amber-300/10 dark:text-amber-300",- },- figure: {- label: "Figure",- icon: ImageCompositionIcon,- overlay:- "border-rose-500/70 bg-rose-500/10 shadow-[0_4px_16px_rgb(244_63_94_/_12%)]",- mutedOverlay: "border-rose-500/35 bg-rose-500/5",- ring: "border-rose-500/60 bg-rose-500/5",- badge: "bg-rose-50 text-rose-600 dark:bg-rose-300/10 dark:text-rose-300",- },- header: {- label: "Header",- icon: TextCenterlineCenterTopIcon,- overlay:- "border-cyan-500/70 bg-cyan-500/10 shadow-[0_4px_16px_rgb(6_182_212_/_12%)]",- mutedOverlay: "border-cyan-500/35 bg-cyan-500/5",- ring: "border-cyan-500/60 bg-cyan-500/5",- badge: "bg-cyan-50 text-cyan-600 dark:bg-cyan-300/10 dark:text-cyan-300",- },- footer: {- label: "Footer",- icon: AlignBoxBottomCenterIcon,- overlay:- "border-slate-500/70 bg-slate-500/10 shadow-[0_4px_16px_rgb(100_116_139_/_12%)]",- mutedOverlay: "border-slate-500/35 bg-slate-500/5",- ring: "border-slate-500/60 bg-slate-500/5",- badge:- "bg-slate-50 text-slate-600 dark:bg-slate-300/10 dark:text-slate-300",- },- page_number: {- label: "Page number",- icon: TextNumberSignIcon,- overlay:- "border-zinc-500/70 bg-zinc-500/10 shadow-[0_4px_16px_rgb(113_113_122_/_12%)]",- mutedOverlay: "border-zinc-500/35 bg-zinc-500/5",- ring: "border-zinc-500/60 bg-zinc-500/5",- badge: "bg-zinc-50 text-zinc-600 dark:bg-zinc-300/10 dark:text-zinc-300",- },-}--const ATTENTION_OCR_OUTPUT = {- chunks: [- {- blocks: [- {- id: "block_1_IKDP4i",- type: "header",- content: "arXiv:1706.03762v7 [cs.CL] 2 Aug 2023",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Header",- minOcrConfidence: 0.959,- avgOcrConfidence: 0.98,- },- polygon: [- {- x: 36.16179897837395,- y: 447.38040863840206,- },- {- x: 75.85163708150822,- y: 447.38040863840206,- },- {- x: 75.85163708150822,- y: 1155.1796566956025,- },- {- x: 36.16179897837395,- y: 1155.1796566956025,- },- ],- boundingBox: {- left: 36.16179897837395,- top: 447.38040863840206,- right: 75.85163708150822,- bottom: 1155.1796566956025,- },- },- {- id: "block_1_rtNdsr",- type: "header",- content:- "Provided proper attribution is provided, Google hereby grants permission to reproduce the tables and figures in this paper solely for use in journalistic or scholarly works.",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Header",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 258.50183528705236,- y: 151.7837261257315,- },- {- x: 1016.8830982960054,- y: 151.7837261257315,- },- {- x: 1016.8830982960054,- y: 233.84929126366637,- },- {- x: 258.50183528705236,- y: 233.84929126366637,- },- ],- boundingBox: {- left: 258.50183528705236,- top: 151.7837261257315,- right: 1016.8830982960054,- bottom: 233.84929126366637,- },- },- {- id: "block_1_eo9AoV",- type: "heading",- content: "# Attention Is All You Need",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Heading",- minOcrConfidence: 0.99,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 440.0215455215343,- y: 312.01490975860366,- },- {- x: 831.4373211268961,- y: 312.01490975860366,- },- {- x: 831.4373211268961,- y: 339.0022611402928,- },- {- x: 440.0215455215343,- y: 339.0022611402928,- },- ],- boundingBox: {- left: 440.0215455215343,- top: 312.01490975860366,- right: 831.4373211268961,- bottom: 339.0022611402928,- },- },- {- id: "block_1_Kdt5Cu",- type: "text",- content: "Ashish Vaswani* Google Brain [email protected]",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.977,- avgOcrConfidence: 0.992,- },- polygon: [- {- x: 242.9606625633518,- y: 490.4495616712068,- },- {- x: 449.64758323056856,- y: 490.4495616712068,- },- {- x: 449.64758323056856,- y: 555.9028907431696,- },- {- x: 242.9606625633518,- y: 555.9028907431696,- },- ],- boundingBox: {- left: 242.9606625633518,- top: 490.4495616712068,- right: 449.64758323056856,- bottom: 555.9028907431696,- },- },- {- id: "block_1_6Xv6uR",- type: "text",- content: "Llion Jones* Google Research [email protected]",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.927,- avgOcrConfidence: 0.982,- },- polygon: [- {- x: 264.3723327748097,- y: 594.5307239733245,- },- {- x: 438.3605845653227,- y: 594.5307239733245,- },- {- x: 438.3605845653227,- y: 660.7685646688132,- },- {- x: 264.3723327748097,- y: 660.7685646688132,- },- ],- boundingBox: {- left: 264.3723327748097,- top: 594.5307239733245,- right: 438.3605845653227,- bottom: 660.7685646688132,- },- },- {- id: "block_1_Lx35WU",- type: "text",- content: "Noam Shazeer* Google Brain [email protected]",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.983,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 479.08373644752226,- y: 490.1169480632122,- },- {- x: 643.7573955006842,- y: 490.1169480632122,- },- {- x: 643.7573955006842,- y: 556.2343205043247,- },- {- x: 479.08373644752226,- y: 556.2343205043247,- },- ],- boundingBox: {- left: 479.08373644752226,- top: 490.1169480632122,- right: 643.7573955006842,- bottom: 556.2343205043247,- },- },- {- id: "block_1_VxOJIL",- type: "text",- content:- "Aidan N. Gomez* * University of Toronto [email protected]",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.095,- avgOcrConfidence: 0.875,- },- polygon: [- {- x: 489.9820146769503,- y: 593.5908916444707,- },- {- x: 708.1676900821881,- y: 593.5908916444707,- },- {- x: 708.1676900821881,- y: 657.7173651788468,- },- {- x: 489.9820146769503,- y: 657.7173651788468,- },- ],- boundingBox: {- left: 489.9820146769503,- top: 593.5908916444707,- right: 708.1676900821881,- bottom: 657.7173651788468,- },- },- {- id: "block_1_m1Gb17",- type: "text",- content: "Niki Parmar* Google Research [email protected]",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.99,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 673.3537325893875,- y: 490.2837284059453,- },- {- x: 848.6601168221802,- y: 490.2837284059453,- },- {- x: 848.6601168221802,- y: 556.287735673718,- },- {- x: 673.3537325893875,- y: 556.287735673718,- },- ],- boundingBox: {- left: 673.3537325893875,- top: 490.2837284059453,- right: 848.6601168221802,- bottom: 556.287735673718,- },- },- {- id: "block_1_otnY8T",- type: "text",- content: "\u0141ukasz Kaiser* Google Brain [email protected]",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.984,- avgOcrConfidence: 0.992,- },- polygon: [- {- x: 759.3324257509552,- y: 594.2661578816579,- },- {- x: 1011.1333304078039,- y: 594.2661578816579,- },- {- x: 1011.1333304078039,- y: 660.9298993160851,- },- {- x: 759.3324257509552,- y: 660.9298993160851,- },- ],- boundingBox: {- left: 759.3324257509552,- top: 594.2661578816579,- right: 1011.1333304078039,- bottom: 660.9298993160851,- },- },- {- id: "block_1_ICaos6",- type: "text",- content: "Illia Polosukhin* * [email protected]",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.107,- avgOcrConfidence: 0.766,- },- polygon: [- {- x: 495.9563429338219,- y: 697.325802423004,- },- {- x: 778.5449758933407,- y: 697.325802423004,- },- {- x: 778.5449758933407,- y: 742.1158899292909,- },- {- x: 495.9563429338219,- y: 742.1158899292909,- },- ],- boundingBox: {- left: 495.9563429338219,- top: 697.325802423004,- right: 778.5449758933407,- bottom: 742.1158899292909,- },- },- {- id: "block_1_zNN0g5",- type: "section_heading",- content: "### Abstract",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.995,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 590.8429918498018,- y: 804.3203170891095,- },- {- x: 683.8031267597728,- y: 804.3203170891095,- },- {- x: 683.8031267597728,- y: 823.7656170264223,- },- {- x: 590.8429918498018,- y: 823.7656170264223,- },- ],- boundingBox: {- left: 590.8429918498018,- top: 804.3203170891095,- right: 683.8031267597728,- bottom: 823.7656170264223,- },- },- {- id: "block_1_Pzc7ia",- type: "text",- content:- "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014 English- to-German translation task, improving over the existing best results, including ensembles, by over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training costs of the best models from the literature. We show that the Transformer generalizes well to other tasks by applying it successfully to English constituency parsing both with large and limited training data.",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.987,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 298.2268201173657,- y: 861.5167879950731,- },- {- x: 978.0244980415288,- y: 861.5167879950731,- },- {- x: 978.0244980415288,- y: 1201.6481075430274,- },- {- x: 298.2268201173657,- y: 1201.6481075430274,- },- ],- boundingBox: {- left: 298.2268201173657,- top: 861.5167879950731,- right: 978.0244980415288,- bottom: 1201.6481075430274,- },- },- {- id: "block_1_bHnLKj",- type: "text",- content:- "*Equal contribution. Listing order is random. Jakob proposed replacing RNNs with self-attention and started the effort to evaluate this idea. Ashish, with Illia, designed and implemented the first Transformer models and has been crucially involved in every aspect of this work. Noam proposed scaled dot-product attention, multi-head attention and the parameter-free position representation and became the other person involved in nearly every detail. Niki designed, implemented, tuned and evaluated countless model variants in our original codebase and tensor2tensor. Llion also experimented with novel model variants, was responsible for our initial codebase, and efficient inference and visualizations. Lukasz and Aidan spent countless long days designing various parts of and implementing tensor2tensor, replacing our earlier codebase, greatly improving results and massively accelerating our research.",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.951,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 222.8755505415645,- y: 1247.2573697082978,- },- {- x: 1049.6971241749116,- y: 1247.2573697082978,- },- {- x: 1049.6971241749116,- y: 1429.7100451476592,- },- {- x: 222.8755505415645,- y: 1429.7100451476592,- },- ],- boundingBox: {- left: 222.8755505415645,- top: 1247.2573697082978,- right: 1049.6971241749116,- bottom: 1429.7100451476592,- },- },- {- id: "block_1_J3Olku",- type: "text",- content: "+ Work performed while at Google Brain.",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.11,- avgOcrConfidence: 0.869,- },- polygon: [- {- x: 250.1677060649343,- y: 1434.3817888991277,- },- {- x: 555.1793119333087,- y: 1434.3817888991277,- },- {- x: 555.1793119333087,- y: 1456.532320926064,- },- {- x: 250.1677060649343,- y: 1456.532320926064,- },- ],- boundingBox: {- left: 250.1677060649343,- top: 1434.3817888991277,- right: 555.1793119333087,- bottom: 1456.532320926064,- },- },- {- id: "block_1_aQsakB",- type: "text",- content: "#Work performed while at Google Research.",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.652,- avgOcrConfidence: 0.94,- },- polygon: [- {- x: 249.36288151427775,- y: 1458.4100914288283,- },- {- x: 582.4047478446125,- y: 1458.4100914288283,- },- {- x: 582.4047478446125,- y: 1479.773507369192,- },- {- x: 249.36288151427775,- y: 1479.773507369192,- },- ],- boundingBox: {- left: 249.36288151427775,- top: 1458.4100914288283,- right: 582.4047478446125,- bottom: 1479.773507369192,- },- },- {- id: "block_1_iKp4Ae",- type: "footer",- content:- "31st Conference on Neural Information Processing Systems (NIPS 2017), Long Beach, CA, USA.",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Footer",- minOcrConfidence: 0.99,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 224.27405893367575,- y: 1527.1945287374626,- },- {- x: 958.2568426201814,- y: 1527.1945287374626,- },- {- x: 958.2568426201814,- y: 1546.3855383736748,- },- {- x: 224.27405893367575,- y: 1546.3855383736748,- },- ],- boundingBox: {- left: 224.27405893367575,- top: 1527.1945287374626,- right: 958.2568426201814,- bottom: 1546.3855383736748,- },- },- {- id: "block_1_zPHQaR",- type: "text",- content: "Jakob Uszkoreit* Google Research [email protected]",- metadata: {- page: {- number: 1,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 879.2488933479699,- y: 489.58686880240765,- },- {- x: 1035.003756780694,- y: 489.58686880240765,- },- {- x: 1035.003756780694,- y: 555.848623204052,- },- {- x: 879.2488933479699,- y: 555.848623204052,- },- ],- boundingBox: {- left: 879.2488933479699,- top: 489.58686880240765,- right: 1035.003756780694,- bottom: 555.848623204052,- },- },- ],- },- {- blocks: [- {- id: "block_2_UD1C1k",- type: "heading",- content: "# 1 Introduction",- metadata: {- page: {- number: 2,- width: 1275,- height: 1651,- },- layoutClass: "Heading",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.992,- },- polygon: [- {- x: 225.86025321570625,- y: 152.1792611932396,- },- {- x: 396.86960095036636,- y: 152.1792611932396,- },- {- x: 396.86960095036636,- y: 171.96800693712737,- },- {- x: 225.86025321570625,- y: 171.96800693712737,- },- ],- boundingBox: {- left: 225.86025321570625,- top: 152.1792611932396,- right: 396.86960095036636,- bottom: 171.96800693712737,- },- },- {- id: "block_2_C25o9D",- type: "text",- content:- "Recurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks in particular, have been firmly established as state of the art approaches in sequence modeling and transduction problems such as language modeling and machine translation [35, 2, 5]. Numerous efforts have since continued to push the boundaries of recurrent language models and encoder-decoder architectures [38, 24, 15].",- metadata: {- page: {- number: 2,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.908,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 223.64054213475134,- y: 206.4059457563816,- },- {- x: 1050.9159227357293,- y: 206.4059457563816,- },- {- x: 1050.9159227357293,- y: 316.89823061720773,- },- {- x: 223.64054213475134,- y: 316.89823061720773,- },- ],- boundingBox: {- left: 223.64054213475134,- top: 206.4059457563816,- right: 1050.9159227357293,- bottom: 316.89823061720773,- },- },- {- id: "block_2_Cw1VyU",- type: "text",- content:- "Recurrent models typically factor computation along the symbol positions of the input and output sequences. Aligning the positions to steps in computation time, they generate a sequence of hidden states ht, as a function of the previous hidden state ht-1 and the input for position t. This inherently sequential nature precludes parallelization within training examples, which becomes critical at longer sequence lengths, as memory constraints limit batching across examples. Recent work has achieved significant improvements in computational efficiency through factorization tricks [21] and conditional computation [32], while also improving model performance in case of the latter. The fundamental constraint of sequential computation, however, remains.",- metadata: {- page: {- number: 2,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.9,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 223.69928568819142,- y: 331.227654822787,- },- {- x: 1049.6158961832089,- y: 331.227654822787,- },- {- x: 1049.6158961832089,- y: 511.80734250061494,- },- {- x: 223.69928568819142,- y: 511.80734250061494,- },- ],- boundingBox: {- left: 223.69928568819142,- top: 331.227654822787,- right: 1049.6158961832089,- bottom: 511.80734250061494,- },- },- {- id: "block_2_FR7zlH",- type: "text",- content:- "Attention mechanisms have become an integral part of compelling sequence modeling and transduc- tion models in various tasks, allowing modeling of dependencies without regard to their distance in the input or output sequences [2, 19]. In all but a few cases [27], however, such attention mechanisms are used in conjunction with a recurrent network.",- metadata: {- page: {- number: 2,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.959,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 223.38852708357095,- y: 525.5238181666324,- },- {- x: 1052.1732525233804,- y: 525.5238181666324,- },- {- x: 1052.1732525233804,- y: 613.7107948647406,- },- {- x: 223.38852708357095,- y: 613.7107948647406,- },- ],- boundingBox: {- left: 223.38852708357095,- top: 525.5238181666324,- right: 1052.1732525233804,- bottom: 613.7107948647406,- },- },- {- id: "block_2_ZyhlFh",- type: "text",- content:- "In this work we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output. The Transformer allows for significantly more parallelization and can reach a new state of the art in translation quality after being trained for as little as twelve hours on eight P100 GPUs.",- metadata: {- page: {- number: 2,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.991,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 223.20226126343667,- y: 627.2328828797304,- },- {- x: 1052.7354108156078,- y: 627.2328828797304,- },- {- x: 1052.7354108156078,- y: 716.0174654623619,- },- {- x: 223.20226126343667,- y: 716.0174654623619,- },- ],- boundingBox: {- left: 223.20226126343667,- top: 627.2328828797304,- right: 1052.7354108156078,- bottom: 716.0174654623619,- },- },- {- id: "block_2_MZBXjP",- type: "section_heading",- content: "### 2 Background",- metadata: {- page: {- number: 2,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.994,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 224.22355178498873,- y: 757.4257287333783,- },- {- x: 392.45446198178036,- y: 757.4257287333783,- },- {- x: 392.45446198178036,- y: 781.2853567654029,- },- {- x: 224.22355178498873,- y: 781.2853567654029,- },- ],- boundingBox: {- left: 224.22355178498873,- top: 757.4257287333783,- right: 392.45446198178036,- bottom: 781.2853567654029,- },- },- {- id: "block_2_JeOnOk",- type: "text",- content:- "The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU [16], ByteNet [18] and ConvS2S [9], all of which use convolutional neural networks as basic building block, computing hidden representations in parallel for all input and output positions. In these models, the number of operations required to relate signals from two arbitrary input or output positions grows in the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes it more difficult to learn dependencies between distant positions [12]. In the Transformer this is reduced to a constant number of operations, albeit at the cost of reduced effective resolution due to averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as described in section 3.2.",- metadata: {- page: {- number: 2,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.893,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 223.30221050847186,- y: 810.9956032315591,- },- {- x: 1051.187440078624,- y: 810.9956032315591,- },- {- x: 1051.187440078624,- y: 1010.7095232511822,- },- {- x: 223.30221050847186,- y: 1010.7095232511822,- },- ],- boundingBox: {- left: 223.30221050847186,- top: 810.9956032315591,- right: 1051.187440078624,- bottom: 1010.7095232511822,- },- },- {- id: "block_2_tEzlrD",- type: "text",- content:- "Self-attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence. Self-attention has been used successfully in a variety of tasks including reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations [4, 27, 28, 22].",- metadata: {- page: {- number: 2,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.984,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 224.00045882176306,- y: 1028.0413251030714,- },- {- x: 1051.4467448213675,- y: 1028.0413251030714,- },- {- x: 1051.4467448213675,- y: 1116.9915041815966,- },- {- x: 224.00045882176306,- y: 1116.9915041815966,- },- ],- boundingBox: {- left: 224.00045882176306,- top: 1028.0413251030714,- right: 1051.4467448213675,- bottom: 1116.9915041815966,- },- },- {- id: "block_2_AFJ4ch",- type: "text",- content:- "End-to-end memory networks are based on a recurrent attention mechanism instead of sequence- aligned recurrence and have been shown to perform well on simple-language question answering and language modeling tasks [34].",- metadata: {- page: {- number: 2,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.963,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 224.05524984763485,- y: 1129.9793457949072,- },- {- x: 1052.8165441359918,- y: 1129.9793457949072,- },- {- x: 1052.8165441359918,- y: 1196.1117767678168,- },- {- x: 224.05524984763485,- y: 1196.1117767678168,- },- ],- boundingBox: {- left: 224.05524984763485,- top: 1129.9793457949072,- right: 1052.8165441359918,- bottom: 1196.1117767678168,- },- },- {- id: "block_2_CBbJP3",- type: "text",- content:- "To the best of our knowledge, however, the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence- aligned RNNs or convolution. In the following sections, we will describe the Transformer, motivate self-attention and discuss its advantages over models such as [17, 18] and [9].",- metadata: {- page: {- number: 2,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.898,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 222.86987026242443,- y: 1210.5673043387276,- },- {- x: 1052.2374396776631,- y: 1210.5673043387276,- },- {- x: 1052.2374396776631,- y: 1298.352294004053,- },- {- x: 222.86987026242443,- y: 1298.352294004053,- },- ],- boundingBox: {- left: 222.86987026242443,- top: 1210.5673043387276,- right: 1052.2374396776631,- bottom: 1298.352294004053,- },- },- {- id: "block_2_RlRHBW",- type: "section_heading",- content: "### 3 Model Architecture",- metadata: {- page: {- number: 2,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.993,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 224.20267675914906,- y: 1339.2827093368187,- },- {- x: 470.2105250671832,- y: 1339.2827093368187,- },- {- x: 470.2105250671832,- y: 1359.0320211424864,- },- {- x: 224.20267675914906,- y: 1359.0320211424864,- },- ],- boundingBox: {- left: 224.20267675914906,- top: 1339.2827093368187,- right: 470.2105250671832,- bottom: 1359.0320211424864,- },- },- {- id: "block_2_OhVaOm",- type: "text",- content:- "Most competitive neural sequence transduction models have an encoder-decoder structure [5, 2, 35]. Here, the encoder maps an input sequence of symbol representations (x1, ... , In) to a sequence of continuous representations z = (Z1, ... , Zn). Given z, the decoder then generates an output sequence (31, ... , ym) of symbols one element at a time. At each step the model is auto-regressive [10], consuming the previously generated symbols as additional input when generating the next.",- metadata: {- page: {- number: 2,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.619,- avgOcrConfidence: 0.969,- },- polygon: [- {- x: 223.9033023806384,- y: 1394.2295871247027,- },- {- x: 1051.703398767179,- y: 1394.2295871247027,- },- {- x: 1051.703398767179,- y: 1505.850527885265,- },- {- x: 223.9033023806384,- y: 1505.850527885265,- },- ],- boundingBox: {- left: 223.9033023806384,- top: 1394.2295871247027,- right: 1051.703398767179,- bottom: 1505.850527885265,- },- },- {- id: "block_2_MzhUlf",- type: "page_number",- content: "2",- metadata: {- page: {- number: 2,- width: 1275,- height: 1651,- },- layoutClass: "Page Number",- minOcrConfidence: 0.995,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 631.4816022441336,- y: 1547.6769732138268,- },- {- x: 642.0810031194757,- y: 1547.6769732138268,- },- {- x: 642.0810031194757,- y: 1563.2578182363868,- },- {- x: 631.4816022441336,- y: 1563.2578182363868,- },- ],- boundingBox: {- left: 631.4816022441336,- top: 1547.6769732138268,- right: 642.0810031194757,- bottom: 1563.2578182363868,- },- },- ],- },- {- blocks: [- {- id: "block_3_afwbz8",- type: "figure",- content:- '<figure type="diagram">\nOutput Probabilities\n\nSoftmax\n\nLinear\n\nAdd & Norm Feed Forward\n\nAdd & Norm\n\nAdd & Norm\n\nMulti-Head Feed Attention Forward Nx\n\nAdd & Norm\n\nNx Add & Norm\n\nMasked Multi-Head Multi-Head Attention Attention\n\nPositional Positional Encoding Encoding Input Output Embedding Embedding\n\nInputs Outputs (shifted right)\n<caption>Transformer Architecture Diagram\n\nLeft Side: Encoder (Nx)\n- Inputs\n\u2193\n- Input Embedding\n\u2193\n- Positional Encoding (added to Input Embedding)\n\u2193\n- Multi-Head Attention\n\u2193\n- Add & Norm\n\u2193\n- Feed Forward\n\u2193\n- Add & Norm\n\nRight Side: Decoder (Nx)\n- Outputs (shifted right)\n\u2193\n- Output Embedding\n\u2193\n- Positional Encoding (added to Output Embedding)\n\u2193\n- Masked Multi-Head Attention\n\u2193\n- Add & Norm\n\u2193\n- Multi-Head Attention (receives input from Encoder\'s Add & Norm)\n\u2193\n- Add & Norm\n\u2193\n- Feed Forward\n\u2193\n- Add & Norm\n\u2193\n- Linear\n\u2193\n- Softmax\n\u2193\n- Output Probabilities</caption>\n</figure>',- metadata: {- page: {- number: 3,- width: 1275,- height: 1651,- },- layoutClass: "Picture/Figure/Image/Chart",- minOcrConfidence: 0.868,- avgOcrConfidence: 0.987,- },- polygon: [- {- x: 409.83791490540887,- y: 150.86351013900642,- },- {- x: 863.1759754932709,- y: 150.86351013900642,- },- {- x: 863.1759754932709,- y: 821.7723977798806,- },- {- x: 409.83791490540887,- y: 821.7723977798806,- },- ],- boundingBox: {- left: 409.83791490540887,- top: 150.86351013900642,- right: 863.1759754932709,- bottom: 821.7723977798806,- },- },- {- id: "block_3_1WIk1S",- type: "text",- content: "Figure 1: The Transformer - model architecture.",- metadata: {- page: {- number: 3,- width: 1275,- height: 1651,- },- layoutClass: "Caption",- minOcrConfidence: 0.989,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 436.4703770101505,- y: 843.2910397178248,- },- {- x: 836.1937028648209,- y: 843.2910397178248,- },- {- x: 836.1937028648209,- y: 863.7018851373429,- },- {- x: 436.4703770101505,- y: 863.7018851373429,- },- ],- boundingBox: {- left: 436.4703770101505,- top: 843.2910397178248,- right: 836.1937028648209,- bottom: 863.7018851373429,- },- },- {- id: "block_3_jyPEOL",- type: "text",- content:- "The Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1, respectively.",- metadata: {- page: {- number: 3,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.973,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 222.86804783953366,- y: 910.1303693154701,- },- {- x: 1051.9256870241932,- y: 910.1303693154701,- },- {- x: 1051.9256870241932,- y: 977.3362178945899,- },- {- x: 222.86804783953366,- y: 977.3362178945899,- },- ],- boundingBox: {- left: 222.86804783953366,- top: 910.1303693154701,- right: 1051.9256870241932,- bottom: 977.3362178945899,- },- },- {- id: "block_3_nEQfm1",- type: "section_heading",- content: "### 3.1 Encoder and Decoder Stacks",- metadata: {- page: {- number: 3,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.995,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 223.72352154585568,- y: 1007.3903008367782,- },- {- x: 527.4041196725664,- y: 1007.3903008367782,- },- {- x: 527.4041196725664,- y: 1023.9329030316575,- },- {- x: 223.72352154585568,- y: 1023.9329030316575,- },- ],- boundingBox: {- left: 223.72352154585568,- top: 1007.3903008367782,- right: 527.4041196725664,- bottom: 1023.9329030316575,- },- },- {- id: "block_3_W2U9b2",- type: "text",- content:- "Encoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position- wise fully connected feed-forward network. We employ a residual connection [11] around each of the two sub-layers, followed by layer normalization [1]. That is, the output of each sub-layer is LayerNorm(x + Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer itself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding layers, produce outputs of dimension dmodel = 512.",- metadata: {- page: {- number: 3,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.657,- avgOcrConfidence: 0.984,- },- polygon: [- {- x: 223.8025010937322,- y: 1048.091523421438,- },- {- x: 1053.5889674277203,- y: 1048.091523421438,- },- {- x: 1053.5889674277203,- y: 1206.3018568225373,- },- {- x: 223.8025010937322,- y: 1206.3018568225373,- },- ],- boundingBox: {- left: 223.8025010937322,- top: 1048.091523421438,- right: 1053.5889674277203,- bottom: 1206.3018568225373,- },- },- {- id: "block_3_8wxg0F",- type: "text",- content:- "Decoder: The decoder is also composed of a stack of N = 6 identical layers. In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head attention over the output of the encoder stack. Similar to the encoder, we employ residual connections around each of the sub-layers, followed by layer normalization. We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position i can depend only on the known outputs at positions less than i.",- metadata: {- page: {- number: 3,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.633,- avgOcrConfidence: 0.99,- },- polygon: [- {- x: 224.16407452882643,- y: 1233.3413921729066,- },- {- x: 1049.721170689938,- y: 1233.3413921729066,- },- {- x: 1049.721170689938,- y: 1391.0596241198086,- },- {- x: 224.16407452882643,- y: 1391.0596241198086,- },- ],- boundingBox: {- left: 224.16407452882643,- top: 1233.3413921729066,- right: 1049.721170689938,- bottom: 1391.0596241198086,- },- },- {- id: "block_3_i0stGS",- type: "section_heading",- content: "### 3.2 Attention",- metadata: {- page: {- number: 3,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.995,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 224.0832962258889,- y: 1421.7722100279386,- },- {- x: 354.57085797386446,- y: 1421.7722100279386,- },- {- x: 354.57085797386446,- y: 1437.668053017523,- },- {- x: 224.0832962258889,- y: 1437.668053017523,- },- ],- boundingBox: {- left: 224.0832962258889,- top: 1421.7722100279386,- right: 354.57085797386446,- bottom: 1437.668053017523,- },- },- {- id: "block_3_LwJLS3",- type: "text",- content:- "An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum",- metadata: {- page: {- number: 3,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.986,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 223.38670466068018,- y: 1462.3713376611695,- },- {- x: 1052.432178580848,- y: 1462.3713376611695,- },- {- x: 1052.432178580848,- y: 1506.3117546138906,- },- {- x: 223.38670466068018,- y: 1506.3117546138906,- },- ],- boundingBox: {- left: 223.38670466068018,- top: 1462.3713376611695,- right: 1052.432178580848,- bottom: 1506.3117546138906,- },- },- {- id: "block_3_gqT8MC",- type: "page_number",- content: "3",- metadata: {- page: {- number: 3,- width: 1275,- height: 1651,- },- layoutClass: "Page Number",- minOcrConfidence: 0.997,- avgOcrConfidence: 0.997,- },- polygon: [- {- x: 632.2706403523466,- y: 1547.236487481827,- },- {- x: 642.0801037419451,- y: 1547.236487481827,- },- {- x: 642.0801037419451,- y: 1562.977578012567,- },- {- x: 632.2706403523466,- y: 1562.977578012567,- },- ],- boundingBox: {- left: 632.2706403523466,- top: 1547.236487481827,- right: 642.0801037419451,- bottom: 1562.977578012567,- },- },- ],- },- {- blocks: [- {- id: "block_4_PplY2k",- type: "header",- content: "Scaled Dot-Product Attention",- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Header",- minOcrConfidence: 0.993,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 307.9120037329458,- y: 148.57123934236685,- },- {- x: 554.1308270753735,- y: 148.57123934236685,- },- {- x: 554.1308270753735,- y: 164.4924521697195,- },- {- x: 307.9120037329458,- y: 164.4924521697195,- },- ],- boundingBox: {- left: 307.9120037329458,- top: 148.57123934236685,- right: 554.1308270753735,- bottom: 164.4924521697195,- },- },- {- id: "block_4_TZACGH",- type: "text",- content: "Multi-Head Attention",- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Caption",- minOcrConfidence: 0.993,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 756.6973442578839,- y: 148.30866211339045,- },- {- x: 937.5759876557511,- y: 148.30866211339045,- },- {- x: 937.5759876557511,- y: 164.44492071911804,- },- {- x: 756.6973442578839,- y: 164.44492071911804,- },- ],- boundingBox: {- left: 756.6973442578839,- top: 148.30866211339045,- right: 937.5759876557511,- bottom: 164.44492071911804,- },- },- {- id: "block_4_yRQL9Y",- type: "figure",- content:- '<figure type="diagram">\n1 MatMul\n\n1 SoftMax 1 Mask (opt.) 1 Scale 1 MatMul 1 1 Q K V\n<caption>Scaled Dot-Product Attention Diagram\n\nInputs: Q, K, V\n\n1. MatMul (Q, K)\n \u2193\n2. Scale\n \u2193\n3. Mask (opt.)\n \u2193\n4. SoftMax\n \u2193\n5. MatMul (Result of SoftMax, V)\n \u2193\nOutput</caption>\n</figure>',- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Picture/Figure/Image/Chart",- minOcrConfidence: 0.226,- avgOcrConfidence: 0.815,- },- polygon: [- {- x: 364.7714322500855,- y: 195.77549835434533,- },- {- x: 497.28713766501767,- y: 195.77549835434533,- },- {- x: 497.28713766501767,- y: 457.62115733784844,- },- {- x: 364.7714322500855,- y: 457.62115733784844,- },- ],- boundingBox: {- left: 364.7714322500855,- top: 195.77549835434533,- right: 497.28713766501767,- bottom: 457.62115733784844,- },- },- {- id: "block_4_goCdts",- type: "figure",- content:- '<figure type="diagram">\nLinear\n\nConcat\n\nScaled Dot-Product\n\nh\n\nAttention\n\nLinear Linear Linear\n\nV K Q\n<caption>Multi-Head Attention\n\nInputs: V, K, Q\n\u2193\nLinear (x3) \u2192 Scaled Dot-Product Attention (h heads)\n\u2193\nConcat\n\u2193\nLinear</caption>\n</figure>',- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Picture/Figure/Image/Chart",- minOcrConfidence: 0.981,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 723.0441991430129,- y: 171.2063080421964,- },- {- x: 971.0292342805515,- y: 171.2063080421964,- },- {- x: 971.0292342805515,- y: 495.8982404264292,- },- {- x: 723.0441991430129,- y: 495.8982404264292,- },- ],- boundingBox: {- left: 723.0441991430129,- top: 171.2063080421964,- right: 971.0292342805515,- bottom: 495.8982404264292,- },- },- {- id: "block_4_ZQ6XHX",- type: "text",- content:- "Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel.",- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Caption",- minOcrConfidence: 0.991,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 224.32437673972473,- y: 572.2067347074809,- },- {- x: 1050.060662039875,- y: 572.2067347074809,- },- {- x: 1050.060662039875,- y: 615.706381804961,- },- {- x: 224.32437673972473,- y: 615.706381804961,- },- ],- boundingBox: {- left: 224.32437673972473,- top: 572.2067347074809,- right: 1050.060662039875,- bottom: 615.706381804961,- },- },- {- id: "block_4_seZO33",- type: "text",- content:- "of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.",- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.989,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 224.44408862260138,- y: 661.3754045586836,- },- {- x: 1049.3653012018135,- y: 661.3754045586836,- },- {- x: 1049.3653012018135,- y: 705.0281940833071,- },- {- x: 224.44408862260138,- y: 705.0281940833071,- },- ],- boundingBox: {- left: 224.44408862260138,- top: 661.3754045586836,- right: 1049.3653012018135,- bottom: 705.0281940833071,- },- },- {- id: "block_4_CMgLHk",- type: "section_heading",- content: "### 3.2.1 Scaled Dot-Product Attention",- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 223.53467593227862,- y: 732.4767248397483,- },- {- x: 549.2687448097842,- y: 732.4767248397483,- },- {- x: 549.2687448097842,- y: 748.6887496431967,- },- {- x: 223.53467593227862,- y: 748.6887496431967,- },- ],- boundingBox: {- left: 223.53467593227862,- top: 732.4767248397483,- right: 549.2687448097842,- bottom: 748.6887496431967,- },- },- {- id: "block_4_fmfLoy",- type: "text",- content:- 'We call our particular attention "Scaled Dot-Product Attention" (Figure 2). The input consists of queries and keys of dimension dk, and values of dimension dy. We compute the dot products of the\n\nquery with all keys, divide each by Vdk, and apply a softmafunction to obtain the weights on the [x]\n\nvalues.',- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.594,- avgOcrConfidence: 0.98,- },- polygon: [- {- x: 223.39593511428276,- y: 771.1101458269851,- },- {- x: 1051.4275265436104,- y: 771.1101458269851,- },- {- x: 1051.4275265436104,- y: 856.1295272138783,- },- {- x: 223.39593511428276,- y: 856.1295272138783,- },- ],- boundingBox: {- left: 223.39593511428276,- top: 771.1101458269851,- right: 1051.4275265436104,- bottom: 856.1295272138783,- },- },- {- id: "block_4_cDuW6h",- type: "text",- content:- "In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix Q. The keys and values are also packed together into matrices K and V. We compute the matrix of outputs as:",- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.976,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 224.08788778486044,- y: 873.4355685585424,- },- {- x: 1050.3812191260122,- y: 873.4355685585424,- },- {- x: 1050.3812191260122,- y: 938.6725377821385,- },- {- x: 224.08788778486044,- y: 938.6725377821385,- },- ],- boundingBox: {- left: 224.08788778486044,- top: 873.4355685585424,- right: 1050.3812191260122,- bottom: 938.6725377821385,- },- },- {- id: "block_4_VaSWNE",- type: "text",- content: "QKT Attention(Q, K, V) = softmax( V Vdk",- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Formula",- minOcrConfidence: 0.908,- avgOcrConfidence: 0.961,- },- polygon: [- {- x: 458.52888900868214,- y: 968.9788274549901,- },- {- x: 816.6205023327013,- y: 968.9788274549901,- },- {- x: 816.6205023327013,- y: 1021.9395890773686,- },- {- x: 458.52888900868214,- y: 1021.9395890773686,- },- ],- boundingBox: {- left: 458.52888900868214,- top: 968.9788274549901,- right: 816.6205023327013,- bottom: 1021.9395890773686,- },- },- {- id: "block_4_Wtl7xI",- type: "text",- content: "(1)",- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Caption",- minOcrConfidence: 0.995,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 1026.9459968065694,- y: 986.4570474839747,- },- {- x: 1051.0514920645387,- y: 986.4570474839747,- },- {- x: 1051.0514920645387,- y: 1005.8566982871607,- },- {- x: 1026.9459968065694,- y: 1005.8566982871607,- },- ],- boundingBox: {- left: 1026.9459968065694,- top: 986.4570474839747,- right: 1051.0514920645387,- bottom: 1005.8566982871607,- },- },- {- id: "block_4_HVInAp",- type: "text",- content:- "The two most commonly used attention functions are additive attention [2], and dot-product (multi- plicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor\n\nof . Additive attention computes the compatibility function using a feed-forward network with [x] Vdk\n\na single hidden layer. While the two are similar in theoretical complexity, dot-product attention is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code.",- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.098,- avgOcrConfidence: 0.981,- },- polygon: [- {- x: 223.11696240501684,- y: 1041.6009173859331,- },- {- x: 1052.8067929901345,- y: 1041.6009173859331,- },- {- x: 1052.8067929901345,- y: 1180.0422397699572,- },- {- x: 223.11696240501684,- y: 1180.0422397699572,- },- ],- boundingBox: {- left: 223.11696240501684,- top: 1041.6009173859331,- right: 1052.8067929901345,- bottom: 1180.0422397699572,- },- },- {- id: "block_4_6NHlzf",- type: "text",- content:- "While for small values of dk the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of dk [3]. We suspect that for large values of dk, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients 4. To counteract this effect, we scale the dot products by.",- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.58,- avgOcrConfidence: 0.98,- },- polygon: [- {- x: 223.18699551324775,- y: 1194.0708248167111,- },- {- x: 1050.8364934990875,- y: 1194.0708248167111,- },- {- x: 1050.8364934990875,- y: 1289.5664457163416,- },- {- x: 223.18699551324775,- y: 1289.5664457163416,- },- ],- boundingBox: {- left: 223.18699551324775,- top: 1194.0708248167111,- right: 1050.8364934990875,- bottom: 1289.5664457163416,- },- },- {- id: "block_4_4VWmvI",- type: "section_heading",- content: "### 3.2.2 Multi-Head Attention",- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.994,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 223.5976323594142,- y: 1315.4335938647278,- },- {- x: 479.8474026422431,- y: 1315.4335938647278,- },- {- x: 479.8474026422431,- y: 1331.4542616650574,- },- {- x: 223.5976323594142,- y: 1331.4542616650574,- },- ],- boundingBox: {- left: 223.5976323594142,- top: 1315.4335938647278,- right: 479.8474026422431,- bottom: 1331.4542616650574,- },- },- {- id: "block_4_n7aPpb",- type: "text",- content:- "Instead of performing a single attention function with dmodel-dimensional keys, values and queries, we found it beneficial to linearly project the queries, keys and values h times with different, learned linear projections to dk, dk and dy dimensions, respectively. On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding dy-dimensional",- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.619,- avgOcrConfidence: 0.979,- },- polygon: [- {- x: 223.83094982509195,- y: 1354.33461159154,- },- {- x: 1052.0098498267848,- y: 1354.33461159154,- },- {- x: 1052.0098498267848,- y: 1442.8801044664883,- },- {- x: 223.83094982509195,- y: 1442.8801044664883,- },- ],- boundingBox: {- left: 223.83094982509195,- top: 1354.33461159154,- right: 1052.0098498267848,- bottom: 1442.8801044664883,- },- },- {- id: "block_4_rfqNPC",- type: "text",- content:- "4To illustrate why the dot products get large, assume that the components of q and k are independent random variables with mean 0 and variance 1. Then their dot product, q \u00b7 k = >i=1 qiki, has mean 0 and variance dk-",- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.105,- avgOcrConfidence: 0.921,- },- polygon: [- {- x: 224.42529636577967,- y: 1459.9841341864794,- },- {- x: 1049.4534401998033,- y: 1459.9841341864794,- },- {- x: 1049.4534401998033,- y: 1506.815978659723,- },- {- x: 224.42529636577967,- y: 1506.815978659723,- },- ],- boundingBox: {- left: 224.42529636577967,- top: 1459.9841341864794,- right: 1049.4534401998033,- bottom: 1506.815978659723,- },- },- {- id: "block_4_35BhDQ",- type: "page_number",- content: "4",- metadata: {- page: {- number: 4,- width: 1275,- height: 1651,- },- layoutClass: "Page Number",- minOcrConfidence: 0.996,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 631.2688757903385,- y: 1548.1330857241064,- },- {- x: 642.0564832478544,- y: 1548.1330857241064,- },- {- x: 642.0564832478544,- y: 1562.0727401962854,- },- {- x: 631.2688757903385,- y: 1562.0727401962854,- },- ],- boundingBox: {- left: 631.2688757903385,- top: 1548.1330857241064,- right: 642.0564832478544,- bottom: 1562.0727401962854,- },- },- ],- },- {- blocks: [- {- id: "block_5_Zc8VSW",- type: "text",- content:- "output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure 2.",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.988,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 224.67903916853186,- y: 155.68632458564932,- },- {- x: 1049.4719957783275,- y: 155.68632458564932,- },- {- x: 1049.4719957783275,- y: 199.30535079841326,- },- {- x: 224.67903916853186,- y: 199.30535079841326,- },- ],- boundingBox: {- left: 224.67903916853186,- top: 155.68632458564932,- right: 1049.4719957783275,- bottom: 199.30535079841326,- },- },- {- id: "block_5_P72mUL",- type: "text",- content:- "Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 224.58133836732293,- y: 212.29537068990837,- },- {- x: 1049.5524663994781,- y: 212.29537068990837,- },- {- x: 1049.5524663994781,- y: 255.9039790504857,- },- {- x: 224.58133836732293,- y: 255.9039790504857,- },- ],- boundingBox: {- left: 224.58133836732293,- top: 212.29537068990837,- right: 1049.5524663994781,- bottom: 255.9039790504857,- },- },- {- id: "block_5_zTpvNY",- type: "text",- content:- "MultiHead(Q,K,V)=Concat(head1, ... , headh)W\u00ba where head; = Attention(Qw?, KWK,VW)",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "Formula",- minOcrConfidence: 0.581,- avgOcrConfidence: 0.796,- },- polygon: [- {- x: 388.73733464818804,- y: 302.5467395065422,- },- {- x: 883.3280911410811,- y: 302.5467395065422,- },- {- x: 883.3280911410811,- y: 364.6030674267532,- },- {- x: 388.73733464818804,- y: 364.6030674267532,- },- ],- boundingBox: {- left: 388.73733464818804,- top: 302.5467395065422,- right: 883.3280911410811,- bottom: 364.6030674267532,- },- },- {- id: "block_5_cOSQOc",- type: "text",- content:- "Where the projections are parameter matrices Wo E Rdmodel X dk , WK \u20ac Rdmodel X dk , WY \u20ac Rdmodel X dy and WO E Rhdy Xdmodel",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.252,- avgOcrConfidence: 0.682,- },- polygon: [- {- x: 223.51567066498916,- y: 424.5787134959285,- },- {- x: 1047.1388211215499,- y: 424.5787134959285,- },- {- x: 1047.1388211215499,- y: 472.1556711698833,- },- {- x: 223.51567066498916,- y: 472.1556711698833,- },- ],- boundingBox: {- left: 223.51567066498916,- top: 424.5787134959285,- right: 1047.1388211215499,- bottom: 472.1556711698833,- },- },- {- id: "block_5_4oR3J2",- type: "text",- content:- "In this work we employ h = 8 parallel attention layers, or heads. For each of these we use dk = dy = dmodel/h = 64. Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality.",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.557,- avgOcrConfidence: 0.98,- },- polygon: [- {- x: 223.83189653828197,- y: 488.323372747665,- },- {- x: 1049.9097559573877,- y: 488.323372747665,- },- {- x: 1049.9097559573877,- y: 555.0531728357302,- },- {- x: 223.83189653828197,- y: 555.0531728357302,- },- ],- boundingBox: {- left: 223.83189653828197,- top: 488.323372747665,- right: 1049.9097559573877,- bottom: 555.0531728357302,- },- },- {- id: "block_5_oGR7Tp",- type: "section_heading",- content: "### 3.2.3 Applications of Attention in our Model",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.994,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 223.9031130380004,- y: 584.1135347409356,- },- {- x: 629.6546824657133,- y: 584.1135347409356,- },- {- x: 629.6546824657133,- y: 605.02614180486,- },- {- x: 223.9031130380004,- y: 605.02614180486,- },- ],- boundingBox: {- left: 223.9031130380004,- top: 584.1135347409356,- right: 629.6546824657133,- bottom: 605.02614180486,- },- },- {- id: "block_5_b34egv",- type: "text",- content:- "The Transformer uses multi-head attention in three different ways:",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 223.3985859112148,- y: 623.9660812033746,- },- {- x: 775.7513199409428,- y: 623.9660812033746,- },- {- x: 775.7513199409428,- y: 644.7702005429376,- },- {- x: 223.3985859112148,- y: 644.7702005429376,- },- ],- boundingBox: {- left: 223.3985859112148,- top: 623.9660812033746,- right: 775.7513199409428,- bottom: 644.7702005429376,- },- },- {- id: "block_5_NSYaLO",- type: "text",- content:- '\u00b7 In "encoder-decoder attention" layers, the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder. This allows every position in the decoder to attend over all positions in the input sequence. This mimics the typical encoder-decoder attention mechanisms in sequence-to-sequence models such as [38, 2, 9].',- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.586,- avgOcrConfidence: 0.984,- },- polygon: [- {- x: 281.7719981618171,- y: 667.4162908568419,- },- {- x: 1052.1352893244612,- y: 667.4162908568419,- },- {- x: 1052.1352893244612,- y: 778.3123385207098,- },- {- x: 281.7719981618171,- y: 778.3123385207098,- },- ],- boundingBox: {- left: 281.7719981618171,- top: 667.4162908568419,- right: 1052.1352893244612,- bottom: 778.3123385207098,- },- },- {- id: "block_5_ZbEUX6",- type: "text",- content:- "\u00b7 The encoder contains self-attention layers. In a self-attention layer all of the keys, values and queries come from the same place, in this case, the output of the previous layer in the encoder. Each position in the encoder can attend to all positions in the previous layer of the encoder.",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.407,- avgOcrConfidence: 0.983,- },- polygon: [- {- x: 282.1731915439132,- y: 791.5420637202442,- },- {- x: 1049.6795153095775,- y: 791.5420637202442,- },- {- x: 1049.6795153095775,- y: 876.9418387735697,- },- {- x: 282.1731915439132,- y: 876.9418387735697,- },- ],- boundingBox: {- left: 282.1731915439132,- top: 791.5420637202442,- right: 1049.6795153095775,- bottom: 876.9418387735697,- },- },- {- id: "block_5_wkxEH8",- type: "text",- content:- "\u00b7 Similarly, self-attention layers in the decoder allow each position in the decoder to attend to all positions in the decoder up to and including that position. We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to -oo) all values in the input of the softmax which correspond to illegal connections. See Figure 2.",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.543,- avgOcrConfidence: 0.985,- },- polygon: [- {- x: 281.12820952478114,- y: 893.687589086088,- },- {- x: 1049.8325041610829,- y: 893.687589086088,- },- {- x: 1049.8325041610829,- y: 1005.0602061336201,- },- {- x: 281.12820952478114,- y: 1005.0602061336201,- },- ],- boundingBox: {- left: 281.12820952478114,- top: 893.687589086088,- right: 1049.8325041610829,- bottom: 1005.0602061336201,- },- },- {- id: "block_5_vVMF0e",- type: "section_heading",- content: "### 3.3 Position-wise Feed-Forward Networks",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 223.59919443617773,- y: 1037.180243872162,- },- {- x: 609.3837069768975,- y: 1037.180243872162,- },- {- x: 609.3837069768975,- y: 1053.935843790384,- },- {- x: 223.59919443617773,- y: 1053.935843790384,- },- ],- boundingBox: {- left: 223.59919443617773,- top: 1037.180243872162,- right: 609.3837069768975,- bottom: 1053.935843790384,- },- },- {- id: "block_5_WtW3Xc",- type: "text",- content:- "In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forward network, which is applied to each position separately and identically. This consists of two linear transformations with a ReLU activation in between.",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.986,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 223.937928415563,- y: 1079.1571798109471,- },- {- x: 1049.736412772297,- y: 1079.1571798109471,- },- {- x: 1049.736412772297,- y: 1142.9025967246607,- },- {- x: 223.937928415563,- y: 1142.9025967246607,- },- ],- boundingBox: {- left: 223.937928415563,- top: 1079.1571798109471,- right: 1049.736412772297,- bottom: 1142.9025967246607,- },- },- {- id: "block_5_TCB4QK",- type: "text",- content: "FFN(x)=max(0,xW1+b1)W2+b2",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "Formula",- minOcrConfidence: 0.668,- avgOcrConfidence: 0.668,- },- polygon: [- {- x: 471.6477776965956,- y: 1184.1576702146604,- },- {- x: 801.1487473536581,- y: 1184.1576702146604,- },- {- x: 801.1487473536581,- y: 1206.444581397494,- },- {- x: 471.6477776965956,- y: 1206.444581397494,- },- ],- boundingBox: {- left: 471.6477776965956,- top: 1184.1576702146604,- right: 801.1487473536581,- bottom: 1206.444581397494,- },- },- {- id: "block_5_olGJjx",- type: "text",- content: "(2)",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "Caption",- minOcrConfidence: 0.997,- avgOcrConfidence: 0.997,- },- polygon: [- {- x: 1026.9936164800267,- y: 1185.5856736262042,- },- {- x: 1051.1806237436558,- y: 1185.5856736262042,- },- {- x: 1051.1806237436558,- y: 1204.3962422421102,- },- {- x: 1026.9936164800267,- y: 1204.3962422421102,- },- ],- boundingBox: {- left: 1026.9936164800267,- top: 1185.5856736262042,- right: 1051.1806237436558,- bottom: 1204.3962422421102,- },- },- {- id: "block_5_KTjDsL",- type: "text",- content:- "While the linear transformations are the same across different positions, they use different parameters from layer to layer. Another way of describing this is as two convolutions with kernel size 1. The dimensionality of input and output is dmodel = 512, and the inner-layer has dimensionality dff =2048.",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.881,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 222.78797957148865,- y: 1230.1093008858818,- },- {- x: 1052.541145269018,- y: 1230.1093008858818,- },- {- x: 1052.541145269018,- y: 1320.3967533541802,- },- {- x: 222.78797957148865,- y: 1320.3967533541802,- },- ],- boundingBox: {- left: 222.78797957148865,- top: 1230.1093008858818,- right: 1052.541145269018,- bottom: 1320.3967533541802,- },- },- {- id: "block_5_Pwzvu2",- type: "section_heading",- content: "### 3.4 Embeddings and Softmax",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.995,- avgOcrConfidence: 0.997,- },- polygon: [- {- x: 223.80512822283447,- y: 1351.0096120045598,- },- {- x: 499.655388045485,- y: 1351.0096120045598,- },- {- x: 499.655388045485,- y: 1371.2419333206979,- },- {- x: 223.80512822283447,- y: 1371.2419333206979,- },- ],- boundingBox: {- left: 223.80512822283447,- top: 1351.0096120045598,- right: 499.655388045485,- bottom: 1371.2419333206979,- },- },- {- id: "block_5_6y9ZGB",- type: "text",- content:- "Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension dmodel. We also use the usual learned linear transfor- mation and softmax function to convert the decoder output to predicted next-token probabilities. In our model, we share the same weight matrix between the two embedding layers and the pre-softmax linear transformation, similar to [30]. In the embedding layers, we multiply those weights by Vdmodel -",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.275,- avgOcrConfidence: 0.983,- },- polygon: [- {- x: 224.49331770848184,- y: 1394.318801822519,- },- {- x: 1052.2855327077154,- y: 1394.318801822519,- },- {- x: 1052.2855327077154,- y: 1505.8341434450076,- },- {- x: 224.49331770848184,- y: 1505.8341434450076,- },- ],- boundingBox: {- left: 224.49331770848184,- top: 1394.318801822519,- right: 1052.2855327077154,- bottom: 1505.8341434450076,- },- },- {- id: "block_5_o8MKrc",- type: "page_number",- content: "5",- metadata: {- page: {- number: 5,- width: 1275,- height: 1651,- },- layoutClass: "Page Number",- minOcrConfidence: 0.995,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 631.5606054598397,- y: 1547.4356578740858,- },- {- x: 641.9868998283888,- y: 1547.4356578740858,- },- {- x: 641.9868998283888,- y: 1563.1716341864794,- },- {- x: 631.5606054598397,- y: 1563.1716341864794,- },- ],- boundingBox: {- left: 631.5606054598397,- top: 1547.4356578740858,- right: 641.9868998283888,- bottom: 1563.1716341864794,- },- },- ],- },- {- blocks: [- {- id: "block_6_YmUPFZ",- type: "text",- content:- "Table 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations for different layer types. n is the sequence length, d is the representation dimension, k is the kernel size of convolutions and r the size of the neighborhood in restricted self-attention.",- metadata: {- page: {- number: 6,- width: 1275,- height: 1651,- },- layoutClass: "Caption",- minOcrConfidence: 0.977,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 222.7798615058843,- y: 148.2273318355245,- },- {- x: 1048.906618661254,- y: 148.2273318355245,- },- {- x: 1048.906618661254,- y: 214.40370720311216,- },- {- x: 222.7798615058843,- y: 214.40370720311216,- },- ],- boundingBox: {- left: 222.7798615058843,- top: 148.2273318355245,- right: 1048.906618661254,- bottom: 214.40370720311216,- },- },- {- id: "block_6_kibLxu",- type: "table",- content:- "| Layer Type | Complexity per Layer | Sequential Operations | Maximum Path Length |\n| --- | --- | --- | --- |\n| Self-Attention | O(n2 \u00b7 d) | O(1) | O(1) |\n| Recurrent | O(n \u00b7 d2) | O(n) | O(n) |\n| Convolutional | O(k \u00b7 n \u00b7 d2) | O(1) | O(logk(n)) |\n| Self-Attention (restricted) | O(r . n . d) [ ] | O(1) | O(n/r) [ ] |",- metadata: {- page: {- number: 6,- width: 1275,- height: 1651,- },- layoutClass: "Table",- minOcrConfidence: 0.256,- avgOcrConfidence: 0.856,- },- polygon: [- {- x: 246.08119491243013,- y: 233.8958637983279,- },- {- x: 1028.2713006012632,- y: 233.8958637983279,- },- {- x: 1028.2713006012632,- y: 389.94297754674926,- },- {- x: 246.08119491243013,- y: 389.94297754674926,- },- ],- boundingBox: {- left: 246.08119491243013,- top: 233.8958637983279,- right: 1028.2713006012632,- bottom: 389.94297754674926,- },- },- {- id: "block_6_tUIpoY",- type: "section_heading",- content: "### 3.5 Positional Encoding",- metadata: {- page: {- number: 6,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 224.00651778617916,- y: 445.9595083078944,- },- {- x: 448.20427163674015,- y: 445.9595083078944,- },- {- x: 448.20427163674015,- y: 466.69903696390026,- },- {- x: 224.00651778617916,- y: 466.69903696390026,- },- ],- boundingBox: {- left: 224.00651778617916,- top: 445.9595083078944,- right: 448.20427163674015,- bottom: 466.69903696390026,- },- },- {- id: "block_6_mmxGrc",- type: "text",- content:- 'Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence. To this end, we add "positional encodings" to the input embeddings at the bottoms of the encoder and decoder stacks. The positional encodings have the same dimension dmodel as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [9].',- metadata: {- page: {- number: 6,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.912,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 223.83698512167825,- y: 487.3354288832586,- },- {- x: 1050.4121766473256,- y: 487.3354288832586,- },- {- x: 1050.4121766473256,- y: 620.7750930786133,- },- {- x: 223.83698512167825,- y: 620.7750930786133,- },- ],- boundingBox: {- left: 223.83698512167825,- top: 487.3354288832586,- right: 1050.4121766473256,- bottom: 620.7750930786133,- },- },- {- id: "block_6_NG2aN8",- type: "text",- content:- "In this work, we use sine and cosine functions of different frequencies:",- metadata: {- page: {- number: 6,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 224.39521455416715,- y: 635.0555533789154,- },- {- x: 810.5588871197108,- y: 635.0555533789154,- },- {- x: 810.5588871197108,- y: 655.9754529393705,- },- {- x: 224.39521455416715,- y: 655.9754529393705,- },- ],- boundingBox: {- left: 224.39521455416715,- top: 635.0555533789154,- right: 810.5588871197108,- bottom: 655.9754529393705,- },- },- {- id: "block_6_ktOzAP",- type: "text",- content:- "PE(pos,2i) = sin(pos/100002i/dmodel ) PE(pos,2i+1) = cos(pos/100002i/dmodel) )",- metadata: {- page: {- number: 6,- width: 1275,- height: 1651,- },- layoutClass: "Formula",- minOcrConfidence: 0.646,- avgOcrConfidence: 0.856,- },- polygon: [- {- x: 470.62755222738224,- y: 700.6432727440855,- },- {- x: 804.2361684089159,- y: 700.6432727440855,- },- {- x: 804.2361684089159,- y: 763.5065343469606,- },- {- x: 470.62755222738224,- y: 763.5065343469606,- },- ],- boundingBox: {- left: 470.62755222738224,- top: 700.6432727440855,- right: 804.2361684089159,- bottom: 763.5065343469606,- },- },- {- id: "block_6_L0vHNu",- type: "text",- content:- "where pos is the position and i is the dimension. That is, each dimension of the positional encoding corresponds to a sinusoid. The wavelengths form a geometric progression from 27 to 10000 . 27. We chose this function because we hypothesized it would allow the model to easily learn to attend by relative positions, since for any fixed offset k, PEpos+k can be represented as a linear function of PEpos.",- metadata: {- page: {- number: 6,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.291,- avgOcrConfidence: 0.967,- },- polygon: [- {- x: 223.63699196028884,- y: 787.3148307800293,- },- {- x: 1050.8335586881985,- y: 787.3148307800293,- },- {- x: 1050.8335586881985,- y: 900.202535012611,- },- {- x: 223.63699196028884,- y: 900.202535012611,- },- ],- boundingBox: {- left: 223.63699196028884,- top: 787.3148307800293,- right: 1050.8335586881985,- bottom: 900.202535012611,- },- },- {- id: "block_6_Sai49H",- type: "text",- content:- "We also experimented with using learned positional embeddings [9] instead, and found that the two versions produced nearly identical results (see Table 3 row (E)). We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.",- metadata: {- page: {- number: 6,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.868,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 223.15007369883736,- y: 912.2991767252298,- },- {- x: 1049.522644933993,- y: 912.2991767252298,- },- {- x: 1049.522644933993,- y: 1000.5864015736975,- },- {- x: 223.15007369883736,- y: 1000.5864015736975,- },- ],- boundingBox: {- left: 223.15007369883736,- top: 912.2991767252298,- right: 1049.522644933993,- bottom: 1000.5864015736975,- },- },- {- id: "block_6_545oKE",- type: "section_heading",- content: "### 4 Why Self-Attention",- metadata: {- page: {- number: 6,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 223.44270274586924,- y: 1036.185907234823,- },- {- x: 468.14631162768734,- y: 1036.185907234823,- },- {- x: 468.14631162768734,- y: 1059.806398205291,- },- {- x: 223.44270274586924,- y: 1059.806398205291,- },- ],- boundingBox: {- left: 223.44270274586924,- top: 1036.185907234823,- right: 468.14631162768734,- bottom: 1059.806398205291,- },- },- {- id: "block_6_rdkytl",- type: "text",- content:- "In this section we compare various aspects of self-attention layers to the recurrent and convolu- tional layers commonly used for mapping one variable-length sequence of symbol representations (x1, ... , In) to another sequence of equal length (21, ... , Zn), with xi, Zi E Rd, such as a hidden layer in a typical sequence transduction encoder or decoder. Motivating our use of self-attention we consider three desiderata.",- metadata: {- page: {- number: 6,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.298,- avgOcrConfidence: 0.936,- },- polygon: [- {- x: 222.55295802206888,- y: 1087.3066867455505,- },- {- x: 1052.7677884067061,- y: 1087.3066867455505,- },- {- x: 1052.7677884067061,- y: 1195.3768446499244,- },- {- x: 222.55295802206888,- y: 1195.3768446499244,- },- ],- boundingBox: {- left: 222.55295802206888,- top: 1087.3066867455505,- right: 1052.7677884067061,- bottom: 1195.3768446499244,- },- },- {- id: "block_6_y2UJTk",- type: "text",- content:- "One is the total computational complexity per layer. Another is the amount of computation that can be parallelized, as measured by the minimum number of sequential operations required.",- metadata: {- page: {- number: 6,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 223.43593374656064,- y: 1212.4905345601246,- },- {- x: 1048.7435946499345,- y: 1212.4905345601246,- },- {- x: 1048.7435946499345,- y: 1255.7911059730932,- },- {- x: 223.43593374656064,- y: 1255.7911059730932,- },- ],- boundingBox: {- left: 223.43593374656064,- top: 1212.4905345601246,- right: 1048.7435946499345,- bottom: 1255.7911059730932,- },- },- {- id: "block_6_OGHshO",- type: "text",- content:- "The third is the path length between long-range dependencies in the network. Learning long-range dependencies is a key challenge in many sequence transduction tasks. One key factor affecting the ability to learn such dependencies is the length of the paths forward and backward signals have to traverse in the network. The shorter these paths between any combination of positions in the input and output sequences, the easier it is to learn long-range dependencies [12]. Hence we also compare the maximum path length between any two input and output positions in networks composed of the different layer types.",- metadata: {- page: {- number: 6,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.983,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 222.87737296445525,- y: 1268.8657945905413,- },- {- x: 1049.749950770914,- y: 1268.8657945905413,- },- {- x: 1049.749950770914,- y: 1426.1352065236945,- },- {- x: 222.87737296445525,- y: 1426.1352065236945,- },- ],- boundingBox: {- left: 222.87737296445525,- top: 1268.8657945905413,- right: 1049.749950770914,- bottom: 1426.1352065236945,- },- },- {- id: "block_6_zgN3wO",- type: "text",- content:- "As noted in Table 1, a self-attention layer connects all positions with a constant number of sequentially executed operations, whereas a recurrent layer requires O(n) sequential operations. In terms of computational complexity, self-attention layers are faster than recurrent layers when the sequence",- metadata: {- page: {- number: 6,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.963,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 223.4352473794979,- y: 1439.235182109632,- },- {- x: 1051.6017217705719,- y: 1439.235182109632,- },- {- x: 1051.6017217705719,- y: 1506.1062388025728,- },- {- x: 223.4352473794979,- y: 1506.1062388025728,- },- ],- boundingBox: {- left: 223.4352473794979,- top: 1439.235182109632,- right: 1051.6017217705719,- bottom: 1506.1062388025728,- },- },- {- id: "block_6_aNgpKT",- type: "page_number",- content: "6",- metadata: {- page: {- number: 6,- width: 1275,- height: 1651,- },- layoutClass: "Page Number",- minOcrConfidence: 0.993,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 631.7702550957673,- y: 1548.2886905526757,- },- {- x: 642.7105200551722,- y: 1548.2886905526757,- },- {- x: 642.7105200551722,- y: 1563.5418467700931,- },- {- x: 631.7702550957673,- y: 1563.5418467700931,- },- ],- boundingBox: {- left: 631.7702550957673,- top: 1548.2886905526757,- right: 642.7105200551722,- bottom: 1563.5418467700931,- },- },- ],- },- {- blocks: [- {- id: "block_7_u723hy",- type: "text",- content:- "length n is smaller than the representation dimensionality d, which is most often the case with sentence representations used by state-of-the-art models in machine translations, such as word-piece [38] and byte-pair [31] representations. To improve computational performance for tasks involving very long sequences, self-attention could be restricted to considering only a neighborhood of size r in the input sequence centered around the respective output position. This would increase the maximum path length to O(n/r). We plan to investigate this approach further in future work.",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.909,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 223.89144479793353,- y: 155.39061148363845,- },- {- x: 1050.0338700565978,- y: 155.39061148363845,- },- {- x: 1050.0338700565978,- y: 290.11272512163436,- },- {- x: 223.89144479793353,- y: 290.11272512163436,- },- ],- boundingBox: {- left: 223.89144479793353,- top: 155.39061148363845,- right: 1050.0338700565978,- bottom: 290.11272512163436,- },- },- {- id: "block_7_SLgoxa",- type: "text",- content:- "A single convolutional layer with kernel width k < n does not connect all pairs of input and output positions. Doing so requires a stack of O(n/k) convolutional layers in the case of contiguous kernels, or O(logk(n)) in the case of dilated convolutions [18], increasing the length of the longest paths between any two positions in the network. Convolutional layers are generally more expensive than recurrent layers, by a factor of k. Separable convolutions [6], however, decrease the complexity considerably, to O(k . n . d + n . d2). Even with k = n, however, the complexity of a separable convolution is equal to the combination of a self-attention layer and a point-wise feed-forward layer, the approach we take in our model.",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.525,- avgOcrConfidence: 0.977,- },- polygon: [- {- x: 223.84822734080961,- y: 303.4973448416344,- },- {- x: 1051.7048188369638,- y: 303.4973448416344,- },- {- x: 1051.7048188369638,- y: 482.7421505003047,- },- {- x: 223.84822734080961,- y: 482.7421505003047,- },- ],- boundingBox: {- left: 223.84822734080961,- top: 303.4973448416344,- right: 1051.7048188369638,- bottom: 482.7421505003047,- },- },- {- id: "block_7_lGN5L0",- type: "text",- content:- "As side benefit, self-attention could yield more interpretable models. We inspect attention distributions from our models and present and discuss examples in the appendix. Not only do individual attention heads clearly learn to perform different tasks, many appear to exhibit behavior related to the syntactic and semantic structure of the sentences.",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.94,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 223.7218884656029,- y: 496.4417208334557,- },- {- x: 1049.5183847246378,- y: 496.4417208334557,- },- {- x: 1049.5183847246378,- y: 581.3287481437052,- },- {- x: 223.7218884656029,- y: 581.3287481437052,- },- ],- boundingBox: {- left: 223.7218884656029,- top: 496.4417208334557,- right: 1049.5183847246378,- bottom: 581.3287481437052,- },- },- {- id: "block_7_FOtl5B",- type: "heading",- content: "# 5 Training",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Heading",- minOcrConfidence: 0.989,- avgOcrConfidence: 0.992,- },- polygon: [- {- x: 224.4122553915873,- y: 625.3390120599503,- },- {- x: 354.91415984439146,- y: 625.3390120599503,- },- {- x: 354.91415984439146,- y: 649.7166914688913,- },- {- x: 224.4122553915873,- y: 649.7166914688913,- },- ],- boundingBox: {- left: 224.4122553915873,- top: 625.3390120599503,- right: 354.91415984439146,- bottom: 649.7166914688913,- },- },- {- id: "block_7_3jYBCf",- type: "text",- content: "This section describes the training regime for our models.",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 222.4527957665659,- y: 679.1303132709704,- },- {- x: 701.988161741382,- y: 679.1303132709704,- },- {- x: 701.988161741382,- y: 699.7081758025894,- },- {- x: 222.4527957665659,- y: 699.7081758025894,- },- ],- boundingBox: {- left: 222.4527957665659,- top: 679.1303132709704,- right: 701.988161741382,- bottom: 699.7081758025894,- },- },- {- id: "block_7_PIafds",- type: "section_heading",- content: "### 5.1 Training Data and Batching",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 223.68002007477475,- y: 735.0401794318866,- },- {- x: 519.6398407873446,- y: 735.0401794318866,- },- {- x: 519.6398407873446,- y: 755.8565634247055,- },- {- x: 223.68002007477475,- y: 755.8565634247055,- },- ],- boundingBox: {- left: 223.68002007477475,- top: 735.0401794318866,- right: 519.6398407873446,- bottom: 755.8565634247055,- },- },- {- id: "block_7_8RhsHH",- type: "text",- content:- "We trained on the standard WMT 2014 English-German dataset consisting of about 4.5 million sentence pairs. Sentences were encoded using byte-pair encoding [3], which has a shared source- target vocabulary of about 37000 tokens. For English-French, we used the significantly larger WMT 2014 English-French dataset consisting of 36M sentences and split tokens into a 32000 word-piece vocabulary [38]. Sentence pairs were batched together by approximate sequence length. Each training batch contained a set of sentence pairs containing approximately 25000 source tokens and 25000 target tokens.",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.911,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 223.70165247116648,- y: 778.8621643467953,- },- {- x: 1052.1871692072737,- y: 778.8621643467953,- },- {- x: 1052.1871692072737,- y: 935.23512009929,- },- {- x: 223.70165247116648,- y: 935.23512009929,- },- ],- boundingBox: {- left: 223.70165247116648,- top: 778.8621643467953,- right: 1052.1871692072737,- bottom: 935.23512009929,- },- },- {- id: "block_7_2fOgoW",- type: "section_heading",- content: "### 5.2 Hardware and Schedule",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.994,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 223.9209349138023,- y: 971.4598863071069,- },- {- x: 484.7486314982394,- y: 971.4598863071069,- },- {- x: 484.7486314982394,- y: 987.6652342143811,- },- {- x: 223.9209349138023,- y: 987.6652342143811,- },- ],- boundingBox: {- left: 223.9209349138023,- top: 971.4598863071069,- right: 484.7486314982394,- bottom: 987.6652342143811,- },- },- {- id: "block_7_7vykWe",- type: "text",- content:- "We trained our models on one machine with 8 NVIDIA P100 GPUs. For our base models using the hyperparameters described throughout the paper, each training step took about 0.4 seconds. We trained the base models for a total of 100,000 steps or 12 hours. For our big models,(described on the bottom line of table 3), step time was 1.0 seconds. The big models were trained for 300,000 steps (3.5 days).",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.961,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 223.2459757449853,- y: 1014.9955223485043,- },- {- x: 1049.3973947789548,- y: 1014.9955223485043,- },- {- x: 1049.3973947789548,- y: 1126.7015106660083,- },- {- x: 223.2459757449853,- y: 1126.7015106660083,- },- ],- boundingBox: {- left: 223.2459757449853,- top: 1014.9955223485043,- right: 1049.3973947789548,- bottom: 1126.7015106660083,- },- },- {- id: "block_7_Xjy6qb",- type: "section_heading",- content: "### 5.3 Optimizer",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.994,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 223.84361211400832,- y: 1161.1210525053784,- },- {- x: 361.9454223744191,- y: 1161.1210525053784,- },- {- x: 361.9454223744191,- y: 1181.9203891037102,- },- {- x: 223.84361211400832,- y: 1181.9203891037102,- },- ],- boundingBox: {- left: 223.84361211400832,- top: 1161.1210525053784,- right: 361.9454223744191,- bottom: 1181.9203891037102,- },- },- {- id: "block_7_uZS3FC",- type: "text",- content:- "We used the Adam optimizer [20] with 31 = 0.9, 32 = 0.98 and \u20ac = 10-9. We varied the learning rate over the course of training, according to the formula:",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.472,- avgOcrConfidence: 0.947,- },- polygon: [- {- x: 223.18536243299496,- y: 1203.7906809068263,- },- {- x: 1049.5936484232436,- y: 1203.7906809068263,- },- {- x: 1049.5936484232436,- y: 1249.0720648514596,- },- {- x: 223.18536243299496,- y: 1249.0720648514596,- },- ],- boundingBox: {- left: 223.18536243299496,- top: 1203.7906809068263,- right: 1049.5936484232436,- bottom: 1249.0720648514596,- },- },- {- id: "block_7_qvJczg",- type: "text",- content:- "lrate = dmodel . min(step_num-0.5, step_num . warmup_steps-1.5)",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Formula",- minOcrConfidence: 0.563,- avgOcrConfidence: 0.786,- },- polygon: [- {- x: 338.51696905428474,- y: 1286.921258338412,- },- {- x: 933.735361586522,- y: 1286.921258338412,- },- {- x: 933.735361586522,- y: 1314.0637410099346,- },- {- x: 338.51696905428474,- y: 1314.0637410099346,- },- ],- boundingBox: {- left: 338.51696905428474,- top: 1286.921258338412,- right: 933.735361586522,- bottom: 1314.0637410099346,- },- },- {- id: "block_7_ZRnl1T",- type: "text",- content: "(3)",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Caption",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.992,- },- polygon: [- {- x: 1026.6387883764114,- y: 1291.0368781986094,- },- {- x: 1051.2767151324417,- y: 1291.0368781986094,- },- {- x: 1051.2767151324417,- y: 1311.080825805664,- },- {- x: 1026.6387883764114,- y: 1311.080825805664,- },- ],- boundingBox: {- left: 1026.6387883764114,- top: 1291.0368781986094,- right: 1051.2767151324417,- bottom: 1311.080825805664,- },- },- {- id: "block_7_M71nL9",- type: "text",- content:- "This corresponds to increasing the learning rate linearly for the first warmup_steps training steps, and decreasing it thereafter proportionally to the inverse square root of the step number. We used warmup_steps = 4000.",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.916,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 222.72840764400732,- y: 1340.2761936044335,- },- {- x: 1052.0266066502481,- y: 1340.2761936044335,- },- {- x: 1052.0266066502481,- y: 1406.6737115616188,- },- {- x: 222.72840764400732,- y: 1406.6737115616188,- },- ],- boundingBox: {- left: 222.72840764400732,- top: 1340.2761936044335,- right: 1052.0266066502481,- bottom: 1406.6737115616188,- },- },- {- id: "block_7_ACakMa",- type: "section_heading",- content: "### 5.4 Regularization",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.993,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 223.81116351942077,- y: 1441.41800626597,- },- {- x: 402.1996435457773,- y: 1441.41800626597,- },- {- x: 402.1996435457773,- y: 1461.9926013803124,- },- {- x: 223.81116351942077,- y: 1461.9926013803124,- },- ],- boundingBox: {- left: 223.81116351942077,- top: 1441.41800626597,- right: 402.1996435457773,- bottom: 1461.9926013803124,- },- },- {- id: "block_7_rR8JeL",- type: "text",- content: "We employ three types of regularization during training:",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 222.88627206844134,- y: 1484.7892296583134,- },- {- x: 690.987449144795,- y: 1484.7892296583134,- },- {- x: 690.987449144795,- y: 1505.950728681751,- },- {- x: 222.88627206844134,- y: 1505.950728681751,- },- ],- boundingBox: {- left: 222.88627206844134,- top: 1484.7892296583134,- right: 690.987449144795,- bottom: 1505.950728681751,- },- },- {- id: "block_7_I7j7Uy",- type: "page_number",- content: "7",- metadata: {- page: {- number: 7,- width: 1275,- height: 1651,- },- layoutClass: "Page Number",- minOcrConfidence: 0.996,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 631.8865114755004,- y: 1547.4189893105872,- },- {- x: 642.4512153124288,- y: 1547.4189893105872,- },- {- x: 642.4512153124288,- y: 1562.541448836936,- },- {- x: 631.8865114755004,- y: 1562.541448836936,- },- ],- boundingBox: {- left: 631.8865114755004,- top: 1547.4189893105872,- right: 642.4512153124288,- bottom: 1562.541448836936,- },- },- ],- },- {- blocks: [- {- id: "block_8_8rtbBp",- type: "text",- content:- "Table 2: The Transformer achieves better BLEU scores than previous state-of-the-art models on the English-to-German and English-to-French newstest2014 tests at a fraction of the training cost.",- metadata: {- page: {- number: 8,- width: 1275,- height: 1651,- },- layoutClass: "Caption",- minOcrConfidence: 0.963,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 222.40285664579295,- y: 148.11078211418666,- },- {- x: 1048.695596291201,- y: 148.11078211418666,- },- {- x: 1048.695596291201,- y: 191.8824890538266,- },- {- x: 222.40285664579295,- y: 191.8824890538266,- },- ],- boundingBox: {- left: 222.40285664579295,- top: 148.11078211418666,- right: 1048.695596291201,- bottom: 191.8824890538266,- },- },- {- id: "block_8_M3V7h9",- type: "table",- content:- "| Model | BLEU | | Training Cost (FLOPs) | |\n| --- | --- | --- | --- | --- |\n| | EN-DE | EN-FR | EN-DE | EN-FR |\n| ByteNet [18] | 23.75 | | | |\n| Deep-Att + PosUnk [39] | | 39.2 | | 1.0 . 1020 |\n| GNMT + RL [38] | 24.6 | 39.92 | 2.3 . 1019 | 1.4 . 1020 |\n| ConvS2S [9] | 25.16 | 40.46 | 9.6 . 1018 | 1.5 . 1020 |\n| MoE [32] | 26.03 | 40.56 | 2.0 \u00b7 1019 | 1.2 . 1020 |\n| Deep-Att + PosUnk Ensemble [39] | | 40.4 | | 8.0 . 1020 |\n| GNMT + RL Ensemble [38] | 26.30 | 41.16 | 1.8 . 1020 | 1.1 . 1021 |\n| ConvS2S Ensemble [9] | 26.36 | 41.29 | 7.7 . 1019 | 1.2 . 1021 |\n| Transformer (base model) | 27.3 | 38.1 | 3.3 . | 1018 |\n| Transformer (big) | 28.4 | 41.8 | 2.3. 1019 | |",- metadata: {- page: {- number: 8,- width: 1275,- height: 1651,- },- layoutClass: "Table",- minOcrConfidence: 0.141,- avgOcrConfidence: 0.893,- },- polygon: [- {- x: 271.150136516042,- y: 195.3426247575229,- },- {- x: 1004.1704442379248,- y: 195.3426247575229,- },- {- x: 1004.1704442379248,- y: 508.6132290201976,- },- {- x: 271.150136516042,- y: 508.6132290201976,- },- ],- boundingBox: {- left: 271.150136516042,- top: 195.3426247575229,- right: 1004.1704442379248,- bottom: 508.6132290201976,- },- },- {- id: "block_8_Wl0xmI",- type: "text",- content:- "Residual Dropout We apply dropout [33] to the output of each sub-layer, before it is added to the sub-layer input and normalized. In addition, we apply dropout to the sums of the embeddings and the positional encodings in both the encoder and decoder stacks. For the base model, we use a rate of Pdrop =0.1.",- metadata: {- page: {- number: 8,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.893,- avgOcrConfidence: 0.992,- },- polygon: [- {- x: 223.9333605244212,- y: 569.1121117154458,- },- {- x: 1051.605887308608,- y: 569.1121117154458,- },- {- x: 1051.605887308608,- y: 660.0886577520155,- },- {- x: 223.9333605244212,- y: 660.0886577520155,- },- ],- boundingBox: {- left: 223.9333605244212,- top: 569.1121117154458,- right: 1051.605887308608,- bottom: 660.0886577520155,- },- },- {- id: "block_8_CtqTnb",- type: "text",- content:- "Label Smoothing During training, we employed label smoothing of value Els = 0.1 [36]. This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.",- metadata: {- page: {- number: 8,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.518,- avgOcrConfidence: 0.977,- },- polygon: [- {- x: 223.52019122047145,- y: 690.790115499855,- },- {- x: 1049.6801780088103,- y: 690.790115499855,- },- {- x: 1049.6801780088103,- y: 734.1354363233523,- },- {- x: 223.52019122047145,- y: 734.1354363233523,- },- ],- boundingBox: {- left: 223.52019122047145,- top: 690.790115499855,- right: 1049.6801780088103,- bottom: 734.1354363233523,- },- },- {- id: "block_8_KA1kZT",- type: "heading",- content: "# 6 Results",- metadata: {- page: {- number: 8,- width: 1275,- height: 1651,- },- layoutClass: "Heading",- minOcrConfidence: 0.995,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 224.16400352533717,- y: 774.585115131579,- },- {- x: 339.42863018843383,- y: 774.585115131579,- },- {- x: 339.42863018843383,- y: 793.809935433524,- },- {- x: 224.16400352533717,- y: 793.809935433524,- },- ],- boundingBox: {- left: 224.16400352533717,- top: 774.585115131579,- right: 339.42863018843383,- bottom: 793.809935433524,- },- },- {- id: "block_8_LYkEL8",- type: "section_heading",- content: "### 6.1 Machine Translation",- metadata: {- page: {- number: 8,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.994,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 224.2968510537252,- y: 828.3471990026029,- },- {- x: 455.2866330111984,- y: 828.3471990026029,- },- {- x: 455.2866330111984,- y: 844.3720339438072,- },- {- x: 224.2968510537252,- y: 844.3720339438072,- },- ],- boundingBox: {- left: 224.2968510537252,- top: 828.3471990026029,- right: 455.2866330111984,- bottom: 844.3720339438072,- },- },- {- id: "block_8_UnI1Ea",- type: "text",- content:- "On the WMT 2014 English-to-German translation task, the big transformer model (Transformer (big) in Table 2) outperforms the best previously reported models (including ensembles) by more than 2.0 BLEU, establishing a new state-of-the-art BLEU score of 28.4. The configuration of this model is listed in the bottom line of Table 3. Training took 3.5 days on 8 P100 GPUs. Even our base model surpasses all previously published models and ensembles, at a fraction of the training cost of any of the competitive models.",- metadata: {- page: {- number: 8,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.973,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 223.56291165317063,- y: 872.0711140453367,- },- {- x: 1050.5385628581919,- y: 872.0711140453367,- },- {- x: 1050.5385628581919,- y: 1006.0390107004266,- },- {- x: 223.56291165317063,- y: 1006.0390107004266,- },- ],- boundingBox: {- left: 223.56291165317063,- top: 872.0711140453367,- right: 1050.5385628581919,- bottom: 1006.0390107004266,- },- },- {- id: "block_8_pkBARc",- type: "text",- content:- "On the WMT 2014 English-to-French translation task, our big model achieves a BLEU score of 41.0, outperforming all of the previously published single models, at less than 1/4 the training cost of the previous state-of-the-art model. The Transformer (big) model trained for English-to-French used dropout rate Pdrop = 0.1, instead of 0.3.",- metadata: {- page: {- number: 8,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.945,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 224.05139199138557,- y: 1019.1086798072756,- },- {- x: 1052.2523977460653,- y: 1019.1086798072756,- },- {- x: 1052.2523977460653,- y: 1109.5784446888401,- },- {- x: 224.05139199138557,- y: 1109.5784446888401,- },- ],- boundingBox: {- left: 224.05139199138557,- top: 1019.1086798072756,- right: 1052.2523977460653,- bottom: 1109.5784446888401,- },- },- {- id: "block_8_vKs7Yg",- type: "text",- content:- "For the base models, we used a single model obtained by averaging the last 5 checkpoints, which were written at 10-minute intervals. For the big models, we averaged the last 20 checkpoints. We used beam search with a beam size of 4 and length penalty & = 0.6 [38]. These hyperparameters were chosen after experimentation on the development set. We set the maximum output length during inference to input length + 50, but terminate early when possible [38].",- metadata: {- page: {- number: 8,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.099,- avgOcrConfidence: 0.983,- },- polygon: [- {- x: 223.50279536560504,- y: 1122.2645474197273,- },- {- x: 1050.043905216412,- y: 1122.2645474197273,- },- {- x: 1050.043905216412,- y: 1233.5787297872673,- },- {- x: 223.50279536560504,- y: 1233.5787297872673,- },- ],- boundingBox: {- left: 223.50279536560504,- top: 1122.2645474197273,- right: 1050.043905216412,- bottom: 1233.5787297872673,- },- },- {- id: "block_8_42PSVl",- type: "text",- content:- "Table 2 summarizes our results and compares our translation quality and training costs to other model architectures from the literature. We estimate the number of floating point operations used to train a model by multiplying the training time, the number of GPUs used, and an estimate of the sustained single-precision floating-point capacity of each GPU 5.",- metadata: {- page: {- number: 8,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.975,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 222.3879459130503,- y: 1247.2785842436597,- },- {- x: 1049.63284234931,- y: 1247.2785842436597,- },- {- x: 1049.63284234931,- y: 1336.1913537620603,- },- {- x: 222.3879459130503,- y: 1336.1913537620603,- },- ],- boundingBox: {- left: 222.3879459130503,- top: 1247.2785842436597,- right: 1049.63284234931,- bottom: 1336.1913537620603,- },- },- {- id: "block_8_pDx0nB",- type: "section_heading",- content: "### 6.2 Model Variations",- metadata: {- page: {- number: 8,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 224.05955739264942,- y: 1370.9984397027727,- },- {- x: 424.93188398597886,- y: 1370.9984397027727,- },- {- x: 424.93188398597886,- y: 1387.4261614003576,- },- {- x: 224.05955739264942,- y: 1387.4261614003576,- },- ],- boundingBox: {- left: 224.05955739264942,- top: 1370.9984397027727,- right: 424.93188398597886,- bottom: 1387.4261614003576,- },- },- {- id: "block_8_XCLvsN",- type: "text",- content:- "To evaluate the importance of different components of the Transformer, we varied our base model in different ways, measuring the change in performance on English-to-German translation on the",- metadata: {- page: {- number: 8,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 222.6526705888066,- y: 1413.835037862448,- },- {- x: 1049.9819901737853,- y: 1413.835037862448,- },- {- x: 1049.9819901737853,- y: 1458.0598621798638,- },- {- x: 222.6526705888066,- y: 1458.0598621798638,- },- ],- boundingBox: {- left: 222.6526705888066,- top: 1413.835037862448,- right: 1049.9819901737853,- bottom: 1458.0598621798638,- },- },- {- id: "block_8_6e9VRc",- type: "text",- content:- "5We used values of 2.8, 3.7, 6.0 and 9.5 TFLOPS for K80, K40, M40 and P100, respectively.",- metadata: {- page: {- number: 8,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.976,- avgOcrConfidence: 0.992,- },- polygon: [- {- x: 249.0640041601919,- y: 1482.8447849015545,- },- {- x: 944.2274051861172,- y: 1482.8447849015545,- },- {- x: 944.2274051861172,- y: 1505.4603319670025,- },- {- x: 249.0640041601919,- y: 1505.4603319670025,- },- ],- boundingBox: {- left: 249.0640041601919,- top: 1482.8447849015545,- right: 944.2274051861172,- bottom: 1505.4603319670025,- },- },- {- id: "block_8_HHxEh9",- type: "page_number",- content: "8",- metadata: {- page: {- number: 8,- width: 1275,- height: 1651,- },- layoutClass: "Page Number",- minOcrConfidence: 0.996,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 631.7743259624843,- y: 1547.954182789738,- },- {- x: 642.6607229413778,- y: 1547.954182789738,- },- {- x: 642.6607229413778,- y: 1563.2957013352473,- },- {- x: 631.7743259624843,- y: 1563.2957013352473,- },- ],- boundingBox: {- left: 631.7743259624843,- top: 1547.954182789738,- right: 642.6607229413778,- bottom: 1563.2957013352473,- },- },- ],- },- {- blocks: [- {- id: "block_9_2CG18E",- type: "text",- content:- "Table 3: Variations on the Transformer architecture. Unlisted values are identical to those of the base model. All metrics are on the English-to-German translation development set, newstest2013. Listed perplexities are per-wordpiece, according to our byte-pair encoding, and should not be compared to per-word perplexities.",- metadata: {- page: {- number: 9,- width: 1275,- height: 1651,- },- layoutClass: "Caption",- minOcrConfidence: 0.99,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 222.6654748847015,- y: 147.86792777355453,- },- {- x: 1049.6700481776775,- y: 147.86792777355453,- },- {- x: 1049.6700481776775,- y: 237.19010704442076,- },- {- x: 222.6654748847015,- y: 237.19010704442076,- },- ],- boundingBox: {- left: 222.6654748847015,- top: 147.86792777355453,- right: 1049.6700481776775,- bottom: 237.19010704442076,- },- },- {- id: "block_9_0WToWH",- type: "table",- content:- "| | N | dmodel | dff | h | dk | dv | Pdrop | Els | train steps | PPL (dev) | BLEU (dev) | params \u00d7106 |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| base | 6 | 512 | 2048 | 8 | 64 | 64 | 0.1 | 0.1 | 100K | 4.92 | 25.8 | 65 |\n| (A) | | | | 1 | 512 | 512 | | | | 5.29 | 24.9 | |\n| | | | | 4 | 128 | 128 | | | | 5.00 | 25.5 | |\n| | | | | 16 | 32 | 32 | | | | 4.91 | 25.8 | |\n| | | | | 32 | 16 | 16 | | | | 5.01 | 25.4 | |\n| (B) | | | | | 16 | | | | | 5.16 | 25.1 | 58 |\n| | | | | | 32 | | | | | 5.01 | 25.4 | 60 |\n| (C) | 2 | | | | | | | | | 6.11 | 23.7 | 36 |\n| | 4 | | | | | | | | | 5.19 | 25.3 | 50 |\n| | 8 | | | | | | | | | 4.88 | 25.5 | 80 |\n| | | 256 | | | 32 | 32 | | | | 5.75 | 24.5 | 28 |\n| | | 1024 | | | 128 | 128 | | | | 4.66 | 26.0 | 168 |\n| | | | 1024 | | | | | | | 5.12 | 25.4 | 53 |\n| | | | 4096 | | | | | | | 4.75 | 26.2 | 90 |\n| (D) | | | | | | | 0.0 | | | 5.77 | 24.6 | |\n| | | | | | | | 0.2 | | | 4.95 | 25.5 | |\n| | | | | | | | | 0.0 | | 4.67 | 25.3 | |\n| | | | | | | | | 0.2 | | 5.47 | 25.7 | |\n| (E) | positional embedding | | | | | instead of | sinusoids | | | 4.92 | 25.7 | |\n| big | 6 | 1024 | 4096 | 16 | | | 0.3 | | 300K | 4.33 | 26.4 | 213 |",- metadata: {- page: {- number: 9,- width: 1275,- height: 1651,- },- layoutClass: "Table",- minOcrConfidence: 0.612,- avgOcrConfidence: 0.986,- },- polygon: [- {- x: 224.84461930546448,- y: 268.65403318763674,- },- {- x: 1060.6742636130673,- y: 268.65403318763674,- },- {- x: 1060.6742636130673,- y: 801.2216690178204,- },- {- x: 224.84461930546448,- y: 801.2216690178204,- },- ],- boundingBox: {- left: 224.84461930546448,- top: 268.65403318763674,- right: 1060.6742636130673,- bottom: 801.2216690178204,- },- },- {- id: "block_9_p8WB9c",- type: "text",- content:- "development set, newstest2013. We used beam search as described in the previous section, but no checkpoint averaging. We present these results in Table 3.",- metadata: {- page: {- number: 9,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.989,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 224.42882287241247,- y: 862.6040329323675,- },- {- x: 1049.5265264580719,- y: 862.6040329323675,- },- {- x: 1049.5265264580719,- y: 905.6541023541213,- },- {- x: 224.42882287241247,- y: 905.6541023541213,- },- ],- boundingBox: {- left: 224.42882287241247,- top: 862.6040329323675,- right: 1049.5265264580719,- bottom: 905.6541023541213,- },- },- {- id: "block_9_XvsIA2",- type: "text",- content:- "In Table 3 rows (A), we vary the number of attention heads and the attention key and value dimensions, keeping the amount of computation constant, as described in Section 3.2.2. While single-head attention is 0.9 BLEU worse than the best setting, quality also drops off with too many heads.",- metadata: {- page: {- number: 9,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.967,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 224.23600106343736,- y: 918.8913094656807,- },- {- x: 1052.034559041044,- y: 918.8913094656807,- },- {- x: 1052.034559041044,- y: 986.1080494357232,- },- {- x: 224.23600106343736,- y: 986.1080494357232,- },- ],- boundingBox: {- left: 224.23600106343736,- top: 918.8913094656807,- right: 1052.034559041044,- bottom: 986.1080494357232,- },- },- {- id: "block_9_lFHLbG",- type: "text",- content:- "In Table 3 rows (B), we observe that reducing the attention key size dk hurts model quality. This suggests that determining compatibility is not easy and that a more sophisticated compatibility function than dot product may be beneficial. We further observe in rows (C) and (D) that, as expected, bigger models are better, and dropout is very helpful in avoiding over-fitting. In row (E) we replace our sinusoidal positional encoding with learned positional embeddings [9], and observe nearly identical results to the base model.",- metadata: {- page: {- number: 9,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.881,- avgOcrConfidence: 0.992,- },- polygon: [- {- x: 224.0262804240206,- y: 998.9746651326803,- },- {- x: 1052.338643317675,- y: 998.9746651326803,- },- {- x: 1052.338643317675,- y: 1130.1984048140678,- },- {- x: 224.0262804240206,- y: 1130.1984048140678,- },- ],- boundingBox: {- left: 224.0262804240206,- top: 998.9746651326803,- right: 1052.338643317675,- bottom: 1130.1984048140678,- },- },- {- id: "block_9_nnE2Kn",- type: "section_heading",- content: "### 6.3 English Constituency Parsing",- metadata: {- page: {- number: 9,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.994,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 224.00199723069687,- y: 1168.0604785546325,- },- {- x: 533.1579584274849,- y: 1168.0604785546325,- },- {- x: 533.1579584274849,- y: 1188.5333575485345,- },- {- x: 224.00199723069687,- y: 1188.5333575485345,- },- ],- boundingBox: {- left: 224.00199723069687,- top: 1168.0604785546325,- right: 533.1579584274849,- bottom: 1188.5333575485345,- },- },- {- id: "block_9_UvLm1J",- type: "text",- content:- "To evaluate if the Transformer can generalize to other tasks we performed experiments on English constituency parsing. This task presents specific challenges: the output is subject to strong structural constraints and is significantly longer than the input. Furthermore, RNN sequence-to-sequence models have not been able to attain state-of-the-art results in small-data regimes [37].",- metadata: {- page: {- number: 9,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.963,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 223.0787388599702,- y: 1212.099580979885,- },- {- x: 1049.9080518736457,- y: 1212.099580979885,- },- {- x: 1049.9080518736457,- y: 1300.6617424183323,- },- {- x: 223.0787388599702,- y: 1300.6617424183323,- },- ],- boundingBox: {- left: 223.0787388599702,- top: 1212.099580979885,- right: 1049.9080518736457,- bottom: 1300.6617424183323,- },- },- {- id: "block_9_nmNLPf",- type: "text",- content:- "We trained a 4-layer transformer with dmodel = 1024 on the Wall Street Journal (WSJ) portion of the Penn Treebank [25], about 40K training sentences. We also trained it in a semi-supervised setting, using the larger high-confidence and BerkleyParser corpora from with approximately 17M sentences [37]. We used a vocabulary of 16K tokens for the WSJ only setting and a vocabulary of 32K tokens for the semi-supervised setting.",- metadata: {- page: {- number: 9,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.913,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 223.08401678600453,- y: 1314.1105266370273,- },- {- x: 1051.1732393807738,- y: 1314.1105266370273,- },- {- x: 1051.1732393807738,- y: 1425.9921031177494,- },- {- x: 223.08401678600453,- y: 1425.9921031177494,- },- ],- boundingBox: {- left: 223.08401678600453,- top: 1314.1105266370273,- right: 1051.1732393807738,- bottom: 1425.9921031177494,- },- },- {- id: "block_9_kQhH3x",- type: "text",- content:- "We performed only a small number of experiments to select the dropout, both attention and residual (section 5.4), learning rates and beam size on the Section 22 development set, all other parameters remained unchanged from the English-to-German base translation model. During inference, we",- metadata: {- page: {- number: 9,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 223.1762739863709,- y: 1439.0945411051127,- },- {- x: 1050.7557388639798,- y: 1439.0945411051127,- },- {- x: 1050.7557388639798,- y: 1505.8386894168711,- },- {- x: 223.1762739863709,- y: 1505.8386894168711,- },- ],- boundingBox: {- left: 223.1762739863709,- top: 1439.0945411051127,- right: 1050.7557388639798,- bottom: 1505.8386894168711,- },- },- {- id: "block_9_C4QuNg",- type: "page_number",- content: "9",- metadata: {- page: {- number: 9,- width: 1275,- height: 1651,- },- layoutClass: "Page Number",- minOcrConfidence: 0.993,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 631.6446262554531,- y: 1547.2787271370566,- },- {- x: 642.3550765879834,- y: 1547.2787271370566,- },- {- x: 642.3550765879834,- y: 1562.906831325445,- },- {- x: 631.6446262554531,- y: 1562.906831325445,- },- ],- boundingBox: {- left: 631.6446262554531,- top: 1547.2787271370566,- right: 642.3550765879834,- bottom: 1562.906831325445,- },- },- ],- },- {- blocks: [- {- id: "block_10_Whfo1k",- type: "text",- content:- "Table 4: The Transformer generalizes well to English constituency parsing (Results are on Section 23 of WSJ)",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "Caption",- minOcrConfidence: 0.988,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 222.60232911492787,- y: 147.913837353986,- },- {- x: 1049.0453121435903,- y: 147.913837353986,- },- {- x: 1049.0453121435903,- y: 190.50408882485297,- },- {- x: 222.60232911492787,- y: 190.50408882485297,- },- ],- boundingBox: {- left: 222.60232911492787,- top: 147.913837353986,- right: 1049.0453121435903,- bottom: 190.50408882485297,- },- },- {- id: "block_10_Oq0boE",- type: "table",- content:- "| Parser | Training | WSJ 23 F1 |\n| --- | --- | --- |\n| Vinyals & Kaiser el al. (2014) [37] | WSJ only, discriminative | 88.3 |\n| Petrov et al. (2006) [29] | WSJ only, discriminative | 90.4 |\n| Zhu et al. (2013) [40] | WSJ only, discriminative | 90.4 |\n| Dyer et al. (2016) [8] | WSJ only, discriminative | 91.7 |\n| Transformer (4 layers) | WSJ only, discriminative | 91.3 |\n| Zhu et al. (2013) [40] | semi-supervised | 91.3 |\n| Huang & Harper (2009) [14] | semi-supervised | 91.3 |\n| McClosky et al. (2006) [26] | semi-supervised | 92.1 |\n| Vinyals & Kaiser el al. (2014) [37] | semi-supervised | 92.1 |\n| Transformer (4 layers) | semi-supervised | 92.7 |\n| Luong et al. (2015) [23] | multi-task | 93.0 |\n| Dyer et al. (2016) [8] | generative | 93.3 |",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "Table",- minOcrConfidence: 0.926,- avgOcrConfidence: 0.99,- },- polygon: [- {- x: 300.48226962124346,- y: 193.81453893417702,- },- {- x: 974.1206315312072,- y: 193.81453893417702,- },- {- x: 974.1206315312072,- y: 493.68785631567016,- },- {- x: 300.48226962124346,- y: 493.68785631567016,- },- ],- boundingBox: {- left: 300.48226962124346,- top: 193.81453893417702,- right: 974.1206315312072,- bottom: 493.68785631567016,- },- },- {- id: "block_10_wSUPzw",- type: "text",- content:- "increased the maximum output length to input length + 300. We used a beam size of 21 and & = 0.3 for both WSJ only and the semi-supervised setting.",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.117,- avgOcrConfidence: 0.964,- },- polygon: [- {- x: 223.84354111051908,- y: 546.3992524398001,- },- {- x: 1049.2353174808252,- y: 546.3992524398001,- },- {- x: 1049.2353174808252,- y: 589.787902057619,- },- {- x: 223.84354111051908,- y: 589.787902057619,- },- ],- boundingBox: {- left: 223.84354111051908,- top: 546.3992524398001,- right: 1049.2353174808252,- bottom: 589.787902057619,- },- },- {- id: "block_10_KdYXbX",- type: "text",- content:- "Our results in Table 4 show that despite the lack of task-specific tuning our model performs sur- prisingly well, yielding better results than all previously reported models with the exception of the Recurrent Neural Network Grammar [8].",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.917,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 224.34470740548016,- y: 603.5821801379211,- },- {- x: 1052.1757139776746,- y: 603.5821801379211,- },- {- x: 1052.1757139776746,- y: 667.7562916691143,- },- {- x: 224.34470740548016,- y: 667.7562916691143,- },- ],- boundingBox: {- left: 224.34470740548016,- top: 603.5821801379211,- right: 1052.1757139776746,- bottom: 667.7562916691143,- },- },- {- id: "block_10_spL6f1",- type: "text",- content:- "In contrast to RNN sequence-to-sequence models [37], the Transformer outperforms the Berkeley- Parser [29] even when training only on the WSJ training set of 40K sentences.",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.907,- avgOcrConfidence: 0.99,- },- polygon: [- {- x: 223.93137242672216,- y: 683.4819921909419,- },- {- x: 1052.021589070341,- y: 683.4819921909419,- },- {- x: 1052.021589070341,- y: 725.8283830513632,- },- {- x: 223.93137242672216,- y: 725.8283830513632,- },- ],- boundingBox: {- left: 223.93137242672216,- top: 683.4819921909419,- right: 1052.021589070341,- bottom: 725.8283830513632,- },- },- {- id: "block_10_FpxS4M",- type: "section_heading",- content: "### 7 Conclusion",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.993,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 223.87968188654767,- y: 760.911873552136,- },- {- x: 380.37754949862074,- y: 760.911873552136,- },- {- x: 380.37754949862074,- y: 780.8896204439321,- },- {- x: 223.87968188654767,- y: 780.8896204439321,- },- ],- boundingBox: {- left: 223.87968188654767,- top: 760.911873552136,- right: 380.37754949862074,- bottom: 780.8896204439321,- },- },- {- id: "block_10_06Cxhy",- type: "text",- content:- "In this work, we presented the Transformer, the first sequence transduction model based entirely on attention, replacing the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention.",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.989,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 223.7800876589587,- y: 811.1846398948727,- },- {- x: 1049.4503160462762,- y: 811.1846398948727,- },- {- x: 1049.4503160462762,- y: 872.951422555106,- },- {- x: 223.7800876589587,- y: 872.951422555106,- },- ],- boundingBox: {- left: 223.7800876589587,- top: 811.1846398948727,- right: 1049.4503160462762,- bottom: 872.951422555106,- },- },- {- id: "block_10_4PqBx5",- type: "text",- content:- "For translation tasks, the Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers. On both WMT 2014 English-to-German and WMT 2014 English-to-French translation tasks, we achieve a new state of the art. In the former task our best model outperforms even all previously reported ensembles.",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.989,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 223.91187013500797,- y: 890.9364237390963,- },- {- x: 1049.8108244290318,- y: 890.9364237390963,- },- {- x: 1049.8108244290318,- y: 980.2941302536126,- },- {- x: 223.91187013500797,- y: 980.2941302536126,- },- ],- boundingBox: {- left: 223.91187013500797,- top: 890.9364237390963,- right: 1049.8108244290318,- bottom: 980.2941302536126,- },- },- {- id: "block_10_9Aa2OZ",- type: "text",- content:- "We are excited about the future of attention-based models and plan to apply them to other tasks. We plan to extend the Transformer to problems involving input and output modalities other than text and to investigate local, restricted attention mechanisms to efficiently handle large inputs and outputs such as images, audio and video. Making generation less sequential is another research goals of ours.",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.985,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 223.4691397117002,- y: 993.4156992059005,- },- {- x: 1051.09778633953,- y: 993.4156992059005,- },- {- x: 1051.09778633953,- y: 1081.8706514745727,- },- {- x: 223.4691397117002,- y: 1081.8706514745727,- },- ],- boundingBox: {- left: 223.4691397117002,- top: 993.4156992059005,- right: 1051.09778633953,- bottom: 1081.8706514745727,- },- },- {- id: "block_10_eXUU9v",- type: "text",- content:- "The code we used to train and evaluate our models is available at https://github.com/ tensorflow/tensor2tensor.",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.94,- avgOcrConfidence: 0.99,- },- polygon: [- {- x: 222.4288912585182,- y: 1095.2490678371344,- },- {- x: 1050.6089983195284,- y: 1095.2490678371344,- },- {- x: 1050.6089983195284,- y: 1136.225321719521,- },- {- x: 222.4288912585182,- y: 1136.225321719521,- },- ],- boundingBox: {- left: 222.4288912585182,- top: 1095.2490678371344,- right: 1050.6089983195284,- bottom: 1136.225321719521,- },- },- {- id: "block_10_HbnFiy",- type: "text",- content:- "Acknowledgements We are grateful to Nal Kalchbrenner and Stephan Gouws for their fruitful comments, corrections and inspiration.",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "Text",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.996,- },- polygon: [- {- x: 223.74068072242457,- y: 1165.530171673997,- },- {- x: 1049.9162882783987,- y: 1165.530171673997,- },- {- x: 1049.9162882783987,- y: 1209.6124608319503,- },- {- x: 223.74068072242457,- y: 1209.6124608319503,- },- ],- boundingBox: {- left: 223.74068072242457,- top: 1165.530171673997,- right: 1049.9162882783987,- bottom: 1209.6124608319503,- },- },- {- id: "block_10_FqHFgA",- type: "section_heading",- content: "### References",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "Subheading",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.992,- },- polygon: [- {- x: 224.3401158465086,- y: 1243.4205694557131,- },- {- x: 340.41243086766156,- y: 1243.4205694557131,- },- {- x: 340.41243086766156,- y: 1263.1433630921786,- },- {- x: 224.3401158465086,- y: 1263.1433630921786,- },- ],- boundingBox: {- left: 224.3401158465086,- top: 1243.4205694557131,- right: 340.41243086766156,- bottom: 1263.1433630921786,- },- },- {- id: "block_10_PnBCYC",- type: "text",- content:- "[1] Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint arXiv: 1607.06450, 2016.",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.913,- avgOcrConfidence: 0.988,- },- polygon: [- {- x: 234.62492392881074,- y: 1281.5349446346884,- },- {- x: 1049.520940850251,- y: 1281.5349446346884,- },- {- x: 1049.520940850251,- y: 1323.6168167573169,- },- {- x: 234.62492392881074,- y: 1323.6168167573169,- },- ],- boundingBox: {- left: 234.62492392881074,- top: 1281.5349446346884,- right: 1049.520940850251,- bottom: 1323.6168167573169,- },- },- {- id: "block_10_sUAYRJ",- type: "text",- content:- "[2] Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly learning to align and translate. CoRR, abs/1409.0473, 2014.",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.913,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 233.7351792050104,- y: 1342.1247941210754,- },- {- x: 1048.5688313950586,- y: 1342.1247941210754,- },- {- x: 1048.5688313950586,- y: 1385.6842018070079,- },- {- x: 233.7351792050104,- y: 1385.6842018070079,- },- ],- boundingBox: {- left: 233.7351792050104,- top: 1342.1247941210754,- right: 1048.5688313950586,- bottom: 1385.6842018070079,- },- },- {- id: "block_10_cYNyCb",- type: "text",- content:- "[3] Denny Britz, Anna Goldie, Minh-Thang Luong, and Quoc V. Le. Massive exploration of neural machine translation architectures. CoRR, abs/1703.03906, 2017.",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.914,- avgOcrConfidence: 0.989,- },- polygon: [- {- x: 234.47555625525703,- y: 1401.96474766552,- },- {- x: 1050.0915248898693,- y: 1401.96474766552,- },- {- x: 1050.0915248898693,- y: 1443.4021335687853,- },- {- x: 234.47555625525703,- y: 1443.4021335687853,- },- ],- boundingBox: {- left: 234.47555625525703,- top: 1401.96474766552,- right: 1050.0915248898693,- bottom: 1443.4021335687853,- },- },- {- id: "block_10_akeHB3",- type: "text",- content:- "[4] Jianpeng Cheng, Li Dong, and Mirella Lapata. Long short-term memory-networks for machine reading. arXiv preprint arXiv: 1601.06733, 2016.",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.91,- avgOcrConfidence: 0.989,- },- polygon: [- {- x: 235.1935672063897,- y: 1461.8473196961825,- },- {- x: 1049.3358584216041,- y: 1461.8473196961825,- },- {- x: 1049.3358584216041,- y: 1505.7106445427228,- },- {- x: 235.1935672063897,- y: 1505.7106445427228,- },- ],- boundingBox: {- left: 235.1935672063897,- top: 1461.8473196961825,- right: 1049.3358584216041,- bottom: 1505.7106445427228,- },- },- {- id: "block_10_sJYSgt",- type: "page_number",- content: "10",- metadata: {- page: {- number: 10,- width: 1275,- height: 1651,- },- layoutClass: "Page Number",- minOcrConfidence: 0.999,- avgOcrConfidence: 0.999,- },- polygon: [- {- x: 628.4902252420022,- y: 1547.7831405983832,- },- {- x: 647.7796484954166,- y: 1547.7831405983832,- },- {- x: 647.7796484954166,- y: 1563.3856736950409,- },- {- x: 628.4902252420022,- y: 1563.3856736950409,- },- ],- boundingBox: {- left: 628.4902252420022,- top: 1547.7831405983832,- right: 647.7796484954166,- bottom: 1563.3856736950409,- },- },- ],- },- {- blocks: [- {- id: "block_11_VBbBwR",- type: "text",- content:- "[5] Kyunghyun Cho, Bart van Merrienboer, Caglar Gulcehre, Fethi Bougares, Holger Schwenk, and Yoshua Bengio. Learning phrase representations using rnn encoder-decoder for statistical machine translation. CoRR, abs/1406.1078, 2014.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.932,- avgOcrConfidence: 0.992,- },- polygon: [- {- x: 234.95565818174043,- y: 155.04768656967278,- },- {- x: 1051.617910566121,- y: 155.04768656967278,- },- {- x: 1051.617910566121,- y: 219.22101676195186,- },- {- x: 234.95565818174043,- y: 219.22101676195186,- },- ],- boundingBox: {- left: 234.95565818174043,- top: 155.04768656967278,- right: 1051.617910566121,- bottom: 219.22101676195186,- },- },- {- id: "block_11_fZULb0",- type: "text",- content:- "[6] Francois Chollet. Xception: Deep learning with depthwise separable convolutions. arXiv preprint arXiv: 1610.02357, 2016.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.916,- avgOcrConfidence: 0.987,- },- polygon: [- {- x: 234.37082610861228,- y: 242.1581676597882,- },- {- x: 1050.1136779785156,- y: 242.1581676597882,- },- {- x: 1050.1136779785156,- y: 284.96119192309845,- },- {- x: 234.37082610861228,- y: 284.96119192309845,- },- ],- boundingBox: {- left: 234.37082610861228,- top: 242.1581676597882,- right: 1050.1136779785156,- bottom: 284.96119192309845,- },- },- {- id: "block_11_KQxaZG",- type: "text",- content:- "[7] Junyoung Chung, \u00c7aglar G\u00fcl\u00e7ehre, Kyunghyun Cho, and Yoshua Bengio. Empirical evaluation of gated recurrent neural networks on sequence modeling. CoRR, abs/1412.3555, 2014.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.937,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 234.59709056102446,- y: 305.8525607747243,- },- {- x: 1050.252182118214,- y: 305.8525607747243,- },- {- x: 1050.252182118214,- y: 348.70033444856347,- },- {- x: 234.59709056102446,- y: 348.70033444856347,- },- ],- boundingBox: {- left: 234.59709056102446,- top: 305.8525607747243,- right: 1050.252182118214,- bottom: 348.70033444856347,- },- },- {- id: "block_11_lSxX1m",- type: "text",- content:- "[8] Chris Dyer, Adhiguna Kuncoro, Miguel Ballesteros, and Noah A. Smith. Recurrent neural network grammars. In Proc. of NAACL, 2016.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.92,- avgOcrConfidence: 0.99,- },- polygon: [- {- x: 234.54393261540545,- y: 369.88837531814,- },- {- x: 1049.7648141679972,- y: 369.88837531814,- },- {- x: 1049.7648141679972,- y: 412.63161531606113,- },- {- x: 234.54393261540545,- y: 412.63161531606113,- },- ],- boundingBox: {- left: 234.54393261540545,- top: 369.88837531814,- right: 1049.7648141679972,- bottom: 412.63161531606113,- },- },- {- id: "block_11_3YLXoz",- type: "text",- content:- "[9] Jonas Gehring, Michael Auli, David Grangier, Denis Yarats, and Yann N. Dauphin. Convolu- tional sequence to sequence learning. arXiv preprint arXiv: 1705.03122v2, 2017.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.927,- avgOcrConfidence: 0.989,- },- polygon: [- {- x: 233.81299902922916,- y: 434.3302966813395,- },- {- x: 1052.8067929901345,- y: 434.3302966813395,- },- {- x: 1052.8067929901345,- y: 476.945989020785,- },- {- x: 233.81299902922916,- y: 476.945989020785,- },- ],- boundingBox: {- left: 233.81299902922916,- top: 434.3302966813395,- right: 1052.8067929901345,- bottom: 476.945989020785,- },- },- {- id: "block_11_OkxRaO",- type: "text",- content:- "[10] Alex Graves. Generating sequences with recurrent neural networks. arXiv preprint arXiv: 1308.0850, 2013.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.904,- avgOcrConfidence: 0.986,- },- polygon: [- {- x: 224.38643378932983,- y: 498.1091927836712,- },- {- x: 1050.5877919440723,- y: 498.1091927836712,- },- {- x: 1050.5877919440723,- y: 539.0395607625632,- },- {- x: 224.38643378932983,- y: 539.0395607625632,- },- ],- boundingBox: {- left: 224.38643378932983,- top: 498.1091927836712,- right: 1050.5877919440723,- bottom: 539.0395607625632,- },- },- {- id: "block_11_RVnHcs",- type: "text",- content:- "[11] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for im- age recognition. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 770-778, 2016.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.919,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 224.3475475450502,- y: 561.9494121522832,- },- {- x: 1053.1976908662893,- y: 561.9494121522832,- },- {- x: 1053.1976908662893,- y: 627.2271530610278,- },- {- x: 224.3475475450502,- y: 627.2271530610278,- },- ],- boundingBox: {- left: 224.3475475450502,- top: 561.9494121522832,- right: 1053.1976908662893,- bottom: 627.2271530610278,- },- },- {- id: "block_11_s96TQd",- type: "text",- content:- "[12] Sepp Hochreiter, Yoshua Bengio, Paolo Frasconi, and J\u00fcrgen Schmidhuber. Gradient flow in recurrent nets: the difficulty of learning long-term dependencies, 2001.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.892,- avgOcrConfidence: 0.989,- },- polygon: [- {- x: 224.27874516396628,- y: 647.9830188034173,- },- {- x: 1048.8635432111087,- y: 647.9830188034173,- },- {- x: 1048.8635432111087,- y: 692.1669293740639,- },- {- x: 224.27874516396628,- y: 692.1669293740639,- },- ],- boundingBox: {- left: 224.27874516396628,- top: 647.9830188034173,- right: 1048.8635432111087,- bottom: 692.1669293740639,- },- },- {- id: "block_11_bKrlBK",- type: "text",- content:- "[13] Sepp Hochreiter and J\u00fcrgen Schmidhuber. Long short-term memory. Neural computation, 9(8):1735-1780, 1997.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.903,- avgOcrConfidence: 0.984,- },- polygon: [- {- x: 224.36335765532334,- y: 712.3709330738038,- },- {- x: 1051.7104044447851,- y: 712.3709330738038,- },- {- x: 1051.7104044447851,- y: 754.2910917181719,- },- {- x: 224.36335765532334,- y: 754.2910917181719,- },- ],- boundingBox: {- left: 224.36335765532334,- top: 712.3709330738038,- right: 1051.7104044447851,- bottom: 754.2910917181719,- },- },- {- id: "block_11_c3sQ7S",- type: "text",- content:- "[14] Zhongqiang Huang and Mary Harper. Self-training PCFG grammars with latent annotations across languages. In Proceedings of the 2009 Conference on Empirical Methods in Natural Language Processing, pages 832-841. ACL, August 2009.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.908,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 224.70277800177138,- y: 777.0990849258308,- },- {- x: 1050.1772024335653,- y: 777.0990849258308,- },- {- x: 1050.1772024335653,- y: 842.7015786995565,- },- {- x: 224.70277800177138,- y: 842.7015786995565,- },- ],- boundingBox: {- left: 224.70277800177138,- top: 777.0990849258308,- right: 1050.1772024335653,- bottom: 842.7015786995565,- },- },- {- id: "block_11_HmSxMA",- type: "text",- content:- "[15] Rafal Jozefowicz, Oriol Vinyals, Mike Schuster, Noam Shazeer, and Yonghui Wu. Exploring the limits of language modeling. arXiv preprint arXiv: 1602.02410, 2016.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.906,- avgOcrConfidence: 0.989,- },- polygon: [- {- x: 223.96287430811972,- y: 863.015632801486,- },- {- x: 1049.822942357864,- y: 863.015632801486,- },- {- x: 1049.822942357864,- y: 907.0369301702743,- },- {- x: 223.96287430811972,- y: 907.0369301702743,- },- ],- boundingBox: {- left: 223.96287430811972,- top: 863.015632801486,- right: 1049.822942357864,- bottom: 907.0369301702743,- },- },- {- id: "block_11_XlCObz",- type: "text",- content:- "[16] \u0141ukasz Kaiser and Samy Bengio. Can active memory replace attention? In Advances in Neural Information Processing Systems, (NIPS), 2016.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.902,- avgOcrConfidence: 0.988,- },- polygon: [- {- x: 224.17545875493627,- y: 927.1137413655905,- },- {- x: 1050.2528448174469,- y: 927.1137413655905,- },- {- x: 1050.2528448174469,- y: 970.5487977795134,- },- {- x: 224.17545875493627,- y: 970.5487977795134,- },- ],- boundingBox: {- left: 224.17545875493627,- top: 927.1137413655905,- right: 1050.2528448174469,- bottom: 970.5487977795134,- },- },- {- id: "block_11_48mMcn",- type: "text",- content:- "[17] \u0141ukasz Kaiser and Ilya Sutskever. Neural GPUs learn algorithms. In International Conference on Learning Representations (ICLR), 2016.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.903,- avgOcrConfidence: 0.987,- },- polygon: [- {- x: 224.42198286961465,- y: 991.1752927392946,- },- {- x: 1049.7810976348653,- y: 991.1752927392946,- },- {- x: 1049.7810976348653,- y: 1034.8329123590227,- },- {- x: 224.42198286961465,- y: 1034.8329123590227,- },- ],- boundingBox: {- left: 224.42198286961465,- top: 991.1752927392946,- right: 1049.7810976348653,- bottom: 1034.8329123590227,- },- },- {- id: "block_11_lBImir",- type: "text",- content:- "[18] Nal Kalchbrenner, Lasse Espeholt, Karen Simonyan, Aaron van den Oord, Alex Graves, and Ko- ray Kavukcuoglu. Neural machine translation in linear time. arXiv preprint arXiv: 1610.10099v2, 2017.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.934,- avgOcrConfidence: 0.988,- },- polygon: [- {- x: 224.23202486803933,- y: 1055.1385374714557,- },- {- x: 1052.4190192675069,- y: 1055.1385374714557,- },- {- x: 1052.4190192675069,- y: 1117.975328259002,- },- {- x: 224.23202486803933,- y: 1117.975328259002,- },- ],- boundingBox: {- left: 224.23202486803933,- top: 1055.1385374714557,- right: 1052.4190192675069,- bottom: 1117.975328259002,- },- },- {- id: "block_11_Y0ddKF",- type: "text",- content:- "[19] Yoon Kim, Carl Denton, Luong Hoang, and Alexander M. Rush. Structured attention networks. In International Conference on Learning Representations, 2017.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.974,- avgOcrConfidence: 0.992,- },- polygon: [- {- x: 224.29036606837366,- y: 1142.1438929622334,- },- {- x: 1052.7023705252766,- y: 1142.1438929622334,- },- {- x: 1052.7023705252766,- y: 1185.793178300212,- },- {- x: 224.29036606837366,- y: 1185.793178300212,- },- ],- boundingBox: {- left: 224.29036606837366,- top: 1142.1438929622334,- right: 1052.7023705252766,- bottom: 1185.793178300212,- },- },- {- id: "block_11_nehypx",- type: "text",- content:- "[20] Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In ICLR, 2015.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.912,- avgOcrConfidence: 0.989,- },- polygon: [- {- x: 223.92950266817192,- y: 1205.8213097134928,- },- {- x: 1052.7550077786411,- y: 1205.8213097134928,- },- {- x: 1052.7550077786411,- y: 1227.2851158658366,- },- {- x: 223.92950266817192,- y: 1227.2851158658366,- },- ],- boundingBox: {- left: 223.92950266817192,- top: 1205.8213097134928,- right: 1052.7550077786411,- bottom: 1227.2851158658366,- },- },- {- id: "block_11_af7MVz",- type: "text",- content:- "[21] Oleksii Kuchaiev and Boris Ginsburg. Factorization tricks for LSTM networks. arXiv preprint arXiv: 1703.10722, 2017.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.925,- avgOcrConfidence: 0.989,- },- polygon: [- {- x: 223.78512890669552,- y: 1247.11833873548,- },- {- x: 1050.4177622551465,- y: 1247.11833873548,- },- {- x: 1050.4177622551465,- y: 1289.109575544085,- },- {- x: 223.78512890669552,- y: 1289.109575544085,- },- ],- boundingBox: {- left: 223.78512890669552,- top: 1247.11833873548,- right: 1050.4177622551465,- bottom: 1289.109575544085,- },- },- {- id: "block_11_vnPlfZ",- type: "text",- content:- "[22] Zhouhan Lin, Minwei Feng, Cicero Nogueira dos Santos, Mo Yu, Bing Xiang, Bowen Zhou, and Yoshua Bengio. A structured self-attentive sentence embedding. arXiv preprint arXiv: 1703.03130, 2017.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.913,- avgOcrConfidence: 0.99,- },- polygon: [- {- x: 223.74063338676507,- y: 1311.0246641116034,- },- {- x: 1050.2205618976677,- y: 1311.0246641116034,- },- {- x: 1050.2205618976677,- y: 1375.8748468958345,- },- {- x: 223.74063338676507,- y: 1375.8748468958345,- },- ],- boundingBox: {- left: 223.74063338676507,- top: 1311.0246641116034,- right: 1050.2205618976677,- bottom: 1375.8748468958345,- },- },- {- id: "block_11_g0SHxO",- type: "text",- content:- "[23] Minh-Thang Luong, Quoc V. Le, Ilya Sutskever, Oriol Vinyals, and Lukasz Kaiser. Multi-task sequence to sequence learning. arXiv preprint arXiv: 1511.06114, 2015.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.908,- avgOcrConfidence: 0.988,- },- polygon: [- {- x: 224.355428932357,- y: 1397.7982697451025,- },- {- x: 1050.4997476174015,- y: 1397.7982697451025,- },- {- x: 1050.4997476174015,- y: 1441.9434448471643,- },- {- x: 224.355428932357,- y: 1441.9434448471643,- },- ],- boundingBox: {- left: 224.355428932357,- top: 1397.7982697451025,- right: 1050.4997476174015,- bottom: 1441.9434448471643,- },- },- {- id: "block_11_gDtqYI",- type: "text",- content:- "[24] Minh-Thang Luong, Hieu Pham, and Christopher D Manning. Effective approaches to attention- based neural machine translation. arXiv preprint arXiv: 1508.04025, 2015.",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.927,- avgOcrConfidence: 0.99,- },- polygon: [- {- x: 224.7064228475529,- y: 1461.612349775501,- },- {- x: 1052.9802308465444,- y: 1461.612349775501,- },- {- x: 1052.9802308465444,- y: 1506.2439438669305,- },- {- x: 224.7064228475529,- y: 1506.2439438669305,- },- ],- boundingBox: {- left: 224.7064228475529,- top: 1461.612349775501,- right: 1052.9802308465444,- bottom: 1506.2439438669305,- },- },- {- id: "block_11_JWTkzE",- type: "page_number",- content: "11",- metadata: {- page: {- number: 11,- width: 1275,- height: 1651,- },- layoutClass: "Page Number",- minOcrConfidence: 0.995,- avgOcrConfidence: 0.995,- },- polygon: [- {- x: 629.039650241824,- y: 1547.854550239735,- },- {- x: 645.38100862155,- y: 1547.854550239735,- },- {- x: 645.38100862155,- y: 1563.4467601919532,- },- {- x: 629.039650241824,- y: 1563.4467601919532,- },- ],- boundingBox: {- left: 629.039650241824,- top: 1547.854550239735,- right: 645.38100862155,- bottom: 1563.4467601919532,- },- },- ],- },- {- blocks: [- {- id: "block_12_TQ4Lbe",- type: "text",- content:- "[25] Mitchell P Marcus, Mary Ann Marcinkiewicz, and Beatrice Santorini. Building a large annotated corpus of english: The penn treebank. Computational linguistics, 19(2):313-330, 1993.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.913,- avgOcrConfidence: 0.99,- },- polygon: [- {- x: 223.94512343580706,- y: 154.85743054411464,- },- {- x: 1050.2930801280222,- y: 154.85743054411464,- },- {- x: 1050.2930801280222,- y: 198.76930494953817,- },- {- x: 223.94512343580706,- y: 198.76930494953817,- },- ],- boundingBox: {- left: 223.94512343580706,- top: 154.85743054411464,- right: 1050.2930801280222,- bottom: 198.76930494953817,- },- },- {- id: "block_12_LvCkff",- type: "text",- content:- "[26] David McClosky, Eugene Charniak, and Mark Johnson. Effective self-training for parsing. In Proceedings of the Human Language Technology Conference of the NAACL, Main Conference, pages 152-159. ACL, June 2006.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.907,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 224.21323261121762,- y: 226.782506971431,- },- {- x: 1051.9384676522582,- y: 226.782506971431,- },- {- x: 1051.9384676522582,- y: 292.8687442406676,- },- {- x: 224.21323261121762,- y: 292.8687442406676,- },- ],- boundingBox: {- left: 224.21323261121762,- top: 226.782506971431,- right: 1051.9384676522582,- bottom: 292.8687442406676,- },- },- {- id: "block_12_Rm8AFL",- type: "text",- content:- "[27] Ankur Parikh, Oscar T\u00e4ckstr\u00f6m, Dipanjan Das, and Jakob Uszkoreit. A decomposable attention model. In Empirical Methods in Natural Language Processing, 2016.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.916,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 224.08847948060418,- y: 321.2656073462694,- },- {- x: 1048.8436622341185,- y: 321.2656073462694,- },- {- x: 1048.8436622341185,- y: 364.85913349811295,- },- {- x: 224.08847948060418,- y: 364.85913349811295,- },- ],- boundingBox: {- left: 224.08847948060418,- top: 321.2656073462694,- right: 1048.8436622341185,- bottom: 364.85913349811295,- },- },- {- id: "block_12_cqas9e",- type: "text",- content:- "[28] Romain Paulus, Caiming Xiong, and Richard Socher. A deep reinforced model for abstractive summarization. arXiv preprint arXiv: 1705.04304, 2017.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.912,- avgOcrConfidence: 0.988,- },- polygon: [- {- x: 224.67392691730583,- y: 392.7383714116606,- },- {- x: 1049.3349117084142,- y: 392.7383714116606,- },- {- x: 1049.3349117084142,- y: 435.42904860991285,- },- {- x: 224.67392691730583,- y: 435.42904860991285,- },- ],- boundingBox: {- left: 224.67392691730583,- top: 392.7383714116606,- right: 1049.3349117084142,- bottom: 435.42904860991285,- },- },- {- id: "block_12_hfa5dB",- type: "text",- content:- "[29] Slav Petrov, Leon Barrett, Romain Thibaux, and Dan Klein. Learning accurate, compact, and interpretable tree annotation. In Proceedings of the 21st International Conference on Computational Linguistics and 44th Annual Meeting of the ACL, pages 433-440. ACL, July 2006.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.899,- avgOcrConfidence: 0.99,- },- polygon: [- {- x: 223.91392923619625,- y: 463.67279296530813,- },- {- x: 1051.5214404920591,- y: 463.67279296530813,- },- {- x: 1051.5214404920591,- y: 549.7230681799408,- },- {- x: 223.91392923619625,- y: 549.7230681799408,- },- ],- boundingBox: {- left: 223.91392923619625,- top: 463.67279296530813,- right: 1051.5214404920591,- bottom: 549.7230681799408,- },- },- {- id: "block_12_H2k7w4",- type: "text",- content:- "[30] Ofir Press and Lior Wolf. Using the output embedding to improve language models. arXiv preprint arXiv: 1608.05859, 2016.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.898,- avgOcrConfidence: 0.987,- },- polygon: [- {- x: 224.29183347381814,- y: 581.8894180068396,- },- {- x: 1049.7876299558764,- y: 581.8894180068396,- },- {- x: 1049.7876299558764,- y: 624.918793785841,- },- {- x: 224.29183347381814,- y: 624.918793785841,- },- ],- boundingBox: {- left: 224.29183347381814,- top: 581.8894180068396,- right: 1049.7876299558764,- bottom: 624.918793785841,- },- },- {- id: "block_12_UrZIEK",- type: "text",- content:- "[31] Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words with subword units. arXiv preprint arXiv: 1508.07909, 2015.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.925,- avgOcrConfidence: 0.988,- },- polygon: [- {- x: 224.35140540129947,- y: 653.3260510666926,- },- {- x: 1049.4855337769445,- y: 653.3260510666926,- },- {- x: 1049.4855337769445,- y: 696.2955715494944,- },- {- x: 224.35140540129947,- y: 696.2955715494944,- },- ],- boundingBox: {- left: 224.35140540129947,- top: 653.3260510666926,- right: 1049.4855337769445,- bottom: 696.2955715494944,- },- },- {- id: "block_12_IIwlxZ",- type: "text",- content:- "[32] Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz, Andy Davis, Quoc Le, Geoffrey Hinton, and Jeff Dean. Outrageously large neural networks: The sparsely-gated mixture-of-experts layer. arXiv preprint arXiv: 1701.06538, 2017.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.88,- avgOcrConfidence: 0.988,- },- polygon: [- {- x: 224.15238262092979,- y: 724.7319041087216,- },- {- x: 1051.274348349467,- y: 724.7319041087216,- },- {- x: 1051.274348349467,- y: 791.0497254966793,- },- {- x: 224.15238262092979,- y: 791.0497254966793,- },- ],- boundingBox: {- left: 224.15238262092979,- top: 724.7319041087216,- right: 1051.274348349467,- bottom: 791.0497254966793,- },- },- {- id: "block_12_pGLzhM",- type: "text",- content:- "[33] Nitish Srivastava, Geoffrey E Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdi- nov. Dropout: a simple way to prevent neural networks from overfitting. Journal of Machine Learning Research, 15(1):1929-1958, 2014.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.938,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 224.4417928431156,- y: 819.0001126052741,- },- {- x: 1053.3042907714844,- y: 819.0001126052741,- },- {- x: 1053.3042907714844,- y: 885.2761205228649,- },- {- x: 224.4417928431156,- y: 885.2761205228649,- },- ],- boundingBox: {- left: 224.4417928431156,- top: 819.0001126052741,- right: 1053.3042907714844,- bottom: 885.2761205228649,- },- },- {- id: "block_12_Bz8MfK",- type: "text",- content:- "[34] Sainbayar Sukhbaatar, Arthur Szlam, Jason Weston, and Rob Fergus. End-to-end memory networks. In C. Cortes, N. D. Lawrence, D. D. Lee, M. Sugiyama, and R. Garnett, editors, Advances in Neural Information Processing Systems 28, pages 2440-2448. Curran Associates, Inc., 2015.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.897,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 224.0948934624665,- y: 913.8373252467105,- },- {- x: 1051.823347328353,- y: 913.8373252467105,- },- {- x: 1051.823347328353,- y: 1000.8878563328793,- },- {- x: 224.0948934624665,- y: 1000.8878563328793,- },- ],- boundingBox: {- left: 224.0948934624665,- top: 913.8373252467105,- right: 1051.823347328353,- bottom: 1000.8878563328793,- },- },- {- id: "block_12_m0nnSr",- type: "text",- content:- "[35] Ilya Sutskever, Oriol Vinyals, and Quoc VV Le. Sequence to sequence learning with neural networks. In Advances in Neural Information Processing Systems, pages 3104-3112, 2014.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.899,- avgOcrConfidence: 0.988,- },- polygon: [- {- x: 224.52872478178818,- y: 1030.965426796361,- },- {- x: 1050.1110271815835,- y: 1030.965426796361,- },- {- x: 1050.1110271815835,- y: 1074.9609636579241,- },- {- x: 224.52872478178818,- y: 1074.9609636579241,- },- ],- boundingBox: {- left: 224.52872478178818,- top: 1030.965426796361,- right: 1050.1110271815835,- bottom: 1074.9609636579241,- },- },- {- id: "block_12_C1nzdD",- type: "text",- content:- "[36] Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, and Zbigniew Wojna. Rethinking the inception architecture for computer vision. CoRR, abs/1512.00567, 2015.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.939,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 224.60145602261062,- y: 1102.9526906981505,- },- {- x: 1051.9790816481095,- y: 1102.9526906981505,- },- {- x: 1051.9790816481095,- y: 1146.15116715969,- },- {- x: 224.60145602261062,- y: 1146.15116715969,- },- ],- boundingBox: {- left: 224.60145602261062,- top: 1102.9526906981505,- right: 1051.9790816481095,- bottom: 1146.15116715969,- },- },- {- id: "block_12_smJ629",- type: "text",- content:- "[37] Vinyals & Kaiser, Koo, Petrov, Sutskever, and Hinton. Grammar as a foreign language. In Advances in Neural Information Processing Systems, 2015.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.912,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 224.70363004364236,- y: 1173.716330506748,- },- {- x: 1049.93891472364,- y: 1173.716330506748,- },- {- x: 1049.93891472364,- y: 1218.0808487512115,- },- {- x: 224.70363004364236,- y: 1218.0808487512115,- },- ],- boundingBox: {- left: 224.70363004364236,- top: 1173.716330506748,- right: 1049.93891472364,- bottom: 1218.0808487512115,- },- },- {- id: "block_12_oKrqzS",- type: "text",- content:- "[38] Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. Google's neural machine translation system: Bridging the gap between human and machine translation. arXiv preprint arXiv: 1609.08144, 2016.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.935,- avgOcrConfidence: 0.992,- },- polygon: [- {- x: 224.222865417926,- y: 1246.0137622804568,- },- {- x: 1050.4285547855127,- y: 1246.0137622804568,- },- {- x: 1050.4285547855127,- y: 1332.3901636224045,- },- {- x: 224.222865417926,- y: 1332.3901636224045,- },- ],- boundingBox: {- left: 224.222865417926,- top: 1246.0137622804568,- right: 1050.4285547855127,- bottom: 1332.3901636224045,- },- },- {- id: "block_12_5hQUgX",- type: "text",- content:- "[39] Jie Zhou, Ying Cao, Xuguang Wang, Peng Li, and Wei Xu. Deep recurrent models with fast-forward connections for neural machine translation. CoRR, abs/1606.04199, 2016.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.977,- avgOcrConfidence: 0.992,- },- polygon: [- {- x: 224.40534438530025,- y: 1362.7727877394598,- },- {- x: 1049.6643678985372,- y: 1362.7727877394598,- },- {- x: 1049.6643678985372,- y: 1404.796982844073,- },- {- x: 224.40534438530025,- y: 1404.796982844073,- },- ],- boundingBox: {- left: 224.40534438530025,- top: 1362.7727877394598,- right: 1049.6643678985372,- bottom: 1404.796982844073,- },- },- {- id: "block_12_7qyMnf",- type: "text",- content:- "[40] Muhua Zhu, Yue Zhang, Wenliang Chen, Min Zhang, and Jingbo Zhu. Fast and accurate shift-reduce constituent parsing. In Proceedings of the 51st Annual Meeting of the ACL (Volume 1: Long Papers), pages 434-443. ACL, August 2013.",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "List Item",- minOcrConfidence: 0.905,- avgOcrConfidence: 0.991,- },- polygon: [- {- x: 224.04902520841057,- y: 1434.5126750056904,- },- {- x: 1049.9945814592124,- y: 1434.5126750056904,- },- {- x: 1049.9945814592124,- y: 1501.148572362455,- },- {- x: 224.04902520841057,- y: 1501.148572362455,- },- ],- boundingBox: {- left: 224.04902520841057,- top: 1434.5126750056904,- right: 1049.9945814592124,- bottom: 1501.148572362455,- },- },- {- id: "block_12_6o6JUd",- type: "page_number",- content: "12",- metadata: {- page: {- number: 12,- width: 1275,- height: 1651,- },- layoutClass: "Page Number",- minOcrConfidence: 0.998,- avgOcrConfidence: 0.998,- },- polygon: [- {- x: 628.997000812614,- y: 1547.789391309695,- },- {- x: 647.0427269483133,- y: 1547.789391309695,- },- {- x: 647.0427269483133,- y: 1563.398364533159,- },- {- x: 628.997000812614,- y: 1563.398364533159,- },- ],- boundingBox: {- left: 628.997000812614,- top: 1547.789391309695,- right: 647.0427269483133,- bottom: 1563.398364533159,- },- },- ],- },- {- blocks: [- {- id: "block_13_KlKk5h",- type: "page_number",- content: "13",- metadata: {- page: {- number: 13,- width: 1651,- height: 1275,- },- layoutClass: "Page Number",- minOcrConfidence: 0.999,- avgOcrConfidence: 0.999,- },- polygon: [- {- x: 103.29433033878627,- y: 628.7723457726248,- },- {- x: 103.29433033878627,- y: 646.9001519418981,- },- {- x: 87.59273293860883,- y: 646.9001519418981,- },- {- x: 87.59273293860883,- y: 628.7723457726248,- },- ],- boundingBox: {- left: 87.59273293860883,- top: 628.7723457726248,- right: 103.29433033878627,- bottom: 646.9001519418981,- },- },- {- id: "block_13_PkaOm5",- type: "text",- content:- "the word 'making'. Different colors represent different heads. Best viewed in color. the verb 'making', completing the phrase 'making ... more difficult'. Attentions here shown only for encoder self-attention in layer 5 of 6. Many of the attention heads attend to a distant dependency of Figure 3: An example of the attention mechanism following long-distance dependencies in the",- metadata: {- page: {- number: 13,- width: 1651,- height: 1275,- },- layoutClass: "Caption",- minOcrConfidence: 0.937,- avgOcrConfidence: 0.992,- },- polygon: [- {- x: 999.8870322148603,- y: 224.33585563715354,- },- {- x: 999.8870322148603,- y: 1052.0067256732577,- },- {- x: 911.037953656419,- y: 1052.0067256732577,- },- {- x: 911.037953656419,- y: 224.33585563715354,- },- ],- boundingBox: {- left: 911.037953656419,- top: 224.33585563715354,- right: 999.8870322148603,- bottom: 1052.0067256732577,- },- },- {- id: "block_13_xamkHQ",- type: "figure",- content:- "<figure type=\"diagram\">\nIt It is is in in this this spirit spirit that that a a majority majority of of American American governments governments have have passed passed new new laws laws since since 2009 2009 making making the the registration registration or or voting voting process process more more difficult difficult\n\n. . <EOS> <EOS> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad>\n<caption>Diagram showing attention mechanism or word alignment between two identical sequences of text. The word 'making' in the right column is highlighted in gray and acts as the target for connections from the left column. Connections originate from the words 'laws', '2009', 'making', 'more', and 'difficult' in the left column and point to 'making' in the right column. The sequence of text is: 'It is in this spirit that a majority of American governments have passed new laws since 2009 making the registration or voting process more difficult. <EOS> <pad> <pad> <pad> <pad> <pad> <pad> <pad>'</caption>\n</figure>",- metadata: {- page: {- number: 13,- width: 1651,- height: 1275,- },- layoutClass: "Picture/Figure/Image/Chart",- minOcrConfidence: 0.717,- avgOcrConfidence: 0.98,- },- polygon: [- {- x: 1444.0009233001479,- y: 252.8656019781628,- },- {- x: 1444.0009233001479,- y: 1047.5539548553688,- },- {- x: 1022.9538143416097,- y: 1047.5539548553688,- },- {- x: 1022.9538143416097,- y: 252.8656019781628,- },- ],- boundingBox: {- left: 1022.9538143416097,- top: 252.8656019781628,- right: 1444.0009233001479,- bottom: 1047.5539548553688,- },- },- {- id: "block_13_5eYqPZ",- type: "heading",- content: "# Attention Visualizations",- metadata: {- page: {- number: 13,- width: 1651,- height: 1275,- },- layoutClass: "Heading",- minOcrConfidence: 0.992,- avgOcrConfidence: 0.992,- },- polygon: [- {- x: 1498.6412794643775,- y: 224.94428453654268,- },- {- x: 1498.6412794643775,- y: 480.8453803514912,- },- {- x: 1479.199057528847,- y: 480.8453803514912,- },- {- x: 1479.199057528847,- y: 224.94428453654268,- },- ],- boundingBox: {- left: 1479.199057528847,- top: 224.94428453654268,- right: 1498.6412794643775,- bottom: 480.8453803514912,- },- },- ],- },- {- blocks: [- {- id: "block_14_DaAuYi",- type: "page_number",- content: "14",- metadata: {- page: {- number: 14,- width: 1651,- height: 1275,- },- layoutClass: "Page Number",- minOcrConfidence: 0.998,- avgOcrConfidence: 0.998,- },- polygon: [- {- x: 103.12243577770732,- y: 628.7327731612825,- },- {- x: 103.12243577770732,- y: 647.0026336447166,- },- {- x: 87.74237117910752,- y: 647.0026336447166,- },- {- x: 87.74237117910752,- y: 628.7327731612825,- },- ],- boundingBox: {- left: 87.74237117910752,- top: 628.7327731612825,- right: 103.12243577770732,- bottom: 647.0026336447166,- },- },- {- id: "block_14_VDKMys",- type: "text",- content:- "and 6. Note that the attentions are very sharp for this word. Full attentions for head 5. Bottom: Isolated attentions from just the word 'its' for attention heads 5 Figure 4: Two attention heads, also in layer 5 of 6, apparently involved in anaphora resolution. Top:",- metadata: {- page: {- number: 14,- width: 1651,- height: 1275,- },- layoutClass: "Caption",- minOcrConfidence: 0.972,- avgOcrConfidence: 0.993,- },- polygon: [- {- x: 370.4634644357782,- y: 224.1528559775248,- },- {- x: 370.4634644357782,- y: 1051.3102287793681,- },- {- x: 303.81733864232115,- y: 1051.3102287793681,- },- {- x: 303.81733864232115,- y: 224.1528559775248,- },- ],- boundingBox: {- left: 303.81733864232115,- top: 224.1528559775248,- right: 370.4634644357782,- bottom: 1051.3102287793681,- },- },- {- id: "block_14_QRz2LE",- type: "figure",- content:- "<figure type=\"diagram\">\nThe The The The Law Law Law Law will will will will never never never never be be be be perfect perfect perfect perfect , , , , but but but but its its its its application application application application should should should should be be be be just just just just - - - - this this this this is is is is what what what what we we we we are are are are missing missing missing missing , , , , in in in in my my my my opinion opinion opinion opinion . . . . <EOS> <EOS> <EOS> <EOS> <pad> <pad> <pad> <pad>\n<caption>Attention weight visualization diagram showing alignment between two sequences of text tokens. The diagram consists of three columns of text, with lines connecting tokens between the columns to represent attention strength. Thicker, more opaque lines indicate higher attention weights. The text sequence is: 'The', 'Law', 'will', 'never', 'be', 'perfect', ',', 'but', 'its', 'application', 'should', 'be', 'just', '-', 'this', 'is', 'what', 'we', 'are', 'missing', ',', 'in', 'my', 'opinion', '.', '<EOS>', '<pad>'. Specific highlights are present: the word 'Law' in the first column and 'its' in the second column are highlighted with a purple/grey background, and lines connect these highlighted tokens to corresponding tokens in the third column.</caption>\n</figure>",- metadata: {- page: {- number: 14,- width: 1651,- height: 1275,- },- layoutClass: "Picture/Figure/Image/Chart",- minOcrConfidence: 0.379,- avgOcrConfidence: 0.963,- },- polygon: [- {- x: 1294.7974623916741,- y: 255.12043611846704,- },- {- x: 1294.7974623916741,- y: 1044.444475382784,- },- {- x: 388.9633916410289,- y: 1044.444475382784,- },- {- x: 388.9633916410289,- y: 255.12043611846704,- },- ],- boundingBox: {- left: 388.9633916410289,- top: 255.12043611846704,- right: 1294.7974623916741,- bottom: 1044.444475382784,- },- },- ],- },- {- blocks: [- {- id: "block_15_pV91a2",- type: "page_number",- content: "15",- metadata: {- page: {- number: 15,- width: 1651,- height: 1275,- },- layoutClass: "Page Number",- minOcrConfidence: 0.998,- avgOcrConfidence: 0.998,- },- polygon: [- {- x: 103.26014084206486,- y: 628.7008215911197,- },- {- x: 103.26014084206486,- y: 647.1549124613296,- },- {- x: 87.58487219559515,- y: 647.1549124613296,- },- {- x: 87.58487219559515,- y: 628.7008215911197,- },- ],- boundingBox: {- left: 87.58487219559515,- top: 628.7008215911197,- right: 103.26014084206486,- bottom: 647.1549124613296,- },- },- {- id: "block_15_2igWoi",- type: "text",- content:- "at layer 5 of 6. The heads clearly learned to perform different tasks. sentence. We give two such examples above, from two different heads from the encoder self-attention Figure 5: Many of the attention heads exhibit behaviour that seems related to the structure of the",- metadata: {- page: {- number: 15,- width: 1651,- height: 1275,- },- layoutClass: "Caption",- minOcrConfidence: 0.976,- avgOcrConfidence: 0.994,- },- polygon: [- {- x: 394.6980404387739,- y: 223.74716570777616,- },- {- x: 394.6980404387739,- y: 1049.736980800211,- },- {- x: 328.87227315113955,- y: 1049.736980800211,- },- {- x: 328.87227315113955,- y: 223.74716570777616,- },- ],- boundingBox: {- left: 328.87227315113955,- top: 223.74716570777616,- right: 394.6980404387739,- bottom: 1049.736980800211,- },- },- {- id: "block_15_OqCqJD",- type: "figure",- content:- "<figure type=\"diagram\">\nThe The Law Law will will never never be be perfect perfect , , but but its its application application should should be be just just - - this this is is what what we we are are missing missing , , in in my my opinion opinion\n\n. . <EOS> <EOS> <pad> <pad>\n<caption>Attention weight visualization showing connections between two identical sequences of text: 'The Law will never be perfect , but its application should be just - this is what we are missing , in my opinion . <EOS> <pad>'. The diagram uses lines of varying thickness and red color intensity to indicate the strength of attention between words in the left sequence and words in the right sequence. Stronger connections are represented by thicker, more opaque red lines, while weaker connections are represented by thinner, more transparent red lines.</caption>\n</figure>",- metadata: {- page: {- number: 15,- width: 1651,- height: 1275,- },- layoutClass: "Picture/Figure/Image/Chart",- minOcrConfidence: 0.651,- avgOcrConfidence: 0.969,- },- polygon: [- {- x: 810.314180990807,- y: 253.4944325467966,- },- {- x: 810.314180990807,- y: 1035.3522419059364,- },- {- x: 421.96601087527165,- y: 1035.3522419059364,- },- {- x: 421.96601087527165,- y: 253.4944325467966,- },- ],- boundingBox: {- left: 421.96601087527165,- top: 253.4944325467966,- right: 810.314180990807,- bottom: 1035.3522419059364,- },- },- {- id: "block_15_sK8Nre",- type: "figure",- content:- "<figure type=\"diagram\">\nThe The Law Law will will never never be be perfect perfect , , but but its its application application should should be be just just - - this this is is what what we we are are missing missing , , in in my my opinion opinion\n\n. . <EOS> <EOS> <pad> <pad>\n<caption>Attention weight visualization diagram showing connections between two identical sequences of text: 'The', 'Law', 'will', 'never', 'be', 'perfect', ',', 'but', 'its', 'application', 'should', 'be', 'just', '-', 'this', 'is', 'what', 'we', 'are', 'missing', ',', 'in', 'my', 'opinion', '.', '<EOS>', '<pad>'. The diagram displays lines connecting tokens from the left sequence to the right sequence, where line thickness and opacity represent the strength of the attention weight. Notable high-attention connections include: 'Law' to 'Law', 'application' to 'application', 'missing' to 'missing', 'opinion' to 'opinion', and '<pad>' to '<pad>'.</caption>\n</figure>",- metadata: {- page: {- number: 15,- width: 1651,- height: 1275,- },- layoutClass: "Picture/Figure/Image/Chart",- minOcrConfidence: 0.6,- avgOcrConfidence: 0.968,- },- polygon: [- {- x: 1255.9501913113702,- y: 254.50874105857238,- },- {- x: 1255.9501913113702,- y: 1034.3072598868043,- },- {- x: 882.2701913360366,- y: 1034.3072598868043,- },- {- x: 882.2701913360366,- y: 254.50874105857238,- },- ],- boundingBox: {- left: 882.2701913360366,- top: 254.50874105857238,- right: 1255.9501913113702,- bottom: 1034.3072598868043,- },- },- ],- },- ],-} satisfies ParsedOcrOutput--function getBlockType(block: ParsedOcrBlock): OcrBlockType | undefined {- if (block.type === "heading" || block.type === "section_heading") {- return "heading"- }-- if (block.type === "header") {- return "header"- }-- if (block.type === "footer") {- return "footer"- }-- if (block.type === "page_number") {- return "page_number"- }-- if (block.type === "figure" || block.type === "image") {- return "figure"- }-- if (block.type === "table") {- return "table"- }-- if (block.metadata.layoutClass === "List Item") {- return "list"- }-- if (block.type === "text") {- return "paragraph"- }-}--function getOcrBlocks(output: ParsedOcrOutput): OcrBlock[] {- return output.chunks.flatMap((chunk) =>- chunk.blocks.flatMap((block) => {- const type = getBlockType(block)- const { page } = block.metadata-- if (!type || page.width <= 0 || page.height <= 0) {- return []- }-- return {- id: block.id,- type,- text: block.content,- page: page.number,- pageWidth: page.width,- pageHeight: page.height,- confidence:- block.metadata.avgOcrConfidence ??- block.metadata.minOcrConfidence ??- 1,- polygon: block.polygon,- boundingBox: block.boundingBox,- }- })- )-}--function getBoundingBox(block: OcrBlock): BoundingBox {- if (block.boundingBox) {- return block.boundingBox- }-- const polygon = block.polygon ?? []- const xValues = polygon.map((point) => point.x)- const yValues = polygon.map((point) => point.y)- const left = Math.min(...xValues)- const right = Math.max(...xValues)- const top = Math.min(...yValues)- const bottom = Math.max(...yValues)-- return { left, top, right, bottom }-}--function getBlockCoordinateRotation(- block: OcrBlock,- pageSize?: { width: number; height: number }-) {- const blockIsLandscape = block.pageWidth > block.pageHeight-- if (!pageSize) return blockIsLandscape ? 1 : 0-- const pageIsLandscape = pageSize.width > pageSize.height-- if (blockIsLandscape && !pageIsLandscape) return 1- if (!blockIsLandscape && pageIsLandscape) return 3-- return 0-}--function normalizeHighlightAreaForRotation(- area: HighlightArea,- rotation: number-): HighlightArea {- if (rotation === 1) {- return {- left: area.top,- top: 100 - area.left - area.width,- width: area.height,- height: area.width,- }- }-- if (rotation === 3) {- return {- left: 100 - area.top - area.height,- top: area.left,- width: area.height,- height: area.width,- }- }-- return area-}--function convertBlockToHighlightArea(- block: OcrBlock,- pageSize?: { width: number; height: number }-): HighlightArea {- const { left, top, right, bottom } = getBoundingBox(block)-- const area = {- left: (left / block.pageWidth) * 100,- top: (top / block.pageHeight) * 100,- width: ((right - left) / block.pageWidth) * 100,- height: ((bottom - top) / block.pageHeight) * 100,- }-- return normalizeHighlightAreaForRotation(- area,- getBlockCoordinateRotation(block, pageSize)- )-}--const BlockOverlay = React.memo(function BlockOverlay({- block,- isActive,- pageHeight,- pageWidth,-}: {- block: OcrBlock- isActive: boolean- pageHeight: number- pageWidth: number-}) {- const highlight = convertBlockToHighlightArea(block, {- width: pageWidth,- height: pageHeight,- })- const style = BLOCK_STYLES[block.type]-- return (- <div- className={cn(- "pointer-events-none absolute z-10 border transition-[opacity,box-shadow]",- isActive- ? cn("opacity-100", style.overlay)- : cn("opacity-55", style.mutedOverlay)- )}- style={{- left: `${highlight.left}%`,- top: `${highlight.top}%`,- width: `${highlight.width}%`,- height: `${highlight.height}%`,- }}- />- )-})--const OcrBlockMarkdown = React.memo(function OcrBlockMarkdown({- text,-}: {- text: string-}) {- const markdown = text.replace(OCR_MARKDOWN_FIGURE_CAPTION_PATTERN, (tag) =>- tag.startsWith("</") ? "</figcaption>" : "<figcaption>"- )-- return (- <div className="space-y-1 text-sm leading-5 text-foreground/90">- <ReactMarkdown- rehypePlugins={OCR_MARKDOWN_REHYPE_PLUGINS}- remarkPlugins={OCR_MARKDOWN_REMARK_PLUGINS}- components={{- h1: ({ node: _node, ...props }) => (- <h1- className="my-0 text-base leading-5 font-semibold text-foreground"- {...props}- />- ),- h2: ({ node: _node, ...props }) => (- <h2- className="my-0 text-[15px] leading-5 font-semibold text-foreground"- {...props}- />- ),- h3: ({ node: _node, ...props }) => (- <h3- className="my-0 text-sm leading-5 font-semibold text-foreground"- {...props}- />- ),- p: ({ node: _node, ...props }) => (- <p className="my-0 text-[13px] leading-5" {...props} />- ),- strong: ({ node: _node, ...props }) => (- <strong className="font-semibold text-foreground" {...props} />- ),- em: ({ node: _node, ...props }) => (- <em className="text-foreground" {...props} />- ),- ul: ({ node: _node, ...props }) => (- <ul className="my-0 list-disc space-y-0.5 pl-4" {...props} />- ),- ol: ({ node: _node, ...props }) => (- <ol className="my-0 list-decimal space-y-0.5 pl-4" {...props} />- ),- li: ({ node: _node, ...props }) => (- <li className="pl-0.5 text-[13px] leading-5" {...props} />- ),- table: ({ node: _node, ...props }) => (- <div className="overflow-hidden rounded-md border bg-background">- <table className="w-full border-collapse text-xs" {...props} />- </div>- ),- figure: ({ node: _node, ...props }) => (- <figure- className="my-0 space-y-2 rounded-md border bg-muted/20 p-2 text-[13px]"- {...props}- />- ),- figcaption: ({ node: _node, ...props }) => (- <figcaption- className="border-t pt-2 text-xs leading-5 text-muted-foreground"- {...props}- />- ),- caption: ({ node: _node, ...props }) => (- <figcaption- className="block border-t pt-2 text-xs leading-5 text-muted-foreground"- {...props}- />- ),- th: ({ node: _node, ...props }) => (- <th- className="border-b bg-muted px-2 py-1 text-left font-medium"- {...props}- />- ),- td: ({ node: _node, ...props }) => (- <td className="border-t px-2 py-1" {...props} />- ),- }}- >- {markdown}- </ReactMarkdown>- </div>- )-})--function OcrBlocksPanel({- activeBlockId,- blocks,- className,- onBlockFocus,-}: {- activeBlockId?: string- blocks: OcrBlock[]- className?: string- onBlockFocus?: (block: OcrBlock) => void-}) {- const scrollViewportRef = React.useRef<HTMLDivElement | null>(null)- const [localActiveBlockId, setLocalActiveBlockId] = React.useState(- activeBlockId ?? blocks[0]?.id- )- const firstBlock = blocks[0]- const focusedBlockId = activeBlockId ?? localActiveBlockId- const activeBlock =- blocks.find((block) => block.id === focusedBlockId) ?? firstBlock- const focusedBlockIdRef = React.useRef(focusedBlockId)-- React.useEffect(() => {- focusedBlockIdRef.current = focusedBlockId- }, [focusedBlockId])-- const focusBlock = React.useCallback(- (block: OcrBlock) => {- if (block.id === focusedBlockIdRef.current) return-- focusedBlockIdRef.current = block.id- setLocalActiveBlockId(block.id)- onBlockFocus?.(block)- },- [onBlockFocus]- )- const estimateBlockSize = React.useCallback(- (index: number) => {- const block = blocks[index]- return block- ? getEstimatedOcrBlockRowHeight(block)- : OCR_BLOCK_ROW_MIN_ESTIMATE- },- [blocks]- )- // eslint-disable-next-line react-hooks/incompatible-library -- TanStack Virtual returns imperative helpers used by the OCR block list.- const virtualizer = useVirtualizer({- count: blocks.length,- estimateSize: estimateBlockSize,- getItemKey: (index) => blocks[index]?.id ?? index,- getScrollElement: () => scrollViewportRef.current,- overscan: 6,- })-- React.useEffect(() => {- if (!firstBlock) return- if (- activeBlockId ||- blocks.some((block) => block.id === localActiveBlockId)- ) {- return- }-- setLocalActiveBlockId(firstBlock.id)- }, [activeBlockId, blocks, firstBlock, localActiveBlockId])-- return (- <aside- className={cn("flex h-[420px] min-h-0 flex-col bg-background", className)}- >- <ScrollArea- className="min-h-0 flex-1"- scrollFade- viewportRef={scrollViewportRef}- >- {blocks.length ? (- <div- className="relative"- style={{- height: virtualizer.getTotalSize() + OCR_BLOCK_LIST_PADDING * 2,- }}- >- {virtualizer.getVirtualItems().map((virtualRow) => {- const block = blocks[virtualRow.index]- if (!block) return null-- return (- <div- key={virtualRow.key}- ref={virtualizer.measureElement}- data-index={virtualRow.index}- className="absolute top-0 right-3 left-3 pb-2 [contain:layout_paint]"- style={{- transform: `translateY(${- virtualRow.start + OCR_BLOCK_LIST_PADDING- }px)`,- }}- >- <OcrBlockButton- block={block}- isActive={block.id === activeBlock?.id}- onFocusBlock={focusBlock}- />- </div>- )- })}- </div>- ) : (- <div className="p-3">- <div className="rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground">- No layout blocks found.- </div>- </div>- )}- </ScrollArea>- </aside>- )-}+ ATTENTION_OCR_OUTPUT,+ getOcrBlocks,+ OcrBlocksPanel,+ PDF_URL,+ renderOcrBlockText,+ type ParsedOcrOutput,+} from "@/components/extend/layout-blocks"+import {+ LayoutBlocksPanel,+ type LayoutBlockItem,+} from "@/components/extend/layout-blocks-panel"+import { OcrBlocksBlock as PdfLayoutBlocks } from "@/registry/new-york-v4/blocks/layout-blocks-block"-const OcrBlockButton = React.memo(function OcrBlockButton({- block,- isActive,- onFocusBlock,-}: {- block: OcrBlock- isActive: boolean- onFocusBlock: (block: OcrBlock) => void-}) {- const style = BLOCK_STYLES[block.type]-- return (- <button- type="button"- onMouseEnter={() => onFocusBlock(block)}- onFocus={() => onFocusBlock(block)}- className={cn(- "w-full rounded-lg border bg-background p-3 text-left hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",- isActive && cn("shadow-[0_0_0_1px_rgb(0_0_0_/_4%)]", style.ring)- )}- >- <div className="min-w-0">- <div className="flex items-center justify-between gap-2">- <div className="flex min-w-0 items-center gap-2">- <div- className={cn(- "inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium",- style.badge- )}- >- <HugeiconsIcon icon={style.icon} className="size-3.5" />- {style.label}- </div>- <div className="truncate text-xs text-muted-foreground">- {Math.round(block.confidence * 100)}%- </div>- </div>- <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">- p. {block.page}- </div>- </div>- <div className="mt-2 text-sm text-foreground/90">- <OcrBlockMarkdown text={block.text} />- </div>- </div>- </button>- )-})+const DocsViewCodeBlock = dynamic(() =>+ import("@/components/docs-code-block").then((mod) => mod.DocsViewCodeBlock)+)export function OcrBlocks() {return (<OcrBlocksPanelblocks={getOcrBlocks(ATTENTION_OCR_OUTPUT).filter(- (block) => block.page === ROOT_OCR_PREVIEW_PAGE+ (block) => block.page === 1)}/>)}export function OcrBlocksBlock({- defaultViewerZoom = DEFAULT_ZOOM,- file = PDF_URL,- output = ATTENTION_OCR_OUTPUT,+ file = withUiBasePath(PDF_URL),+ defaultViewerZoom,+ output,}: {- defaultViewerZoom?: numberfile?: string+ defaultViewerZoom?: numberoutput?: ParsedOcrOutput}) {- const blocks = React.useMemo(() => getOcrBlocks(output), [output])- const [activeBlockId, setActiveBlockId] = React.useState(blocks[0]?.id)- const viewerRef = React.useRef<PDFViewerHandle>(null)- const activeBlockIdRef = React.useRef(activeBlockId)- const activeBlock = blocks.find((block) => block.id === activeBlockId)-- React.useEffect(() => {- activeBlockIdRef.current = activeBlockId- }, [activeBlockId])-- if (blocks.length && !blocks.some((block) => block.id === activeBlockId)) {- setActiveBlockId(blocks[0].id)- }-- const focusBlock = React.useCallback((block: OcrBlock) => {- if (block.id === activeBlockIdRef.current) return-- activeBlockIdRef.current = block.id- setActiveBlockId(block.id)- viewerRef.current?.scrollToPageArea(- block.page,- convertBlockToHighlightArea(block),- { behavior: "auto" }- )- }, [])-- const activeOverlayBlockId = activeBlock?.id- const renderPageOverlay = React.useCallback(- ({- pageHeight,- pageNumber,- pageWidth,- }: {- pageHeight: number- pageNumber: number- pageWidth: number- }) =>- blocks- .filter((block) => block.page === pageNumber)- .map((block) => (- <BlockOverlay- key={block.id}- block={block}- isActive={activeOverlayBlockId === block.id}- pageHeight={pageHeight}- pageWidth={pageWidth}- />- )),- [activeOverlayBlockId, blocks]- )-return (- <PdfBlockResizableShell+ <PdfLayoutBlocksautoSaveId="pdf-block-layout-blocks"- left={- <PDFViewer- ref={viewerRef}- src={file}- defaultZoom={defaultViewerZoom}- renderPageOverlay={renderPageOverlay}- />- }- right={- <OcrBlocksPanel- activeBlockId={activeBlock?.id}- blocks={blocks}- className="h-full"- onBlockFocus={focusBlock}- />- }+ file={file}+ defaultViewerZoom={defaultViewerZoom}+ output={output}/>)}-function OcrExampleCard({- active,- activeClassName,- badgeClassName,- confidence,- icon,- kind,- pageLabel,- text,-}: {- active?: boolean- activeClassName?: string- badgeClassName: string- confidence: number- icon: typeof Heading01Icon- kind: string- pageLabel: string- text: string-}) {- return (- <button- type="button"- className={cn(- "w-full rounded-lg border bg-background p-3 text-left hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",- active &&- (activeClassName ??- "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(0_0_0_/_4%)]")- )}- >- <div className="min-w-0">- <div className="flex items-center justify-between gap-2">- <div className="flex min-w-0 items-center gap-2">- <div- className={cn(- "inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium",- badgeClassName- )}- >- <HugeiconsIcon icon={icon} className="size-3.5" />- {kind}- </div>- <div className="truncate text-xs text-muted-foreground">- {Math.round(confidence * 100)}%- </div>- </div>- <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">- {pageLabel}- </div>- </div>- <div className="mt-2 text-sm text-foreground/90">- <OcrBlockMarkdown text={text} />- </div>- </div>- </button>- )-}--function OcrBlocksExample() {- return (- <div className="flex h-[420px] flex-col gap-2 bg-background p-3">- <OcrExampleCard- active- icon={Heading01Icon}- kind="Heading"- pageLabel="p. 1"- confidence={0.99}- text="# Attention Is All You Need"- badgeClassName="bg-violet-50 text-violet-600 dark:bg-violet-300/10 dark:text-violet-300"- activeClassName="border-violet-500/60 bg-violet-500/5"- />- <OcrExampleCard- icon={ParagraphIcon}- kind="Paragraph"- pageLabel="p. 1"- confidence={0.94}- text="The model relies **only on attention**, avoiding recurrence and convolutions."- badgeClassName="bg-blue-50 text-blue-600 dark:bg-blue-300/10 dark:text-blue-300"- />- <OcrExampleCard- icon={Table01Icon}- kind="Table"- pageLabel="p. 6"- confidence={0.91}- text={"- **Layer type**\n- Path length\n- Sequential operations"}- badgeClassName="bg-amber-50 text-amber-600 dark:bg-amber-300/10 dark:text-amber-300"- />- </div>- )-}+const exampleBlocks: LayoutBlockItem[] = [+ {+ id: "heading",+ type: "heading",+ page: 1,+ confidence: 0.99,+ text: "# Attention Is All You Need",+ },+ {+ id: "paragraph",+ type: "paragraph",+ page: 1,+ confidence: 0.94,+ text: "The model relies **only on attention**, avoiding recurrence and convolutions.",+ },+ {+ id: "table",+ type: "table",+ page: 6,+ confidence: 0.91,+ text: "- **Layer type**\n- Path length\n- Sequential operations",+ },+]export function OcrBlocksDemo() {return (@@ -8662,7 +80,10 @@ export function OcrBlocksDemo() {data-slot="component-preview"className="group relative mt-4 mb-12 flex flex-col overflow-hidden rounded-xl border">- <OcrBlocksExample />+ <LayoutBlocksPanel+ blocks={exampleBlocks}+ renderText={renderOcrBlockText}+ /><DocsViewCodeBlock code={ocrBlocksUsageCode} /></div>)@@ -8675,15 +96,3 @@ import { OcrBlocks } from "@/components/extend/layout-blocks";export function OcrBlocksExample() {return <OcrBlocks />;}`--const ocrBlocksSourceCode =- '"use client"\n\nimport * as React from "react"\nimport { useVirtualizer } from "@tanstack/react-virtual"\nimport ReactMarkdown from "react-markdown"\nimport rehypeRaw from "rehype-raw"\nimport rehypeSanitize, { defaultSchema } from "rehype-sanitize"\nimport remarkGfm from "remark-gfm"\n\nimport { cn } from "@/lib/utils"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nfunction AlignBoxBottomCenterGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="AlignVerticalJustifyEnd"\n tabler="IconAlignBoxBottomCenter"\n hugeicons="AlignBoxBottomCenterIcon"\n phosphor="AlignBottomIcon"\n remixicon="RiAlignBottom"\n {...props}\n />\n )\n}\n\nfunction Heading01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Heading1"\n tabler="IconH1"\n hugeicons="Heading01Icon"\n phosphor="TextHOneIcon"\n remixicon="RiH1"\n {...props}\n />\n )\n}\n\nfunction ImageCompositionGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Image"\n tabler="IconPhoto"\n hugeicons="ImageCompositionIcon"\n phosphor="ImageSquareIcon"\n remixicon="RiImageLine"\n {...props}\n />\n )\n}\n\nfunction LeftToRightListBulletGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Columns3Icon"\n tabler="IconLayoutColumns"\n hugeicons="LeftToRightListBulletIcon"\n phosphor="ColumnsIcon"\n remixicon="RiLayoutColumnLine"\n {...props}\n />\n )\n}\n\nfunction ParagraphGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Pilcrow"\n tabler="IconPilcrow"\n hugeicons="ParagraphIcon"\n phosphor="ParagraphIcon"\n remixicon="RiParagraph"\n {...props}\n />\n )\n}\n\nfunction Table01Glyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Table"\n tabler="IconTable"\n hugeicons="Table01Icon"\n phosphor="TableIcon"\n remixicon="RiTableLine"\n {...props}\n />\n )\n}\n\nfunction TextCenterlineCenterTopGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="PanelTop"\n tabler="IconLayoutNavbar"\n hugeicons="TextCenterlineCenterTopIcon"\n phosphor="AlignTopSimpleIcon"\n remixicon="RiLayoutTopLine"\n {...props}\n />\n )\n}\n\nfunction TextNumberSignGlyph(props: React.ComponentProps<"svg">) {\n return (\n <IconPlaceholder\n lucide="Hash"\n tabler="IconHash"\n hugeicons="TextNumberSignIcon"\n phosphor="HashIcon"\n remixicon="RiHashtag"\n {...props}\n />\n )\n}\n\nexport type Point = {\n x: number\n y: number\n}\n\nexport type BoundingBox = {\n left: number\n top: number\n right: number\n bottom: number\n}\n\nexport type OcrBlockType =\n | "heading"\n | "paragraph"\n | "list"\n | "table"\n | "figure"\n | "header"\n | "footer"\n | "page_number"\n\nexport type ParsedOcrBlock = {\n id: string\n type: string\n content: string\n metadata: {\n page: {\n number: number\n width: number\n height: number\n }\n layoutClass?: string\n minOcrConfidence?: number\n avgOcrConfidence?: number\n }\n polygon?: Point[]\n boundingBox?: BoundingBox\n}\n\nexport type ParsedOcrOutput = {\n chunks: {\n blocks: ParsedOcrBlock[]\n }[]\n}\n\nexport type OcrBlock = {\n id: string\n type: OcrBlockType\n text: string\n page: number\n pageWidth: number\n pageHeight: number\n confidence: number\n polygon?: Point[]\n boundingBox?: BoundingBox\n}\n\nexport type HighlightArea = {\n left: number\n top: number\n width: number\n height: number\n}\n\nexport const PDF_URL = "/samples/attention.pdf"\nconst OCR_BLOCK_ROW_MIN_ESTIMATE = 92\nconst OCR_BLOCK_ROW_VERTICAL_CHROME = 62\nconst OCR_BLOCK_LINE_HEIGHT = 20\nconst OCR_BLOCK_ESTIMATED_CHARS_PER_LINE = 42\nconst OCR_BLOCK_ROW_GAP = 8\nconst OCR_BLOCK_LIST_PADDING = 12\nconst OCR_MARKDOWN_SCHEMA = {\n ...defaultSchema,\n attributes: {\n ...defaultSchema.attributes,\n figure: [...(defaultSchema.attributes?.figure ?? []), "type"],\n },\n tagNames: [\n ...(defaultSchema.tagNames ?? []),\n "caption",\n "figcaption",\n "figure",\n ],\n}\nconst OCR_MARKDOWN_REHYPE_PLUGINS: NonNullable<\n React.ComponentProps<typeof ReactMarkdown>["rehypePlugins"]\n> = [rehypeRaw, [rehypeSanitize, OCR_MARKDOWN_SCHEMA]]\nconst OCR_MARKDOWN_REMARK_PLUGINS: NonNullable<\n React.ComponentProps<typeof ReactMarkdown>["remarkPlugins"]\n> = [remarkGfm]\nconst OCR_MARKDOWN_FIGURE_CAPTION_PATTERN = /<\\/?caption>/gi\n\nfunction getEstimatedOcrBlockRowHeight(block: OcrBlock) {\n const plainText = block.text\n .replace(OCR_MARKDOWN_FIGURE_CAPTION_PATTERN, "")\n .replace(/<[^>]*>/g, "")\n .replace(/\\s+/g, " ")\n .trim()\n const explicitLineCount = block.text.split(/\\n+/).filter(Boolean).length\n const wrappedLineCount = Math.max(\n explicitLineCount,\n Math.ceil(plainText.length / OCR_BLOCK_ESTIMATED_CHARS_PER_LINE)\n )\n const contentHeight = Math.max(1, wrappedLineCount) * OCR_BLOCK_LINE_HEIGHT\n const typeExtraHeight =\n block.type === "figure" ? 44 : block.type === "table" ? 28 : 0\n\n return Math.max(\n OCR_BLOCK_ROW_MIN_ESTIMATE,\n OCR_BLOCK_ROW_VERTICAL_CHROME +\n contentHeight +\n typeExtraHeight +\n OCR_BLOCK_ROW_GAP\n )\n}\n\nexport const ATTENTION_OCR_OUTPUT = {\n chunks: [\n {\n blocks: [\n {\n id: "block_1_IKDP4i",\n type: "header",\n content: "arXiv:1706.03762v7 [cs.CL] 2 Aug 2023",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Header",\n minOcrConfidence: 0.959,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 36.16179897837395,\n y: 447.38040863840206,\n },\n {\n x: 75.85163708150822,\n y: 447.38040863840206,\n },\n {\n x: 75.85163708150822,\n y: 1155.1796566956025,\n },\n {\n x: 36.16179897837395,\n y: 1155.1796566956025,\n },\n ],\n boundingBox: {\n left: 36.16179897837395,\n top: 447.38040863840206,\n right: 75.85163708150822,\n bottom: 1155.1796566956025,\n },\n },\n {\n id: "block_1_rtNdsr",\n type: "header",\n content:\n "Provided proper attribution is provided, Google hereby grants permission to reproduce the tables and figures in this paper solely for use in journalistic or scholarly works.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Header",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 258.50183528705236,\n y: 151.7837261257315,\n },\n {\n x: 1016.8830982960054,\n y: 151.7837261257315,\n },\n {\n x: 1016.8830982960054,\n y: 233.84929126366637,\n },\n {\n x: 258.50183528705236,\n y: 233.84929126366637,\n },\n ],\n boundingBox: {\n left: 258.50183528705236,\n top: 151.7837261257315,\n right: 1016.8830982960054,\n bottom: 233.84929126366637,\n },\n },\n {\n id: "block_1_eo9AoV",\n type: "heading",\n content: "# Attention Is All You Need",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 440.0215455215343,\n y: 312.01490975860366,\n },\n {\n x: 831.4373211268961,\n y: 312.01490975860366,\n },\n {\n x: 831.4373211268961,\n y: 339.0022611402928,\n },\n {\n x: 440.0215455215343,\n y: 339.0022611402928,\n },\n ],\n boundingBox: {\n left: 440.0215455215343,\n top: 312.01490975860366,\n right: 831.4373211268961,\n bottom: 339.0022611402928,\n },\n },\n {\n id: "block_1_Kdt5Cu",\n type: "text",\n content: "Ashish Vaswani* Google Brain [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.977,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 242.9606625633518,\n y: 490.4495616712068,\n },\n {\n x: 449.64758323056856,\n y: 490.4495616712068,\n },\n {\n x: 449.64758323056856,\n y: 555.9028907431696,\n },\n {\n x: 242.9606625633518,\n y: 555.9028907431696,\n },\n ],\n boundingBox: {\n left: 242.9606625633518,\n top: 490.4495616712068,\n right: 449.64758323056856,\n bottom: 555.9028907431696,\n },\n },\n {\n id: "block_1_6Xv6uR",\n type: "text",\n content: "Llion Jones* Google Research [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.927,\n avgOcrConfidence: 0.982,\n },\n polygon: [\n {\n x: 264.3723327748097,\n y: 594.5307239733245,\n },\n {\n x: 438.3605845653227,\n y: 594.5307239733245,\n },\n {\n x: 438.3605845653227,\n y: 660.7685646688132,\n },\n {\n x: 264.3723327748097,\n y: 660.7685646688132,\n },\n ],\n boundingBox: {\n left: 264.3723327748097,\n top: 594.5307239733245,\n right: 438.3605845653227,\n bottom: 660.7685646688132,\n },\n },\n {\n id: "block_1_Lx35WU",\n type: "text",\n content: "Noam Shazeer* Google Brain [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.983,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 479.08373644752226,\n y: 490.1169480632122,\n },\n {\n x: 643.7573955006842,\n y: 490.1169480632122,\n },\n {\n x: 643.7573955006842,\n y: 556.2343205043247,\n },\n {\n x: 479.08373644752226,\n y: 556.2343205043247,\n },\n ],\n boundingBox: {\n left: 479.08373644752226,\n top: 490.1169480632122,\n right: 643.7573955006842,\n bottom: 556.2343205043247,\n },\n },\n {\n id: "block_1_VxOJIL",\n type: "text",\n content:\n "Aidan N. Gomez* * University of Toronto [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.095,\n avgOcrConfidence: 0.875,\n },\n polygon: [\n {\n x: 489.9820146769503,\n y: 593.5908916444707,\n },\n {\n x: 708.1676900821881,\n y: 593.5908916444707,\n },\n {\n x: 708.1676900821881,\n y: 657.7173651788468,\n },\n {\n x: 489.9820146769503,\n y: 657.7173651788468,\n },\n ],\n boundingBox: {\n left: 489.9820146769503,\n top: 593.5908916444707,\n right: 708.1676900821881,\n bottom: 657.7173651788468,\n },\n },\n {\n id: "block_1_m1Gb17",\n type: "text",\n content: "Niki Parmar* Google Research [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 673.3537325893875,\n y: 490.2837284059453,\n },\n {\n x: 848.6601168221802,\n y: 490.2837284059453,\n },\n {\n x: 848.6601168221802,\n y: 556.287735673718,\n },\n {\n x: 673.3537325893875,\n y: 556.287735673718,\n },\n ],\n boundingBox: {\n left: 673.3537325893875,\n top: 490.2837284059453,\n right: 848.6601168221802,\n bottom: 556.287735673718,\n },\n },\n {\n id: "block_1_otnY8T",\n type: "text",\n content: "\\u0141ukasz Kaiser* Google Brain [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.984,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 759.3324257509552,\n y: 594.2661578816579,\n },\n {\n x: 1011.1333304078039,\n y: 594.2661578816579,\n },\n {\n x: 1011.1333304078039,\n y: 660.9298993160851,\n },\n {\n x: 759.3324257509552,\n y: 660.9298993160851,\n },\n ],\n boundingBox: {\n left: 759.3324257509552,\n top: 594.2661578816579,\n right: 1011.1333304078039,\n bottom: 660.9298993160851,\n },\n },\n {\n id: "block_1_ICaos6",\n type: "text",\n content: "Illia Polosukhin* * [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.107,\n avgOcrConfidence: 0.766,\n },\n polygon: [\n {\n x: 495.9563429338219,\n y: 697.325802423004,\n },\n {\n x: 778.5449758933407,\n y: 697.325802423004,\n },\n {\n x: 778.5449758933407,\n y: 742.1158899292909,\n },\n {\n x: 495.9563429338219,\n y: 742.1158899292909,\n },\n ],\n boundingBox: {\n left: 495.9563429338219,\n top: 697.325802423004,\n right: 778.5449758933407,\n bottom: 742.1158899292909,\n },\n },\n {\n id: "block_1_zNN0g5",\n type: "section_heading",\n content: "### Abstract",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 590.8429918498018,\n y: 804.3203170891095,\n },\n {\n x: 683.8031267597728,\n y: 804.3203170891095,\n },\n {\n x: 683.8031267597728,\n y: 823.7656170264223,\n },\n {\n x: 590.8429918498018,\n y: 823.7656170264223,\n },\n ],\n boundingBox: {\n left: 590.8429918498018,\n top: 804.3203170891095,\n right: 683.8031267597728,\n bottom: 823.7656170264223,\n },\n },\n {\n id: "block_1_Pzc7ia",\n type: "text",\n content:\n "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014 English- to-German translation task, improving over the existing best results, including ensembles, by over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training costs of the best models from the literature. We show that the Transformer generalizes well to other tasks by applying it successfully to English constituency parsing both with large and limited training data.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.987,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 298.2268201173657,\n y: 861.5167879950731,\n },\n {\n x: 978.0244980415288,\n y: 861.5167879950731,\n },\n {\n x: 978.0244980415288,\n y: 1201.6481075430274,\n },\n {\n x: 298.2268201173657,\n y: 1201.6481075430274,\n },\n ],\n boundingBox: {\n left: 298.2268201173657,\n top: 861.5167879950731,\n right: 978.0244980415288,\n bottom: 1201.6481075430274,\n },\n },\n {\n id: "block_1_bHnLKj",\n type: "text",\n content:\n "*Equal contribution. Listing order is random. Jakob proposed replacing RNNs with self-attention and started the effort to evaluate this idea. Ashish, with Illia, designed and implemented the first Transformer models and has been crucially involved in every aspect of this work. Noam proposed scaled dot-product attention, multi-head attention and the parameter-free position representation and became the other person involved in nearly every detail. Niki designed, implemented, tuned and evaluated countless model variants in our original codebase and tensor2tensor. Llion also experimented with novel model variants, was responsible for our initial codebase, and efficient inference and visualizations. Lukasz and Aidan spent countless long days designing various parts of and implementing tensor2tensor, replacing our earlier codebase, greatly improving results and massively accelerating our research.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.951,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.8755505415645,\n y: 1247.2573697082978,\n },\n {\n x: 1049.6971241749116,\n y: 1247.2573697082978,\n },\n {\n x: 1049.6971241749116,\n y: 1429.7100451476592,\n },\n {\n x: 222.8755505415645,\n y: 1429.7100451476592,\n },\n ],\n boundingBox: {\n left: 222.8755505415645,\n top: 1247.2573697082978,\n right: 1049.6971241749116,\n bottom: 1429.7100451476592,\n },\n },\n {\n id: "block_1_J3Olku",\n type: "text",\n content: "+ Work performed while at Google Brain.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.11,\n avgOcrConfidence: 0.869,\n },\n polygon: [\n {\n x: 250.1677060649343,\n y: 1434.3817888991277,\n },\n {\n x: 555.1793119333087,\n y: 1434.3817888991277,\n },\n {\n x: 555.1793119333087,\n y: 1456.532320926064,\n },\n {\n x: 250.1677060649343,\n y: 1456.532320926064,\n },\n ],\n boundingBox: {\n left: 250.1677060649343,\n top: 1434.3817888991277,\n right: 555.1793119333087,\n bottom: 1456.532320926064,\n },\n },\n {\n id: "block_1_aQsakB",\n type: "text",\n content: "#Work performed while at Google Research.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.652,\n avgOcrConfidence: 0.94,\n },\n polygon: [\n {\n x: 249.36288151427775,\n y: 1458.4100914288283,\n },\n {\n x: 582.4047478446125,\n y: 1458.4100914288283,\n },\n {\n x: 582.4047478446125,\n y: 1479.773507369192,\n },\n {\n x: 249.36288151427775,\n y: 1479.773507369192,\n },\n ],\n boundingBox: {\n left: 249.36288151427775,\n top: 1458.4100914288283,\n right: 582.4047478446125,\n bottom: 1479.773507369192,\n },\n },\n {\n id: "block_1_iKp4Ae",\n type: "footer",\n content:\n "31st Conference on Neural Information Processing Systems (NIPS 2017), Long Beach, CA, USA.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Footer",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.27405893367575,\n y: 1527.1945287374626,\n },\n {\n x: 958.2568426201814,\n y: 1527.1945287374626,\n },\n {\n x: 958.2568426201814,\n y: 1546.3855383736748,\n },\n {\n x: 224.27405893367575,\n y: 1546.3855383736748,\n },\n ],\n boundingBox: {\n left: 224.27405893367575,\n top: 1527.1945287374626,\n right: 958.2568426201814,\n bottom: 1546.3855383736748,\n },\n },\n {\n id: "block_1_zPHQaR",\n type: "text",\n content: "Jakob Uszkoreit* Google Research [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 879.2488933479699,\n y: 489.58686880240765,\n },\n {\n x: 1035.003756780694,\n y: 489.58686880240765,\n },\n {\n x: 1035.003756780694,\n y: 555.848623204052,\n },\n {\n x: 879.2488933479699,\n y: 555.848623204052,\n },\n ],\n boundingBox: {\n left: 879.2488933479699,\n top: 489.58686880240765,\n right: 1035.003756780694,\n bottom: 555.848623204052,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_2_UD1C1k",\n type: "heading",\n content: "# 1 Introduction",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 225.86025321570625,\n y: 152.1792611932396,\n },\n {\n x: 396.86960095036636,\n y: 152.1792611932396,\n },\n {\n x: 396.86960095036636,\n y: 171.96800693712737,\n },\n {\n x: 225.86025321570625,\n y: 171.96800693712737,\n },\n ],\n boundingBox: {\n left: 225.86025321570625,\n top: 152.1792611932396,\n right: 396.86960095036636,\n bottom: 171.96800693712737,\n },\n },\n {\n id: "block_2_C25o9D",\n type: "text",\n content:\n "Recurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks in particular, have been firmly established as state of the art approaches in sequence modeling and transduction problems such as language modeling and machine translation [35, 2, 5]. Numerous efforts have since continued to push the boundaries of recurrent language models and encoder-decoder architectures [38, 24, 15].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 223.64054213475134,\n y: 206.4059457563816,\n },\n {\n x: 1050.9159227357293,\n y: 206.4059457563816,\n },\n {\n x: 1050.9159227357293,\n y: 316.89823061720773,\n },\n {\n x: 223.64054213475134,\n y: 316.89823061720773,\n },\n ],\n boundingBox: {\n left: 223.64054213475134,\n top: 206.4059457563816,\n right: 1050.9159227357293,\n bottom: 316.89823061720773,\n },\n },\n {\n id: "block_2_Cw1VyU",\n type: "text",\n content:\n "Recurrent models typically factor computation along the symbol positions of the input and output sequences. Aligning the positions to steps in computation time, they generate a sequence of hidden states ht, as a function of the previous hidden state ht-1 and the input for position t. This inherently sequential nature precludes parallelization within training examples, which becomes critical at longer sequence lengths, as memory constraints limit batching across examples. Recent work has achieved significant improvements in computational efficiency through factorization tricks [21] and conditional computation [32], while also improving model performance in case of the latter. The fundamental constraint of sequential computation, however, remains.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.9,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.69928568819142,\n y: 331.227654822787,\n },\n {\n x: 1049.6158961832089,\n y: 331.227654822787,\n },\n {\n x: 1049.6158961832089,\n y: 511.80734250061494,\n },\n {\n x: 223.69928568819142,\n y: 511.80734250061494,\n },\n ],\n boundingBox: {\n left: 223.69928568819142,\n top: 331.227654822787,\n right: 1049.6158961832089,\n bottom: 511.80734250061494,\n },\n },\n {\n id: "block_2_FR7zlH",\n type: "text",\n content:\n "Attention mechanisms have become an integral part of compelling sequence modeling and transduc- tion models in various tasks, allowing modeling of dependencies without regard to their distance in the input or output sequences [2, 19]. In all but a few cases [27], however, such attention mechanisms are used in conjunction with a recurrent network.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.959,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.38852708357095,\n y: 525.5238181666324,\n },\n {\n x: 1052.1732525233804,\n y: 525.5238181666324,\n },\n {\n x: 1052.1732525233804,\n y: 613.7107948647406,\n },\n {\n x: 223.38852708357095,\n y: 613.7107948647406,\n },\n ],\n boundingBox: {\n left: 223.38852708357095,\n top: 525.5238181666324,\n right: 1052.1732525233804,\n bottom: 613.7107948647406,\n },\n },\n {\n id: "block_2_ZyhlFh",\n type: "text",\n content:\n "In this work we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output. The Transformer allows for significantly more parallelization and can reach a new state of the art in translation quality after being trained for as little as twelve hours on eight P100 GPUs.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.991,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.20226126343667,\n y: 627.2328828797304,\n },\n {\n x: 1052.7354108156078,\n y: 627.2328828797304,\n },\n {\n x: 1052.7354108156078,\n y: 716.0174654623619,\n },\n {\n x: 223.20226126343667,\n y: 716.0174654623619,\n },\n ],\n boundingBox: {\n left: 223.20226126343667,\n top: 627.2328828797304,\n right: 1052.7354108156078,\n bottom: 716.0174654623619,\n },\n },\n {\n id: "block_2_MZBXjP",\n type: "section_heading",\n content: "### 2 Background",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.22355178498873,\n y: 757.4257287333783,\n },\n {\n x: 392.45446198178036,\n y: 757.4257287333783,\n },\n {\n x: 392.45446198178036,\n y: 781.2853567654029,\n },\n {\n x: 224.22355178498873,\n y: 781.2853567654029,\n },\n ],\n boundingBox: {\n left: 224.22355178498873,\n top: 757.4257287333783,\n right: 392.45446198178036,\n bottom: 781.2853567654029,\n },\n },\n {\n id: "block_2_JeOnOk",\n type: "text",\n content:\n "The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU [16], ByteNet [18] and ConvS2S [9], all of which use convolutional neural networks as basic building block, computing hidden representations in parallel for all input and output positions. In these models, the number of operations required to relate signals from two arbitrary input or output positions grows in the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes it more difficult to learn dependencies between distant positions [12]. In the Transformer this is reduced to a constant number of operations, albeit at the cost of reduced effective resolution due to averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as described in section 3.2.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.893,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.30221050847186,\n y: 810.9956032315591,\n },\n {\n x: 1051.187440078624,\n y: 810.9956032315591,\n },\n {\n x: 1051.187440078624,\n y: 1010.7095232511822,\n },\n {\n x: 223.30221050847186,\n y: 1010.7095232511822,\n },\n ],\n boundingBox: {\n left: 223.30221050847186,\n top: 810.9956032315591,\n right: 1051.187440078624,\n bottom: 1010.7095232511822,\n },\n },\n {\n id: "block_2_tEzlrD",\n type: "text",\n content:\n "Self-attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence. Self-attention has been used successfully in a variety of tasks including reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations [4, 27, 28, 22].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.984,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.00045882176306,\n y: 1028.0413251030714,\n },\n {\n x: 1051.4467448213675,\n y: 1028.0413251030714,\n },\n {\n x: 1051.4467448213675,\n y: 1116.9915041815966,\n },\n {\n x: 224.00045882176306,\n y: 1116.9915041815966,\n },\n ],\n boundingBox: {\n left: 224.00045882176306,\n top: 1028.0413251030714,\n right: 1051.4467448213675,\n bottom: 1116.9915041815966,\n },\n },\n {\n id: "block_2_AFJ4ch",\n type: "text",\n content:\n "End-to-end memory networks are based on a recurrent attention mechanism instead of sequence- aligned recurrence and have been shown to perform well on simple-language question answering and language modeling tasks [34].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.05524984763485,\n y: 1129.9793457949072,\n },\n {\n x: 1052.8165441359918,\n y: 1129.9793457949072,\n },\n {\n x: 1052.8165441359918,\n y: 1196.1117767678168,\n },\n {\n x: 224.05524984763485,\n y: 1196.1117767678168,\n },\n ],\n boundingBox: {\n left: 224.05524984763485,\n top: 1129.9793457949072,\n right: 1052.8165441359918,\n bottom: 1196.1117767678168,\n },\n },\n {\n id: "block_2_CBbJP3",\n type: "text",\n content:\n "To the best of our knowledge, however, the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence- aligned RNNs or convolution. In the following sections, we will describe the Transformer, motivate self-attention and discuss its advantages over models such as [17, 18] and [9].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.898,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 222.86987026242443,\n y: 1210.5673043387276,\n },\n {\n x: 1052.2374396776631,\n y: 1210.5673043387276,\n },\n {\n x: 1052.2374396776631,\n y: 1298.352294004053,\n },\n {\n x: 222.86987026242443,\n y: 1298.352294004053,\n },\n ],\n boundingBox: {\n left: 222.86987026242443,\n top: 1210.5673043387276,\n right: 1052.2374396776631,\n bottom: 1298.352294004053,\n },\n },\n {\n id: "block_2_RlRHBW",\n type: "section_heading",\n content: "### 3 Model Architecture",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.20267675914906,\n y: 1339.2827093368187,\n },\n {\n x: 470.2105250671832,\n y: 1339.2827093368187,\n },\n {\n x: 470.2105250671832,\n y: 1359.0320211424864,\n },\n {\n x: 224.20267675914906,\n y: 1359.0320211424864,\n },\n ],\n boundingBox: {\n left: 224.20267675914906,\n top: 1339.2827093368187,\n right: 470.2105250671832,\n bottom: 1359.0320211424864,\n },\n },\n {\n id: "block_2_OhVaOm",\n type: "text",\n content:\n "Most competitive neural sequence transduction models have an encoder-decoder structure [5, 2, 35]. Here, the encoder maps an input sequence of symbol representations (x1, ... , In) to a sequence of continuous representations z = (Z1, ... , Zn). Given z, the decoder then generates an output sequence (31, ... , ym) of symbols one element at a time. At each step the model is auto-regressive [10], consuming the previously generated symbols as additional input when generating the next.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.619,\n avgOcrConfidence: 0.969,\n },\n polygon: [\n {\n x: 223.9033023806384,\n y: 1394.2295871247027,\n },\n {\n x: 1051.703398767179,\n y: 1394.2295871247027,\n },\n {\n x: 1051.703398767179,\n y: 1505.850527885265,\n },\n {\n x: 223.9033023806384,\n y: 1505.850527885265,\n },\n ],\n boundingBox: {\n left: 223.9033023806384,\n top: 1394.2295871247027,\n right: 1051.703398767179,\n bottom: 1505.850527885265,\n },\n },\n {\n id: "block_2_MzhUlf",\n type: "page_number",\n content: "2",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 631.4816022441336,\n y: 1547.6769732138268,\n },\n {\n x: 642.0810031194757,\n y: 1547.6769732138268,\n },\n {\n x: 642.0810031194757,\n y: 1563.2578182363868,\n },\n {\n x: 631.4816022441336,\n y: 1563.2578182363868,\n },\n ],\n boundingBox: {\n left: 631.4816022441336,\n top: 1547.6769732138268,\n right: 642.0810031194757,\n bottom: 1563.2578182363868,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_3_afwbz8",\n type: "figure",\n content:\n \'<figure type="diagram">\\nOutput Probabilities\\n\\nSoftmax\\n\\nLinear\\n\\nAdd & Norm Feed Forward\\n\\nAdd & Norm\\n\\nAdd & Norm\\n\\nMulti-Head Feed Attention Forward Nx\\n\\nAdd & Norm\\n\\nNx Add & Norm\\n\\nMasked Multi-Head Multi-Head Attention Attention\\n\\nPositional Positional Encoding Encoding Input Output Embedding Embedding\\n\\nInputs Outputs (shifted right)\\n<caption>Transformer Architecture Diagram\\n\\nLeft Side: Encoder (Nx)\\n- Inputs\\n\\u2193\\n- Input Embedding\\n\\u2193\\n- Positional Encoding (added to Input Embedding)\\n\\u2193\\n- Multi-Head Attention\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Feed Forward\\n\\u2193\\n- Add & Norm\\n\\nRight Side: Decoder (Nx)\\n- Outputs (shifted right)\\n\\u2193\\n- Output Embedding\\n\\u2193\\n- Positional Encoding (added to Output Embedding)\\n\\u2193\\n- Masked Multi-Head Attention\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Multi-Head Attention (receives input from Encoder\\\'s Add & Norm)\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Feed Forward\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Linear\\n\\u2193\\n- Softmax\\n\\u2193\\n- Output Probabilities</caption>\\n</figure>\',\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.868,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 409.83791490540887,\n y: 150.86351013900642,\n },\n {\n x: 863.1759754932709,\n y: 150.86351013900642,\n },\n {\n x: 863.1759754932709,\n y: 821.7723977798806,\n },\n {\n x: 409.83791490540887,\n y: 821.7723977798806,\n },\n ],\n boundingBox: {\n left: 409.83791490540887,\n top: 150.86351013900642,\n right: 863.1759754932709,\n bottom: 821.7723977798806,\n },\n },\n {\n id: "block_3_1WIk1S",\n type: "text",\n content: "Figure 1: The Transformer - model architecture.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 436.4703770101505,\n y: 843.2910397178248,\n },\n {\n x: 836.1937028648209,\n y: 843.2910397178248,\n },\n {\n x: 836.1937028648209,\n y: 863.7018851373429,\n },\n {\n x: 436.4703770101505,\n y: 863.7018851373429,\n },\n ],\n boundingBox: {\n left: 436.4703770101505,\n top: 843.2910397178248,\n right: 836.1937028648209,\n bottom: 863.7018851373429,\n },\n },\n {\n id: "block_3_jyPEOL",\n type: "text",\n content:\n "The Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1, respectively.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.973,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.86804783953366,\n y: 910.1303693154701,\n },\n {\n x: 1051.9256870241932,\n y: 910.1303693154701,\n },\n {\n x: 1051.9256870241932,\n y: 977.3362178945899,\n },\n {\n x: 222.86804783953366,\n y: 977.3362178945899,\n },\n ],\n boundingBox: {\n left: 222.86804783953366,\n top: 910.1303693154701,\n right: 1051.9256870241932,\n bottom: 977.3362178945899,\n },\n },\n {\n id: "block_3_nEQfm1",\n type: "section_heading",\n content: "### 3.1 Encoder and Decoder Stacks",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.72352154585568,\n y: 1007.3903008367782,\n },\n {\n x: 527.4041196725664,\n y: 1007.3903008367782,\n },\n {\n x: 527.4041196725664,\n y: 1023.9329030316575,\n },\n {\n x: 223.72352154585568,\n y: 1023.9329030316575,\n },\n ],\n boundingBox: {\n left: 223.72352154585568,\n top: 1007.3903008367782,\n right: 527.4041196725664,\n bottom: 1023.9329030316575,\n },\n },\n {\n id: "block_3_W2U9b2",\n type: "text",\n content:\n "Encoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position- wise fully connected feed-forward network. We employ a residual connection [11] around each of the two sub-layers, followed by layer normalization [1]. That is, the output of each sub-layer is LayerNorm(x + Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer itself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding layers, produce outputs of dimension dmodel = 512.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.657,\n avgOcrConfidence: 0.984,\n },\n polygon: [\n {\n x: 223.8025010937322,\n y: 1048.091523421438,\n },\n {\n x: 1053.5889674277203,\n y: 1048.091523421438,\n },\n {\n x: 1053.5889674277203,\n y: 1206.3018568225373,\n },\n {\n x: 223.8025010937322,\n y: 1206.3018568225373,\n },\n ],\n boundingBox: {\n left: 223.8025010937322,\n top: 1048.091523421438,\n right: 1053.5889674277203,\n bottom: 1206.3018568225373,\n },\n },\n {\n id: "block_3_8wxg0F",\n type: "text",\n content:\n "Decoder: The decoder is also composed of a stack of N = 6 identical layers. In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head attention over the output of the encoder stack. Similar to the encoder, we employ residual connections around each of the sub-layers, followed by layer normalization. We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position i can depend only on the known outputs at positions less than i.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.633,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 224.16407452882643,\n y: 1233.3413921729066,\n },\n {\n x: 1049.721170689938,\n y: 1233.3413921729066,\n },\n {\n x: 1049.721170689938,\n y: 1391.0596241198086,\n },\n {\n x: 224.16407452882643,\n y: 1391.0596241198086,\n },\n ],\n boundingBox: {\n left: 224.16407452882643,\n top: 1233.3413921729066,\n right: 1049.721170689938,\n bottom: 1391.0596241198086,\n },\n },\n {\n id: "block_3_i0stGS",\n type: "section_heading",\n content: "### 3.2 Attention",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 224.0832962258889,\n y: 1421.7722100279386,\n },\n {\n x: 354.57085797386446,\n y: 1421.7722100279386,\n },\n {\n x: 354.57085797386446,\n y: 1437.668053017523,\n },\n {\n x: 224.0832962258889,\n y: 1437.668053017523,\n },\n ],\n boundingBox: {\n left: 224.0832962258889,\n top: 1421.7722100279386,\n right: 354.57085797386446,\n bottom: 1437.668053017523,\n },\n },\n {\n id: "block_3_LwJLS3",\n type: "text",\n content:\n "An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.986,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.38670466068018,\n y: 1462.3713376611695,\n },\n {\n x: 1052.432178580848,\n y: 1462.3713376611695,\n },\n {\n x: 1052.432178580848,\n y: 1506.3117546138906,\n },\n {\n x: 223.38670466068018,\n y: 1506.3117546138906,\n },\n ],\n boundingBox: {\n left: 223.38670466068018,\n top: 1462.3713376611695,\n right: 1052.432178580848,\n bottom: 1506.3117546138906,\n },\n },\n {\n id: "block_3_gqT8MC",\n type: "page_number",\n content: "3",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.997,\n avgOcrConfidence: 0.997,\n },\n polygon: [\n {\n x: 632.2706403523466,\n y: 1547.236487481827,\n },\n {\n x: 642.0801037419451,\n y: 1547.236487481827,\n },\n {\n x: 642.0801037419451,\n y: 1562.977578012567,\n },\n {\n x: 632.2706403523466,\n y: 1562.977578012567,\n },\n ],\n boundingBox: {\n left: 632.2706403523466,\n top: 1547.236487481827,\n right: 642.0801037419451,\n bottom: 1562.977578012567,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_4_PplY2k",\n type: "header",\n content: "Scaled Dot-Product Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Header",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 307.9120037329458,\n y: 148.57123934236685,\n },\n {\n x: 554.1308270753735,\n y: 148.57123934236685,\n },\n {\n x: 554.1308270753735,\n y: 164.4924521697195,\n },\n {\n x: 307.9120037329458,\n y: 164.4924521697195,\n },\n ],\n boundingBox: {\n left: 307.9120037329458,\n top: 148.57123934236685,\n right: 554.1308270753735,\n bottom: 164.4924521697195,\n },\n },\n {\n id: "block_4_TZACGH",\n type: "text",\n content: "Multi-Head Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 756.6973442578839,\n y: 148.30866211339045,\n },\n {\n x: 937.5759876557511,\n y: 148.30866211339045,\n },\n {\n x: 937.5759876557511,\n y: 164.44492071911804,\n },\n {\n x: 756.6973442578839,\n y: 164.44492071911804,\n },\n ],\n boundingBox: {\n left: 756.6973442578839,\n top: 148.30866211339045,\n right: 937.5759876557511,\n bottom: 164.44492071911804,\n },\n },\n {\n id: "block_4_yRQL9Y",\n type: "figure",\n content:\n \'<figure type="diagram">\\n1 MatMul\\n\\n1 SoftMax 1 Mask (opt.) 1 Scale 1 MatMul 1 1 Q K V\\n<caption>Scaled Dot-Product Attention Diagram\\n\\nInputs: Q, K, V\\n\\n1. MatMul (Q, K)\\n \\u2193\\n2. Scale\\n \\u2193\\n3. Mask (opt.)\\n \\u2193\\n4. SoftMax\\n \\u2193\\n5. MatMul (Result of SoftMax, V)\\n \\u2193\\nOutput</caption>\\n</figure>\',\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.226,\n avgOcrConfidence: 0.815,\n },\n polygon: [\n {\n x: 364.7714322500855,\n y: 195.77549835434533,\n },\n {\n x: 497.28713766501767,\n y: 195.77549835434533,\n },\n {\n x: 497.28713766501767,\n y: 457.62115733784844,\n },\n {\n x: 364.7714322500855,\n y: 457.62115733784844,\n },\n ],\n boundingBox: {\n left: 364.7714322500855,\n top: 195.77549835434533,\n right: 497.28713766501767,\n bottom: 457.62115733784844,\n },\n },\n {\n id: "block_4_goCdts",\n type: "figure",\n content:\n \'<figure type="diagram">\\nLinear\\n\\nConcat\\n\\nScaled Dot-Product\\n\\nh\\n\\nAttention\\n\\nLinear Linear Linear\\n\\nV K Q\\n<caption>Multi-Head Attention\\n\\nInputs: V, K, Q\\n\\u2193\\nLinear (x3) \\u2192 Scaled Dot-Product Attention (h heads)\\n\\u2193\\nConcat\\n\\u2193\\nLinear</caption>\\n</figure>\',\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.981,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 723.0441991430129,\n y: 171.2063080421964,\n },\n {\n x: 971.0292342805515,\n y: 171.2063080421964,\n },\n {\n x: 971.0292342805515,\n y: 495.8982404264292,\n },\n {\n x: 723.0441991430129,\n y: 495.8982404264292,\n },\n ],\n boundingBox: {\n left: 723.0441991430129,\n top: 171.2063080421964,\n right: 971.0292342805515,\n bottom: 495.8982404264292,\n },\n },\n {\n id: "block_4_ZQ6XHX",\n type: "text",\n content:\n "Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.991,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.32437673972473,\n y: 572.2067347074809,\n },\n {\n x: 1050.060662039875,\n y: 572.2067347074809,\n },\n {\n x: 1050.060662039875,\n y: 615.706381804961,\n },\n {\n x: 224.32437673972473,\n y: 615.706381804961,\n },\n ],\n boundingBox: {\n left: 224.32437673972473,\n top: 572.2067347074809,\n right: 1050.060662039875,\n bottom: 615.706381804961,\n },\n },\n {\n id: "block_4_seZO33",\n type: "text",\n content:\n "of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.44408862260138,\n y: 661.3754045586836,\n },\n {\n x: 1049.3653012018135,\n y: 661.3754045586836,\n },\n {\n x: 1049.3653012018135,\n y: 705.0281940833071,\n },\n {\n x: 224.44408862260138,\n y: 705.0281940833071,\n },\n ],\n boundingBox: {\n left: 224.44408862260138,\n top: 661.3754045586836,\n right: 1049.3653012018135,\n bottom: 705.0281940833071,\n },\n },\n {\n id: "block_4_CMgLHk",\n type: "section_heading",\n content: "### 3.2.1 Scaled Dot-Product Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.53467593227862,\n y: 732.4767248397483,\n },\n {\n x: 549.2687448097842,\n y: 732.4767248397483,\n },\n {\n x: 549.2687448097842,\n y: 748.6887496431967,\n },\n {\n x: 223.53467593227862,\n y: 748.6887496431967,\n },\n ],\n boundingBox: {\n left: 223.53467593227862,\n top: 732.4767248397483,\n right: 549.2687448097842,\n bottom: 748.6887496431967,\n },\n },\n {\n id: "block_4_fmfLoy",\n type: "text",\n content:\n \'We call our particular attention "Scaled Dot-Product Attention" (Figure 2). The input consists of queries and keys of dimension dk, and values of dimension dy. We compute the dot products of the\\n\\nquery with all keys, divide each by Vdk, and apply a softmafunction to obtain the weights on the [x]\\n\\nvalues.\',\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.594,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 223.39593511428276,\n y: 771.1101458269851,\n },\n {\n x: 1051.4275265436104,\n y: 771.1101458269851,\n },\n {\n x: 1051.4275265436104,\n y: 856.1295272138783,\n },\n {\n x: 223.39593511428276,\n y: 856.1295272138783,\n },\n ],\n boundingBox: {\n left: 223.39593511428276,\n top: 771.1101458269851,\n right: 1051.4275265436104,\n bottom: 856.1295272138783,\n },\n },\n {\n id: "block_4_cDuW6h",\n type: "text",\n content:\n "In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix Q. The keys and values are also packed together into matrices K and V. We compute the matrix of outputs as:",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.976,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.08788778486044,\n y: 873.4355685585424,\n },\n {\n x: 1050.3812191260122,\n y: 873.4355685585424,\n },\n {\n x: 1050.3812191260122,\n y: 938.6725377821385,\n },\n {\n x: 224.08788778486044,\n y: 938.6725377821385,\n },\n ],\n boundingBox: {\n left: 224.08788778486044,\n top: 873.4355685585424,\n right: 1050.3812191260122,\n bottom: 938.6725377821385,\n },\n },\n {\n id: "block_4_VaSWNE",\n type: "text",\n content: "QKT Attention(Q, K, V) = softmax( V Vdk",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.961,\n },\n polygon: [\n {\n x: 458.52888900868214,\n y: 968.9788274549901,\n },\n {\n x: 816.6205023327013,\n y: 968.9788274549901,\n },\n {\n x: 816.6205023327013,\n y: 1021.9395890773686,\n },\n {\n x: 458.52888900868214,\n y: 1021.9395890773686,\n },\n ],\n boundingBox: {\n left: 458.52888900868214,\n top: 968.9788274549901,\n right: 816.6205023327013,\n bottom: 1021.9395890773686,\n },\n },\n {\n id: "block_4_Wtl7xI",\n type: "text",\n content: "(1)",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 1026.9459968065694,\n y: 986.4570474839747,\n },\n {\n x: 1051.0514920645387,\n y: 986.4570474839747,\n },\n {\n x: 1051.0514920645387,\n y: 1005.8566982871607,\n },\n {\n x: 1026.9459968065694,\n y: 1005.8566982871607,\n },\n ],\n boundingBox: {\n left: 1026.9459968065694,\n top: 986.4570474839747,\n right: 1051.0514920645387,\n bottom: 1005.8566982871607,\n },\n },\n {\n id: "block_4_HVInAp",\n type: "text",\n content:\n "The two most commonly used attention functions are additive attention [2], and dot-product (multi- plicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor\\n\\nof . Additive attention computes the compatibility function using a feed-forward network with [x] Vdk\\n\\na single hidden layer. While the two are similar in theoretical complexity, dot-product attention is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.098,\n avgOcrConfidence: 0.981,\n },\n polygon: [\n {\n x: 223.11696240501684,\n y: 1041.6009173859331,\n },\n {\n x: 1052.8067929901345,\n y: 1041.6009173859331,\n },\n {\n x: 1052.8067929901345,\n y: 1180.0422397699572,\n },\n {\n x: 223.11696240501684,\n y: 1180.0422397699572,\n },\n ],\n boundingBox: {\n left: 223.11696240501684,\n top: 1041.6009173859331,\n right: 1052.8067929901345,\n bottom: 1180.0422397699572,\n },\n },\n {\n id: "block_4_6NHlzf",\n type: "text",\n content:\n "While for small values of dk the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of dk [3]. We suspect that for large values of dk, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients 4. To counteract this effect, we scale the dot products by.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.58,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 223.18699551324775,\n y: 1194.0708248167111,\n },\n {\n x: 1050.8364934990875,\n y: 1194.0708248167111,\n },\n {\n x: 1050.8364934990875,\n y: 1289.5664457163416,\n },\n {\n x: 223.18699551324775,\n y: 1289.5664457163416,\n },\n ],\n boundingBox: {\n left: 223.18699551324775,\n top: 1194.0708248167111,\n right: 1050.8364934990875,\n bottom: 1289.5664457163416,\n },\n },\n {\n id: "block_4_4VWmvI",\n type: "section_heading",\n content: "### 3.2.2 Multi-Head Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.5976323594142,\n y: 1315.4335938647278,\n },\n {\n x: 479.8474026422431,\n y: 1315.4335938647278,\n },\n {\n x: 479.8474026422431,\n y: 1331.4542616650574,\n },\n {\n x: 223.5976323594142,\n y: 1331.4542616650574,\n },\n ],\n boundingBox: {\n left: 223.5976323594142,\n top: 1315.4335938647278,\n right: 479.8474026422431,\n bottom: 1331.4542616650574,\n },\n },\n {\n id: "block_4_n7aPpb",\n type: "text",\n content:\n "Instead of performing a single attention function with dmodel-dimensional keys, values and queries, we found it beneficial to linearly project the queries, keys and values h times with different, learned linear projections to dk, dk and dy dimensions, respectively. On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding dy-dimensional",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.619,\n avgOcrConfidence: 0.979,\n },\n polygon: [\n {\n x: 223.83094982509195,\n y: 1354.33461159154,\n },\n {\n x: 1052.0098498267848,\n y: 1354.33461159154,\n },\n {\n x: 1052.0098498267848,\n y: 1442.8801044664883,\n },\n {\n x: 223.83094982509195,\n y: 1442.8801044664883,\n },\n ],\n boundingBox: {\n left: 223.83094982509195,\n top: 1354.33461159154,\n right: 1052.0098498267848,\n bottom: 1442.8801044664883,\n },\n },\n {\n id: "block_4_rfqNPC",\n type: "text",\n content:\n "4To illustrate why the dot products get large, assume that the components of q and k are independent random variables with mean 0 and variance 1. Then their dot product, q \\u00b7 k = >i=1 qiki, has mean 0 and variance dk-",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.105,\n avgOcrConfidence: 0.921,\n },\n polygon: [\n {\n x: 224.42529636577967,\n y: 1459.9841341864794,\n },\n {\n x: 1049.4534401998033,\n y: 1459.9841341864794,\n },\n {\n x: 1049.4534401998033,\n y: 1506.815978659723,\n },\n {\n x: 224.42529636577967,\n y: 1506.815978659723,\n },\n ],\n boundingBox: {\n left: 224.42529636577967,\n top: 1459.9841341864794,\n right: 1049.4534401998033,\n bottom: 1506.815978659723,\n },\n },\n {\n id: "block_4_35BhDQ",\n type: "page_number",\n content: "4",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.996,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 631.2688757903385,\n y: 1548.1330857241064,\n },\n {\n x: 642.0564832478544,\n y: 1548.1330857241064,\n },\n {\n x: 642.0564832478544,\n y: 1562.0727401962854,\n },\n {\n x: 631.2688757903385,\n y: 1562.0727401962854,\n },\n ],\n boundingBox: {\n left: 631.2688757903385,\n top: 1548.1330857241064,\n right: 642.0564832478544,\n bottom: 1562.0727401962854,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_5_Zc8VSW",\n type: "text",\n content:\n "output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure 2.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.988,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.67903916853186,\n y: 155.68632458564932,\n },\n {\n x: 1049.4719957783275,\n y: 155.68632458564932,\n },\n {\n x: 1049.4719957783275,\n y: 199.30535079841326,\n },\n {\n x: 224.67903916853186,\n y: 199.30535079841326,\n },\n ],\n boundingBox: {\n left: 224.67903916853186,\n top: 155.68632458564932,\n right: 1049.4719957783275,\n bottom: 199.30535079841326,\n },\n },\n {\n id: "block_5_P72mUL",\n type: "text",\n content:\n "Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 224.58133836732293,\n y: 212.29537068990837,\n },\n {\n x: 1049.5524663994781,\n y: 212.29537068990837,\n },\n {\n x: 1049.5524663994781,\n y: 255.9039790504857,\n },\n {\n x: 224.58133836732293,\n y: 255.9039790504857,\n },\n ],\n boundingBox: {\n left: 224.58133836732293,\n top: 212.29537068990837,\n right: 1049.5524663994781,\n bottom: 255.9039790504857,\n },\n },\n {\n id: "block_5_zTpvNY",\n type: "text",\n content:\n "MultiHead(Q,K,V)=Concat(head1, ... , headh)W\\u00ba where head; = Attention(Qw?, KWK,VW)",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.581,\n avgOcrConfidence: 0.796,\n },\n polygon: [\n {\n x: 388.73733464818804,\n y: 302.5467395065422,\n },\n {\n x: 883.3280911410811,\n y: 302.5467395065422,\n },\n {\n x: 883.3280911410811,\n y: 364.6030674267532,\n },\n {\n x: 388.73733464818804,\n y: 364.6030674267532,\n },\n ],\n boundingBox: {\n left: 388.73733464818804,\n top: 302.5467395065422,\n right: 883.3280911410811,\n bottom: 364.6030674267532,\n },\n },\n {\n id: "block_5_cOSQOc",\n type: "text",\n content:\n "Where the projections are parameter matrices Wo E Rdmodel X dk , WK \\u20ac Rdmodel X dk , WY \\u20ac Rdmodel X dy and WO E Rhdy Xdmodel",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.252,\n avgOcrConfidence: 0.682,\n },\n polygon: [\n {\n x: 223.51567066498916,\n y: 424.5787134959285,\n },\n {\n x: 1047.1388211215499,\n y: 424.5787134959285,\n },\n {\n x: 1047.1388211215499,\n y: 472.1556711698833,\n },\n {\n x: 223.51567066498916,\n y: 472.1556711698833,\n },\n ],\n boundingBox: {\n left: 223.51567066498916,\n top: 424.5787134959285,\n right: 1047.1388211215499,\n bottom: 472.1556711698833,\n },\n },\n {\n id: "block_5_4oR3J2",\n type: "text",\n content:\n "In this work we employ h = 8 parallel attention layers, or heads. For each of these we use dk = dy = dmodel/h = 64. Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.557,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 223.83189653828197,\n y: 488.323372747665,\n },\n {\n x: 1049.9097559573877,\n y: 488.323372747665,\n },\n {\n x: 1049.9097559573877,\n y: 555.0531728357302,\n },\n {\n x: 223.83189653828197,\n y: 555.0531728357302,\n },\n ],\n boundingBox: {\n left: 223.83189653828197,\n top: 488.323372747665,\n right: 1049.9097559573877,\n bottom: 555.0531728357302,\n },\n },\n {\n id: "block_5_oGR7Tp",\n type: "section_heading",\n content: "### 3.2.3 Applications of Attention in our Model",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.9031130380004,\n y: 584.1135347409356,\n },\n {\n x: 629.6546824657133,\n y: 584.1135347409356,\n },\n {\n x: 629.6546824657133,\n y: 605.02614180486,\n },\n {\n x: 223.9031130380004,\n y: 605.02614180486,\n },\n ],\n boundingBox: {\n left: 223.9031130380004,\n top: 584.1135347409356,\n right: 629.6546824657133,\n bottom: 605.02614180486,\n },\n },\n {\n id: "block_5_b34egv",\n type: "text",\n content:\n "The Transformer uses multi-head attention in three different ways:",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.3985859112148,\n y: 623.9660812033746,\n },\n {\n x: 775.7513199409428,\n y: 623.9660812033746,\n },\n {\n x: 775.7513199409428,\n y: 644.7702005429376,\n },\n {\n x: 223.3985859112148,\n y: 644.7702005429376,\n },\n ],\n boundingBox: {\n left: 223.3985859112148,\n top: 623.9660812033746,\n right: 775.7513199409428,\n bottom: 644.7702005429376,\n },\n },\n {\n id: "block_5_NSYaLO",\n type: "text",\n content:\n \'\\u00b7 In "encoder-decoder attention" layers, the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder. This allows every position in the decoder to attend over all positions in the input sequence. This mimics the typical encoder-decoder attention mechanisms in sequence-to-sequence models such as [38, 2, 9].\',\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.586,\n avgOcrConfidence: 0.984,\n },\n polygon: [\n {\n x: 281.7719981618171,\n y: 667.4162908568419,\n },\n {\n x: 1052.1352893244612,\n y: 667.4162908568419,\n },\n {\n x: 1052.1352893244612,\n y: 778.3123385207098,\n },\n {\n x: 281.7719981618171,\n y: 778.3123385207098,\n },\n ],\n boundingBox: {\n left: 281.7719981618171,\n top: 667.4162908568419,\n right: 1052.1352893244612,\n bottom: 778.3123385207098,\n },\n },\n {\n id: "block_5_ZbEUX6",\n type: "text",\n content:\n "\\u00b7 The encoder contains self-attention layers. In a self-attention layer all of the keys, values and queries come from the same place, in this case, the output of the previous layer in the encoder. Each position in the encoder can attend to all positions in the previous layer of the encoder.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.407,\n avgOcrConfidence: 0.983,\n },\n polygon: [\n {\n x: 282.1731915439132,\n y: 791.5420637202442,\n },\n {\n x: 1049.6795153095775,\n y: 791.5420637202442,\n },\n {\n x: 1049.6795153095775,\n y: 876.9418387735697,\n },\n {\n x: 282.1731915439132,\n y: 876.9418387735697,\n },\n ],\n boundingBox: {\n left: 282.1731915439132,\n top: 791.5420637202442,\n right: 1049.6795153095775,\n bottom: 876.9418387735697,\n },\n },\n {\n id: "block_5_wkxEH8",\n type: "text",\n content:\n "\\u00b7 Similarly, self-attention layers in the decoder allow each position in the decoder to attend to all positions in the decoder up to and including that position. We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to -oo) all values in the input of the softmax which correspond to illegal connections. See Figure 2.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.543,\n avgOcrConfidence: 0.985,\n },\n polygon: [\n {\n x: 281.12820952478114,\n y: 893.687589086088,\n },\n {\n x: 1049.8325041610829,\n y: 893.687589086088,\n },\n {\n x: 1049.8325041610829,\n y: 1005.0602061336201,\n },\n {\n x: 281.12820952478114,\n y: 1005.0602061336201,\n },\n ],\n boundingBox: {\n left: 281.12820952478114,\n top: 893.687589086088,\n right: 1049.8325041610829,\n bottom: 1005.0602061336201,\n },\n },\n {\n id: "block_5_vVMF0e",\n type: "section_heading",\n content: "### 3.3 Position-wise Feed-Forward Networks",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.59919443617773,\n y: 1037.180243872162,\n },\n {\n x: 609.3837069768975,\n y: 1037.180243872162,\n },\n {\n x: 609.3837069768975,\n y: 1053.935843790384,\n },\n {\n x: 223.59919443617773,\n y: 1053.935843790384,\n },\n ],\n boundingBox: {\n left: 223.59919443617773,\n top: 1037.180243872162,\n right: 609.3837069768975,\n bottom: 1053.935843790384,\n },\n },\n {\n id: "block_5_WtW3Xc",\n type: "text",\n content:\n "In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forward network, which is applied to each position separately and identically. This consists of two linear transformations with a ReLU activation in between.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.986,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.937928415563,\n y: 1079.1571798109471,\n },\n {\n x: 1049.736412772297,\n y: 1079.1571798109471,\n },\n {\n x: 1049.736412772297,\n y: 1142.9025967246607,\n },\n {\n x: 223.937928415563,\n y: 1142.9025967246607,\n },\n ],\n boundingBox: {\n left: 223.937928415563,\n top: 1079.1571798109471,\n right: 1049.736412772297,\n bottom: 1142.9025967246607,\n },\n },\n {\n id: "block_5_TCB4QK",\n type: "text",\n content: "FFN(x)=max(0,xW1+b1)W2+b2",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.668,\n avgOcrConfidence: 0.668,\n },\n polygon: [\n {\n x: 471.6477776965956,\n y: 1184.1576702146604,\n },\n {\n x: 801.1487473536581,\n y: 1184.1576702146604,\n },\n {\n x: 801.1487473536581,\n y: 1206.444581397494,\n },\n {\n x: 471.6477776965956,\n y: 1206.444581397494,\n },\n ],\n boundingBox: {\n left: 471.6477776965956,\n top: 1184.1576702146604,\n right: 801.1487473536581,\n bottom: 1206.444581397494,\n },\n },\n {\n id: "block_5_olGJjx",\n type: "text",\n content: "(2)",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.997,\n avgOcrConfidence: 0.997,\n },\n polygon: [\n {\n x: 1026.9936164800267,\n y: 1185.5856736262042,\n },\n {\n x: 1051.1806237436558,\n y: 1185.5856736262042,\n },\n {\n x: 1051.1806237436558,\n y: 1204.3962422421102,\n },\n {\n x: 1026.9936164800267,\n y: 1204.3962422421102,\n },\n ],\n boundingBox: {\n left: 1026.9936164800267,\n top: 1185.5856736262042,\n right: 1051.1806237436558,\n bottom: 1204.3962422421102,\n },\n },\n {\n id: "block_5_KTjDsL",\n type: "text",\n content:\n "While the linear transformations are the same across different positions, they use different parameters from layer to layer. Another way of describing this is as two convolutions with kernel size 1. The dimensionality of input and output is dmodel = 512, and the inner-layer has dimensionality dff =2048.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.881,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 222.78797957148865,\n y: 1230.1093008858818,\n },\n {\n x: 1052.541145269018,\n y: 1230.1093008858818,\n },\n {\n x: 1052.541145269018,\n y: 1320.3967533541802,\n },\n {\n x: 222.78797957148865,\n y: 1320.3967533541802,\n },\n ],\n boundingBox: {\n left: 222.78797957148865,\n top: 1230.1093008858818,\n right: 1052.541145269018,\n bottom: 1320.3967533541802,\n },\n },\n {\n id: "block_5_Pwzvu2",\n type: "section_heading",\n content: "### 3.4 Embeddings and Softmax",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.997,\n },\n polygon: [\n {\n x: 223.80512822283447,\n y: 1351.0096120045598,\n },\n {\n x: 499.655388045485,\n y: 1351.0096120045598,\n },\n {\n x: 499.655388045485,\n y: 1371.2419333206979,\n },\n {\n x: 223.80512822283447,\n y: 1371.2419333206979,\n },\n ],\n boundingBox: {\n left: 223.80512822283447,\n top: 1351.0096120045598,\n right: 499.655388045485,\n bottom: 1371.2419333206979,\n },\n },\n {\n id: "block_5_6y9ZGB",\n type: "text",\n content:\n "Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension dmodel. We also use the usual learned linear transfor- mation and softmax function to convert the decoder output to predicted next-token probabilities. In our model, we share the same weight matrix between the two embedding layers and the pre-softmax linear transformation, similar to [30]. In the embedding layers, we multiply those weights by Vdmodel -",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.275,\n avgOcrConfidence: 0.983,\n },\n polygon: [\n {\n x: 224.49331770848184,\n y: 1394.318801822519,\n },\n {\n x: 1052.2855327077154,\n y: 1394.318801822519,\n },\n {\n x: 1052.2855327077154,\n y: 1505.8341434450076,\n },\n {\n x: 224.49331770848184,\n y: 1505.8341434450076,\n },\n ],\n boundingBox: {\n left: 224.49331770848184,\n top: 1394.318801822519,\n right: 1052.2855327077154,\n bottom: 1505.8341434450076,\n },\n },\n {\n id: "block_5_o8MKrc",\n type: "page_number",\n content: "5",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 631.5606054598397,\n y: 1547.4356578740858,\n },\n {\n x: 641.9868998283888,\n y: 1547.4356578740858,\n },\n {\n x: 641.9868998283888,\n y: 1563.1716341864794,\n },\n {\n x: 631.5606054598397,\n y: 1563.1716341864794,\n },\n ],\n boundingBox: {\n left: 631.5606054598397,\n top: 1547.4356578740858,\n right: 641.9868998283888,\n bottom: 1563.1716341864794,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_6_YmUPFZ",\n type: "text",\n content:\n "Table 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations for different layer types. n is the sequence length, d is the representation dimension, k is the kernel size of convolutions and r the size of the neighborhood in restricted self-attention.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.977,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.7798615058843,\n y: 148.2273318355245,\n },\n {\n x: 1048.906618661254,\n y: 148.2273318355245,\n },\n {\n x: 1048.906618661254,\n y: 214.40370720311216,\n },\n {\n x: 222.7798615058843,\n y: 214.40370720311216,\n },\n ],\n boundingBox: {\n left: 222.7798615058843,\n top: 148.2273318355245,\n right: 1048.906618661254,\n bottom: 214.40370720311216,\n },\n },\n {\n id: "block_6_kibLxu",\n type: "table",\n content:\n "| Layer Type | Complexity per Layer | Sequential Operations | Maximum Path Length |\\n| --- | --- | --- | --- |\\n| Self-Attention | O(n2 \\u00b7 d) | O(1) | O(1) |\\n| Recurrent | O(n \\u00b7 d2) | O(n) | O(n) |\\n| Convolutional | O(k \\u00b7 n \\u00b7 d2) | O(1) | O(logk(n)) |\\n| Self-Attention (restricted) | O(r . n . d) [ ] | O(1) | O(n/r) [ ] |",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.256,\n avgOcrConfidence: 0.856,\n },\n polygon: [\n {\n x: 246.08119491243013,\n y: 233.8958637983279,\n },\n {\n x: 1028.2713006012632,\n y: 233.8958637983279,\n },\n {\n x: 1028.2713006012632,\n y: 389.94297754674926,\n },\n {\n x: 246.08119491243013,\n y: 389.94297754674926,\n },\n ],\n boundingBox: {\n left: 246.08119491243013,\n top: 233.8958637983279,\n right: 1028.2713006012632,\n bottom: 389.94297754674926,\n },\n },\n {\n id: "block_6_tUIpoY",\n type: "section_heading",\n content: "### 3.5 Positional Encoding",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.00651778617916,\n y: 445.9595083078944,\n },\n {\n x: 448.20427163674015,\n y: 445.9595083078944,\n },\n {\n x: 448.20427163674015,\n y: 466.69903696390026,\n },\n {\n x: 224.00651778617916,\n y: 466.69903696390026,\n },\n ],\n boundingBox: {\n left: 224.00651778617916,\n top: 445.9595083078944,\n right: 448.20427163674015,\n bottom: 466.69903696390026,\n },\n },\n {\n id: "block_6_mmxGrc",\n type: "text",\n content:\n \'Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence. To this end, we add "positional encodings" to the input embeddings at the bottoms of the encoder and decoder stacks. The positional encodings have the same dimension dmodel as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [9].\',\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.83698512167825,\n y: 487.3354288832586,\n },\n {\n x: 1050.4121766473256,\n y: 487.3354288832586,\n },\n {\n x: 1050.4121766473256,\n y: 620.7750930786133,\n },\n {\n x: 223.83698512167825,\n y: 620.7750930786133,\n },\n ],\n boundingBox: {\n left: 223.83698512167825,\n top: 487.3354288832586,\n right: 1050.4121766473256,\n bottom: 620.7750930786133,\n },\n },\n {\n id: "block_6_NG2aN8",\n type: "text",\n content:\n "In this work, we use sine and cosine functions of different frequencies:",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.39521455416715,\n y: 635.0555533789154,\n },\n {\n x: 810.5588871197108,\n y: 635.0555533789154,\n },\n {\n x: 810.5588871197108,\n y: 655.9754529393705,\n },\n {\n x: 224.39521455416715,\n y: 655.9754529393705,\n },\n ],\n boundingBox: {\n left: 224.39521455416715,\n top: 635.0555533789154,\n right: 810.5588871197108,\n bottom: 655.9754529393705,\n },\n },\n {\n id: "block_6_ktOzAP",\n type: "text",\n content:\n "PE(pos,2i) = sin(pos/100002i/dmodel ) PE(pos,2i+1) = cos(pos/100002i/dmodel) )",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.646,\n avgOcrConfidence: 0.856,\n },\n polygon: [\n {\n x: 470.62755222738224,\n y: 700.6432727440855,\n },\n {\n x: 804.2361684089159,\n y: 700.6432727440855,\n },\n {\n x: 804.2361684089159,\n y: 763.5065343469606,\n },\n {\n x: 470.62755222738224,\n y: 763.5065343469606,\n },\n ],\n boundingBox: {\n left: 470.62755222738224,\n top: 700.6432727440855,\n right: 804.2361684089159,\n bottom: 763.5065343469606,\n },\n },\n {\n id: "block_6_L0vHNu",\n type: "text",\n content:\n "where pos is the position and i is the dimension. That is, each dimension of the positional encoding corresponds to a sinusoid. The wavelengths form a geometric progression from 27 to 10000 . 27. We chose this function because we hypothesized it would allow the model to easily learn to attend by relative positions, since for any fixed offset k, PEpos+k can be represented as a linear function of PEpos.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.291,\n avgOcrConfidence: 0.967,\n },\n polygon: [\n {\n x: 223.63699196028884,\n y: 787.3148307800293,\n },\n {\n x: 1050.8335586881985,\n y: 787.3148307800293,\n },\n {\n x: 1050.8335586881985,\n y: 900.202535012611,\n },\n {\n x: 223.63699196028884,\n y: 900.202535012611,\n },\n ],\n boundingBox: {\n left: 223.63699196028884,\n top: 787.3148307800293,\n right: 1050.8335586881985,\n bottom: 900.202535012611,\n },\n },\n {\n id: "block_6_Sai49H",\n type: "text",\n content:\n "We also experimented with using learned positional embeddings [9] instead, and found that the two versions produced nearly identical results (see Table 3 row (E)). We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.868,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 223.15007369883736,\n y: 912.2991767252298,\n },\n {\n x: 1049.522644933993,\n y: 912.2991767252298,\n },\n {\n x: 1049.522644933993,\n y: 1000.5864015736975,\n },\n {\n x: 223.15007369883736,\n y: 1000.5864015736975,\n },\n ],\n boundingBox: {\n left: 223.15007369883736,\n top: 912.2991767252298,\n right: 1049.522644933993,\n bottom: 1000.5864015736975,\n },\n },\n {\n id: "block_6_545oKE",\n type: "section_heading",\n content: "### 4 Why Self-Attention",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.44270274586924,\n y: 1036.185907234823,\n },\n {\n x: 468.14631162768734,\n y: 1036.185907234823,\n },\n {\n x: 468.14631162768734,\n y: 1059.806398205291,\n },\n {\n x: 223.44270274586924,\n y: 1059.806398205291,\n },\n ],\n boundingBox: {\n left: 223.44270274586924,\n top: 1036.185907234823,\n right: 468.14631162768734,\n bottom: 1059.806398205291,\n },\n },\n {\n id: "block_6_rdkytl",\n type: "text",\n content:\n "In this section we compare various aspects of self-attention layers to the recurrent and convolu- tional layers commonly used for mapping one variable-length sequence of symbol representations (x1, ... , In) to another sequence of equal length (21, ... , Zn), with xi, Zi E Rd, such as a hidden layer in a typical sequence transduction encoder or decoder. Motivating our use of self-attention we consider three desiderata.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.298,\n avgOcrConfidence: 0.936,\n },\n polygon: [\n {\n x: 222.55295802206888,\n y: 1087.3066867455505,\n },\n {\n x: 1052.7677884067061,\n y: 1087.3066867455505,\n },\n {\n x: 1052.7677884067061,\n y: 1195.3768446499244,\n },\n {\n x: 222.55295802206888,\n y: 1195.3768446499244,\n },\n ],\n boundingBox: {\n left: 222.55295802206888,\n top: 1087.3066867455505,\n right: 1052.7677884067061,\n bottom: 1195.3768446499244,\n },\n },\n {\n id: "block_6_y2UJTk",\n type: "text",\n content:\n "One is the total computational complexity per layer. Another is the amount of computation that can be parallelized, as measured by the minimum number of sequential operations required.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.43593374656064,\n y: 1212.4905345601246,\n },\n {\n x: 1048.7435946499345,\n y: 1212.4905345601246,\n },\n {\n x: 1048.7435946499345,\n y: 1255.7911059730932,\n },\n {\n x: 223.43593374656064,\n y: 1255.7911059730932,\n },\n ],\n boundingBox: {\n left: 223.43593374656064,\n top: 1212.4905345601246,\n right: 1048.7435946499345,\n bottom: 1255.7911059730932,\n },\n },\n {\n id: "block_6_OGHshO",\n type: "text",\n content:\n "The third is the path length between long-range dependencies in the network. Learning long-range dependencies is a key challenge in many sequence transduction tasks. One key factor affecting the ability to learn such dependencies is the length of the paths forward and backward signals have to traverse in the network. The shorter these paths between any combination of positions in the input and output sequences, the easier it is to learn long-range dependencies [12]. Hence we also compare the maximum path length between any two input and output positions in networks composed of the different layer types.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.983,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.87737296445525,\n y: 1268.8657945905413,\n },\n {\n x: 1049.749950770914,\n y: 1268.8657945905413,\n },\n {\n x: 1049.749950770914,\n y: 1426.1352065236945,\n },\n {\n x: 222.87737296445525,\n y: 1426.1352065236945,\n },\n ],\n boundingBox: {\n left: 222.87737296445525,\n top: 1268.8657945905413,\n right: 1049.749950770914,\n bottom: 1426.1352065236945,\n },\n },\n {\n id: "block_6_zgN3wO",\n type: "text",\n content:\n "As noted in Table 1, a self-attention layer connects all positions with a constant number of sequentially executed operations, whereas a recurrent layer requires O(n) sequential operations. In terms of computational complexity, self-attention layers are faster than recurrent layers when the sequence",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.4352473794979,\n y: 1439.235182109632,\n },\n {\n x: 1051.6017217705719,\n y: 1439.235182109632,\n },\n {\n x: 1051.6017217705719,\n y: 1506.1062388025728,\n },\n {\n x: 223.4352473794979,\n y: 1506.1062388025728,\n },\n ],\n boundingBox: {\n left: 223.4352473794979,\n top: 1439.235182109632,\n right: 1051.6017217705719,\n bottom: 1506.1062388025728,\n },\n },\n {\n id: "block_6_aNgpKT",\n type: "page_number",\n content: "6",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 631.7702550957673,\n y: 1548.2886905526757,\n },\n {\n x: 642.7105200551722,\n y: 1548.2886905526757,\n },\n {\n x: 642.7105200551722,\n y: 1563.5418467700931,\n },\n {\n x: 631.7702550957673,\n y: 1563.5418467700931,\n },\n ],\n boundingBox: {\n left: 631.7702550957673,\n top: 1548.2886905526757,\n right: 642.7105200551722,\n bottom: 1563.5418467700931,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_7_u723hy",\n type: "text",\n content:\n "length n is smaller than the representation dimensionality d, which is most often the case with sentence representations used by state-of-the-art models in machine translations, such as word-piece [38] and byte-pair [31] representations. To improve computational performance for tasks involving very long sequences, self-attention could be restricted to considering only a neighborhood of size r in the input sequence centered around the respective output position. This would increase the maximum path length to O(n/r). We plan to investigate this approach further in future work.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.909,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.89144479793353,\n y: 155.39061148363845,\n },\n {\n x: 1050.0338700565978,\n y: 155.39061148363845,\n },\n {\n x: 1050.0338700565978,\n y: 290.11272512163436,\n },\n {\n x: 223.89144479793353,\n y: 290.11272512163436,\n },\n ],\n boundingBox: {\n left: 223.89144479793353,\n top: 155.39061148363845,\n right: 1050.0338700565978,\n bottom: 290.11272512163436,\n },\n },\n {\n id: "block_7_SLgoxa",\n type: "text",\n content:\n "A single convolutional layer with kernel width k < n does not connect all pairs of input and output positions. Doing so requires a stack of O(n/k) convolutional layers in the case of contiguous kernels, or O(logk(n)) in the case of dilated convolutions [18], increasing the length of the longest paths between any two positions in the network. Convolutional layers are generally more expensive than recurrent layers, by a factor of k. Separable convolutions [6], however, decrease the complexity considerably, to O(k . n . d + n . d2). Even with k = n, however, the complexity of a separable convolution is equal to the combination of a self-attention layer and a point-wise feed-forward layer, the approach we take in our model.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.525,\n avgOcrConfidence: 0.977,\n },\n polygon: [\n {\n x: 223.84822734080961,\n y: 303.4973448416344,\n },\n {\n x: 1051.7048188369638,\n y: 303.4973448416344,\n },\n {\n x: 1051.7048188369638,\n y: 482.7421505003047,\n },\n {\n x: 223.84822734080961,\n y: 482.7421505003047,\n },\n ],\n boundingBox: {\n left: 223.84822734080961,\n top: 303.4973448416344,\n right: 1051.7048188369638,\n bottom: 482.7421505003047,\n },\n },\n {\n id: "block_7_lGN5L0",\n type: "text",\n content:\n "As side benefit, self-attention could yield more interpretable models. We inspect attention distributions from our models and present and discuss examples in the appendix. Not only do individual attention heads clearly learn to perform different tasks, many appear to exhibit behavior related to the syntactic and semantic structure of the sentences.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.94,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.7218884656029,\n y: 496.4417208334557,\n },\n {\n x: 1049.5183847246378,\n y: 496.4417208334557,\n },\n {\n x: 1049.5183847246378,\n y: 581.3287481437052,\n },\n {\n x: 223.7218884656029,\n y: 581.3287481437052,\n },\n ],\n boundingBox: {\n left: 223.7218884656029,\n top: 496.4417208334557,\n right: 1049.5183847246378,\n bottom: 581.3287481437052,\n },\n },\n {\n id: "block_7_FOtl5B",\n type: "heading",\n content: "# 5 Training",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.4122553915873,\n y: 625.3390120599503,\n },\n {\n x: 354.91415984439146,\n y: 625.3390120599503,\n },\n {\n x: 354.91415984439146,\n y: 649.7166914688913,\n },\n {\n x: 224.4122553915873,\n y: 649.7166914688913,\n },\n ],\n boundingBox: {\n left: 224.4122553915873,\n top: 625.3390120599503,\n right: 354.91415984439146,\n bottom: 649.7166914688913,\n },\n },\n {\n id: "block_7_3jYBCf",\n type: "text",\n content: "This section describes the training regime for our models.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.4527957665659,\n y: 679.1303132709704,\n },\n {\n x: 701.988161741382,\n y: 679.1303132709704,\n },\n {\n x: 701.988161741382,\n y: 699.7081758025894,\n },\n {\n x: 222.4527957665659,\n y: 699.7081758025894,\n },\n ],\n boundingBox: {\n left: 222.4527957665659,\n top: 679.1303132709704,\n right: 701.988161741382,\n bottom: 699.7081758025894,\n },\n },\n {\n id: "block_7_PIafds",\n type: "section_heading",\n content: "### 5.1 Training Data and Batching",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.68002007477475,\n y: 735.0401794318866,\n },\n {\n x: 519.6398407873446,\n y: 735.0401794318866,\n },\n {\n x: 519.6398407873446,\n y: 755.8565634247055,\n },\n {\n x: 223.68002007477475,\n y: 755.8565634247055,\n },\n ],\n boundingBox: {\n left: 223.68002007477475,\n top: 735.0401794318866,\n right: 519.6398407873446,\n bottom: 755.8565634247055,\n },\n },\n {\n id: "block_7_8RhsHH",\n type: "text",\n content:\n "We trained on the standard WMT 2014 English-German dataset consisting of about 4.5 million sentence pairs. Sentences were encoded using byte-pair encoding [3], which has a shared source- target vocabulary of about 37000 tokens. For English-French, we used the significantly larger WMT 2014 English-French dataset consisting of 36M sentences and split tokens into a 32000 word-piece vocabulary [38]. Sentence pairs were batched together by approximate sequence length. Each training batch contained a set of sentence pairs containing approximately 25000 source tokens and 25000 target tokens.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.911,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.70165247116648,\n y: 778.8621643467953,\n },\n {\n x: 1052.1871692072737,\n y: 778.8621643467953,\n },\n {\n x: 1052.1871692072737,\n y: 935.23512009929,\n },\n {\n x: 223.70165247116648,\n y: 935.23512009929,\n },\n ],\n boundingBox: {\n left: 223.70165247116648,\n top: 778.8621643467953,\n right: 1052.1871692072737,\n bottom: 935.23512009929,\n },\n },\n {\n id: "block_7_2fOgoW",\n type: "section_heading",\n content: "### 5.2 Hardware and Schedule",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.9209349138023,\n y: 971.4598863071069,\n },\n {\n x: 484.7486314982394,\n y: 971.4598863071069,\n },\n {\n x: 484.7486314982394,\n y: 987.6652342143811,\n },\n {\n x: 223.9209349138023,\n y: 987.6652342143811,\n },\n ],\n boundingBox: {\n left: 223.9209349138023,\n top: 971.4598863071069,\n right: 484.7486314982394,\n bottom: 987.6652342143811,\n },\n },\n {\n id: "block_7_7vykWe",\n type: "text",\n content:\n "We trained our models on one machine with 8 NVIDIA P100 GPUs. For our base models using the hyperparameters described throughout the paper, each training step took about 0.4 seconds. We trained the base models for a total of 100,000 steps or 12 hours. For our big models,(described on the bottom line of table 3), step time was 1.0 seconds. The big models were trained for 300,000 steps (3.5 days).",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.961,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.2459757449853,\n y: 1014.9955223485043,\n },\n {\n x: 1049.3973947789548,\n y: 1014.9955223485043,\n },\n {\n x: 1049.3973947789548,\n y: 1126.7015106660083,\n },\n {\n x: 223.2459757449853,\n y: 1126.7015106660083,\n },\n ],\n boundingBox: {\n left: 223.2459757449853,\n top: 1014.9955223485043,\n right: 1049.3973947789548,\n bottom: 1126.7015106660083,\n },\n },\n {\n id: "block_7_Xjy6qb",\n type: "section_heading",\n content: "### 5.3 Optimizer",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.84361211400832,\n y: 1161.1210525053784,\n },\n {\n x: 361.9454223744191,\n y: 1161.1210525053784,\n },\n {\n x: 361.9454223744191,\n y: 1181.9203891037102,\n },\n {\n x: 223.84361211400832,\n y: 1181.9203891037102,\n },\n ],\n boundingBox: {\n left: 223.84361211400832,\n top: 1161.1210525053784,\n right: 361.9454223744191,\n bottom: 1181.9203891037102,\n },\n },\n {\n id: "block_7_uZS3FC",\n type: "text",\n content:\n "We used the Adam optimizer [20] with 31 = 0.9, 32 = 0.98 and \\u20ac = 10-9. We varied the learning rate over the course of training, according to the formula:",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.472,\n avgOcrConfidence: 0.947,\n },\n polygon: [\n {\n x: 223.18536243299496,\n y: 1203.7906809068263,\n },\n {\n x: 1049.5936484232436,\n y: 1203.7906809068263,\n },\n {\n x: 1049.5936484232436,\n y: 1249.0720648514596,\n },\n {\n x: 223.18536243299496,\n y: 1249.0720648514596,\n },\n ],\n boundingBox: {\n left: 223.18536243299496,\n top: 1203.7906809068263,\n right: 1049.5936484232436,\n bottom: 1249.0720648514596,\n },\n },\n {\n id: "block_7_qvJczg",\n type: "text",\n content:\n "lrate = dmodel . min(step_num-0.5, step_num . warmup_steps-1.5)",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.563,\n avgOcrConfidence: 0.786,\n },\n polygon: [\n {\n x: 338.51696905428474,\n y: 1286.921258338412,\n },\n {\n x: 933.735361586522,\n y: 1286.921258338412,\n },\n {\n x: 933.735361586522,\n y: 1314.0637410099346,\n },\n {\n x: 338.51696905428474,\n y: 1314.0637410099346,\n },\n ],\n boundingBox: {\n left: 338.51696905428474,\n top: 1286.921258338412,\n right: 933.735361586522,\n bottom: 1314.0637410099346,\n },\n },\n {\n id: "block_7_ZRnl1T",\n type: "text",\n content: "(3)",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 1026.6387883764114,\n y: 1291.0368781986094,\n },\n {\n x: 1051.2767151324417,\n y: 1291.0368781986094,\n },\n {\n x: 1051.2767151324417,\n y: 1311.080825805664,\n },\n {\n x: 1026.6387883764114,\n y: 1311.080825805664,\n },\n ],\n boundingBox: {\n left: 1026.6387883764114,\n top: 1291.0368781986094,\n right: 1051.2767151324417,\n bottom: 1311.080825805664,\n },\n },\n {\n id: "block_7_M71nL9",\n type: "text",\n content:\n "This corresponds to increasing the learning rate linearly for the first warmup_steps training steps, and decreasing it thereafter proportionally to the inverse square root of the step number. We used warmup_steps = 4000.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.916,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 222.72840764400732,\n y: 1340.2761936044335,\n },\n {\n x: 1052.0266066502481,\n y: 1340.2761936044335,\n },\n {\n x: 1052.0266066502481,\n y: 1406.6737115616188,\n },\n {\n x: 222.72840764400732,\n y: 1406.6737115616188,\n },\n ],\n boundingBox: {\n left: 222.72840764400732,\n top: 1340.2761936044335,\n right: 1052.0266066502481,\n bottom: 1406.6737115616188,\n },\n },\n {\n id: "block_7_ACakMa",\n type: "section_heading",\n content: "### 5.4 Regularization",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.81116351942077,\n y: 1441.41800626597,\n },\n {\n x: 402.1996435457773,\n y: 1441.41800626597,\n },\n {\n x: 402.1996435457773,\n y: 1461.9926013803124,\n },\n {\n x: 223.81116351942077,\n y: 1461.9926013803124,\n },\n ],\n boundingBox: {\n left: 223.81116351942077,\n top: 1441.41800626597,\n right: 402.1996435457773,\n bottom: 1461.9926013803124,\n },\n },\n {\n id: "block_7_rR8JeL",\n type: "text",\n content: "We employ three types of regularization during training:",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.88627206844134,\n y: 1484.7892296583134,\n },\n {\n x: 690.987449144795,\n y: 1484.7892296583134,\n },\n {\n x: 690.987449144795,\n y: 1505.950728681751,\n },\n {\n x: 222.88627206844134,\n y: 1505.950728681751,\n },\n ],\n boundingBox: {\n left: 222.88627206844134,\n top: 1484.7892296583134,\n right: 690.987449144795,\n bottom: 1505.950728681751,\n },\n },\n {\n id: "block_7_I7j7Uy",\n type: "page_number",\n content: "7",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.996,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 631.8865114755004,\n y: 1547.4189893105872,\n },\n {\n x: 642.4512153124288,\n y: 1547.4189893105872,\n },\n {\n x: 642.4512153124288,\n y: 1562.541448836936,\n },\n {\n x: 631.8865114755004,\n y: 1562.541448836936,\n },\n ],\n boundingBox: {\n left: 631.8865114755004,\n top: 1547.4189893105872,\n right: 642.4512153124288,\n bottom: 1562.541448836936,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_8_8rtbBp",\n type: "text",\n content:\n "Table 2: The Transformer achieves better BLEU scores than previous state-of-the-art models on the English-to-German and English-to-French newstest2014 tests at a fraction of the training cost.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 222.40285664579295,\n y: 148.11078211418666,\n },\n {\n x: 1048.695596291201,\n y: 148.11078211418666,\n },\n {\n x: 1048.695596291201,\n y: 191.8824890538266,\n },\n {\n x: 222.40285664579295,\n y: 191.8824890538266,\n },\n ],\n boundingBox: {\n left: 222.40285664579295,\n top: 148.11078211418666,\n right: 1048.695596291201,\n bottom: 191.8824890538266,\n },\n },\n {\n id: "block_8_M3V7h9",\n type: "table",\n content:\n "| Model | BLEU | | Training Cost (FLOPs) | |\\n| --- | --- | --- | --- | --- |\\n| | EN-DE | EN-FR | EN-DE | EN-FR |\\n| ByteNet [18] | 23.75 | | | |\\n| Deep-Att + PosUnk [39] | | 39.2 | | 1.0 . 1020 |\\n| GNMT + RL [38] | 24.6 | 39.92 | 2.3 . 1019 | 1.4 . 1020 |\\n| ConvS2S [9] | 25.16 | 40.46 | 9.6 . 1018 | 1.5 . 1020 |\\n| MoE [32] | 26.03 | 40.56 | 2.0 \\u00b7 1019 | 1.2 . 1020 |\\n| Deep-Att + PosUnk Ensemble [39] | | 40.4 | | 8.0 . 1020 |\\n| GNMT + RL Ensemble [38] | 26.30 | 41.16 | 1.8 . 1020 | 1.1 . 1021 |\\n| ConvS2S Ensemble [9] | 26.36 | 41.29 | 7.7 . 1019 | 1.2 . 1021 |\\n| Transformer (base model) | 27.3 | 38.1 | 3.3 . | 1018 |\\n| Transformer (big) | 28.4 | 41.8 | 2.3. 1019 | |",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.141,\n avgOcrConfidence: 0.893,\n },\n polygon: [\n {\n x: 271.150136516042,\n y: 195.3426247575229,\n },\n {\n x: 1004.1704442379248,\n y: 195.3426247575229,\n },\n {\n x: 1004.1704442379248,\n y: 508.6132290201976,\n },\n {\n x: 271.150136516042,\n y: 508.6132290201976,\n },\n ],\n boundingBox: {\n left: 271.150136516042,\n top: 195.3426247575229,\n right: 1004.1704442379248,\n bottom: 508.6132290201976,\n },\n },\n {\n id: "block_8_Wl0xmI",\n type: "text",\n content:\n "Residual Dropout We apply dropout [33] to the output of each sub-layer, before it is added to the sub-layer input and normalized. In addition, we apply dropout to the sums of the embeddings and the positional encodings in both the encoder and decoder stacks. For the base model, we use a rate of Pdrop =0.1.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.893,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 223.9333605244212,\n y: 569.1121117154458,\n },\n {\n x: 1051.605887308608,\n y: 569.1121117154458,\n },\n {\n x: 1051.605887308608,\n y: 660.0886577520155,\n },\n {\n x: 223.9333605244212,\n y: 660.0886577520155,\n },\n ],\n boundingBox: {\n left: 223.9333605244212,\n top: 569.1121117154458,\n right: 1051.605887308608,\n bottom: 660.0886577520155,\n },\n },\n {\n id: "block_8_CtqTnb",\n type: "text",\n content:\n "Label Smoothing During training, we employed label smoothing of value Els = 0.1 [36]. This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.518,\n avgOcrConfidence: 0.977,\n },\n polygon: [\n {\n x: 223.52019122047145,\n y: 690.790115499855,\n },\n {\n x: 1049.6801780088103,\n y: 690.790115499855,\n },\n {\n x: 1049.6801780088103,\n y: 734.1354363233523,\n },\n {\n x: 223.52019122047145,\n y: 734.1354363233523,\n },\n ],\n boundingBox: {\n left: 223.52019122047145,\n top: 690.790115499855,\n right: 1049.6801780088103,\n bottom: 734.1354363233523,\n },\n },\n {\n id: "block_8_KA1kZT",\n type: "heading",\n content: "# 6 Results",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.16400352533717,\n y: 774.585115131579,\n },\n {\n x: 339.42863018843383,\n y: 774.585115131579,\n },\n {\n x: 339.42863018843383,\n y: 793.809935433524,\n },\n {\n x: 224.16400352533717,\n y: 793.809935433524,\n },\n ],\n boundingBox: {\n left: 224.16400352533717,\n top: 774.585115131579,\n right: 339.42863018843383,\n bottom: 793.809935433524,\n },\n },\n {\n id: "block_8_LYkEL8",\n type: "section_heading",\n content: "### 6.1 Machine Translation",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 224.2968510537252,\n y: 828.3471990026029,\n },\n {\n x: 455.2866330111984,\n y: 828.3471990026029,\n },\n {\n x: 455.2866330111984,\n y: 844.3720339438072,\n },\n {\n x: 224.2968510537252,\n y: 844.3720339438072,\n },\n ],\n boundingBox: {\n left: 224.2968510537252,\n top: 828.3471990026029,\n right: 455.2866330111984,\n bottom: 844.3720339438072,\n },\n },\n {\n id: "block_8_UnI1Ea",\n type: "text",\n content:\n "On the WMT 2014 English-to-German translation task, the big transformer model (Transformer (big) in Table 2) outperforms the best previously reported models (including ensembles) by more than 2.0 BLEU, establishing a new state-of-the-art BLEU score of 28.4. The configuration of this model is listed in the bottom line of Table 3. Training took 3.5 days on 8 P100 GPUs. Even our base model surpasses all previously published models and ensembles, at a fraction of the training cost of any of the competitive models.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.973,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.56291165317063,\n y: 872.0711140453367,\n },\n {\n x: 1050.5385628581919,\n y: 872.0711140453367,\n },\n {\n x: 1050.5385628581919,\n y: 1006.0390107004266,\n },\n {\n x: 223.56291165317063,\n y: 1006.0390107004266,\n },\n ],\n boundingBox: {\n left: 223.56291165317063,\n top: 872.0711140453367,\n right: 1050.5385628581919,\n bottom: 1006.0390107004266,\n },\n },\n {\n id: "block_8_pkBARc",\n type: "text",\n content:\n "On the WMT 2014 English-to-French translation task, our big model achieves a BLEU score of 41.0, outperforming all of the previously published single models, at less than 1/4 the training cost of the previous state-of-the-art model. The Transformer (big) model trained for English-to-French used dropout rate Pdrop = 0.1, instead of 0.3.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.945,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.05139199138557,\n y: 1019.1086798072756,\n },\n {\n x: 1052.2523977460653,\n y: 1019.1086798072756,\n },\n {\n x: 1052.2523977460653,\n y: 1109.5784446888401,\n },\n {\n x: 224.05139199138557,\n y: 1109.5784446888401,\n },\n ],\n boundingBox: {\n left: 224.05139199138557,\n top: 1019.1086798072756,\n right: 1052.2523977460653,\n bottom: 1109.5784446888401,\n },\n },\n {\n id: "block_8_vKs7Yg",\n type: "text",\n content:\n "For the base models, we used a single model obtained by averaging the last 5 checkpoints, which were written at 10-minute intervals. For the big models, we averaged the last 20 checkpoints. We used beam search with a beam size of 4 and length penalty & = 0.6 [38]. These hyperparameters were chosen after experimentation on the development set. We set the maximum output length during inference to input length + 50, but terminate early when possible [38].",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.099,\n avgOcrConfidence: 0.983,\n },\n polygon: [\n {\n x: 223.50279536560504,\n y: 1122.2645474197273,\n },\n {\n x: 1050.043905216412,\n y: 1122.2645474197273,\n },\n {\n x: 1050.043905216412,\n y: 1233.5787297872673,\n },\n {\n x: 223.50279536560504,\n y: 1233.5787297872673,\n },\n ],\n boundingBox: {\n left: 223.50279536560504,\n top: 1122.2645474197273,\n right: 1050.043905216412,\n bottom: 1233.5787297872673,\n },\n },\n {\n id: "block_8_42PSVl",\n type: "text",\n content:\n "Table 2 summarizes our results and compares our translation quality and training costs to other model architectures from the literature. We estimate the number of floating point operations used to train a model by multiplying the training time, the number of GPUs used, and an estimate of the sustained single-precision floating-point capacity of each GPU 5.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.975,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 222.3879459130503,\n y: 1247.2785842436597,\n },\n {\n x: 1049.63284234931,\n y: 1247.2785842436597,\n },\n {\n x: 1049.63284234931,\n y: 1336.1913537620603,\n },\n {\n x: 222.3879459130503,\n y: 1336.1913537620603,\n },\n ],\n boundingBox: {\n left: 222.3879459130503,\n top: 1247.2785842436597,\n right: 1049.63284234931,\n bottom: 1336.1913537620603,\n },\n },\n {\n id: "block_8_pDx0nB",\n type: "section_heading",\n content: "### 6.2 Model Variations",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.05955739264942,\n y: 1370.9984397027727,\n },\n {\n x: 424.93188398597886,\n y: 1370.9984397027727,\n },\n {\n x: 424.93188398597886,\n y: 1387.4261614003576,\n },\n {\n x: 224.05955739264942,\n y: 1387.4261614003576,\n },\n ],\n boundingBox: {\n left: 224.05955739264942,\n top: 1370.9984397027727,\n right: 424.93188398597886,\n bottom: 1387.4261614003576,\n },\n },\n {\n id: "block_8_XCLvsN",\n type: "text",\n content:\n "To evaluate the importance of different components of the Transformer, we varied our base model in different ways, measuring the change in performance on English-to-German translation on the",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.6526705888066,\n y: 1413.835037862448,\n },\n {\n x: 1049.9819901737853,\n y: 1413.835037862448,\n },\n {\n x: 1049.9819901737853,\n y: 1458.0598621798638,\n },\n {\n x: 222.6526705888066,\n y: 1458.0598621798638,\n },\n ],\n boundingBox: {\n left: 222.6526705888066,\n top: 1413.835037862448,\n right: 1049.9819901737853,\n bottom: 1458.0598621798638,\n },\n },\n {\n id: "block_8_6e9VRc",\n type: "text",\n content:\n "5We used values of 2.8, 3.7, 6.0 and 9.5 TFLOPS for K80, K40, M40 and P100, respectively.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.976,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 249.0640041601919,\n y: 1482.8447849015545,\n },\n {\n x: 944.2274051861172,\n y: 1482.8447849015545,\n },\n {\n x: 944.2274051861172,\n y: 1505.4603319670025,\n },\n {\n x: 249.0640041601919,\n y: 1505.4603319670025,\n },\n ],\n boundingBox: {\n left: 249.0640041601919,\n top: 1482.8447849015545,\n right: 944.2274051861172,\n bottom: 1505.4603319670025,\n },\n },\n {\n id: "block_8_HHxEh9",\n type: "page_number",\n content: "8",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.996,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 631.7743259624843,\n y: 1547.954182789738,\n },\n {\n x: 642.6607229413778,\n y: 1547.954182789738,\n },\n {\n x: 642.6607229413778,\n y: 1563.2957013352473,\n },\n {\n x: 631.7743259624843,\n y: 1563.2957013352473,\n },\n ],\n boundingBox: {\n left: 631.7743259624843,\n top: 1547.954182789738,\n right: 642.6607229413778,\n bottom: 1563.2957013352473,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_9_2CG18E",\n type: "text",\n content:\n "Table 3: Variations on the Transformer architecture. Unlisted values are identical to those of the base model. All metrics are on the English-to-German translation development set, newstest2013. Listed perplexities are per-wordpiece, according to our byte-pair encoding, and should not be compared to per-word perplexities.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 222.6654748847015,\n y: 147.86792777355453,\n },\n {\n x: 1049.6700481776775,\n y: 147.86792777355453,\n },\n {\n x: 1049.6700481776775,\n y: 237.19010704442076,\n },\n {\n x: 222.6654748847015,\n y: 237.19010704442076,\n },\n ],\n boundingBox: {\n left: 222.6654748847015,\n top: 147.86792777355453,\n right: 1049.6700481776775,\n bottom: 237.19010704442076,\n },\n },\n {\n id: "block_9_0WToWH",\n type: "table",\n content:\n "| | N | dmodel | dff | h | dk | dv | Pdrop | Els | train steps | PPL (dev) | BLEU (dev) | params \\u00d7106 |\\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\\n| base | 6 | 512 | 2048 | 8 | 64 | 64 | 0.1 | 0.1 | 100K | 4.92 | 25.8 | 65 |\\n| (A) | | | | 1 | 512 | 512 | | | | 5.29 | 24.9 | |\\n| | | | | 4 | 128 | 128 | | | | 5.00 | 25.5 | |\\n| | | | | 16 | 32 | 32 | | | | 4.91 | 25.8 | |\\n| | | | | 32 | 16 | 16 | | | | 5.01 | 25.4 | |\\n| (B) | | | | | 16 | | | | | 5.16 | 25.1 | 58 |\\n| | | | | | 32 | | | | | 5.01 | 25.4 | 60 |\\n| (C) | 2 | | | | | | | | | 6.11 | 23.7 | 36 |\\n| | 4 | | | | | | | | | 5.19 | 25.3 | 50 |\\n| | 8 | | | | | | | | | 4.88 | 25.5 | 80 |\\n| | | 256 | | | 32 | 32 | | | | 5.75 | 24.5 | 28 |\\n| | | 1024 | | | 128 | 128 | | | | 4.66 | 26.0 | 168 |\\n| | | | 1024 | | | | | | | 5.12 | 25.4 | 53 |\\n| | | | 4096 | | | | | | | 4.75 | 26.2 | 90 |\\n| (D) | | | | | | | 0.0 | | | 5.77 | 24.6 | |\\n| | | | | | | | 0.2 | | | 4.95 | 25.5 | |\\n| | | | | | | | | 0.0 | | 4.67 | 25.3 | |\\n| | | | | | | | | 0.2 | | 5.47 | 25.7 | |\\n| (E) | positional embedding | | | | | instead of | sinusoids | | | 4.92 | 25.7 | |\\n| big | 6 | 1024 | 4096 | 16 | | | 0.3 | | 300K | 4.33 | 26.4 | 213 |",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.612,\n avgOcrConfidence: 0.986,\n },\n polygon: [\n {\n x: 224.84461930546448,\n y: 268.65403318763674,\n },\n {\n x: 1060.6742636130673,\n y: 268.65403318763674,\n },\n {\n x: 1060.6742636130673,\n y: 801.2216690178204,\n },\n {\n x: 224.84461930546448,\n y: 801.2216690178204,\n },\n ],\n boundingBox: {\n left: 224.84461930546448,\n top: 268.65403318763674,\n right: 1060.6742636130673,\n bottom: 801.2216690178204,\n },\n },\n {\n id: "block_9_p8WB9c",\n type: "text",\n content:\n "development set, newstest2013. We used beam search as described in the previous section, but no checkpoint averaging. We present these results in Table 3.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.42882287241247,\n y: 862.6040329323675,\n },\n {\n x: 1049.5265264580719,\n y: 862.6040329323675,\n },\n {\n x: 1049.5265264580719,\n y: 905.6541023541213,\n },\n {\n x: 224.42882287241247,\n y: 905.6541023541213,\n },\n ],\n boundingBox: {\n left: 224.42882287241247,\n top: 862.6040329323675,\n right: 1049.5265264580719,\n bottom: 905.6541023541213,\n },\n },\n {\n id: "block_9_XvsIA2",\n type: "text",\n content:\n "In Table 3 rows (A), we vary the number of attention heads and the attention key and value dimensions, keeping the amount of computation constant, as described in Section 3.2.2. While single-head attention is 0.9 BLEU worse than the best setting, quality also drops off with too many heads.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.967,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.23600106343736,\n y: 918.8913094656807,\n },\n {\n x: 1052.034559041044,\n y: 918.8913094656807,\n },\n {\n x: 1052.034559041044,\n y: 986.1080494357232,\n },\n {\n x: 224.23600106343736,\n y: 986.1080494357232,\n },\n ],\n boundingBox: {\n left: 224.23600106343736,\n top: 918.8913094656807,\n right: 1052.034559041044,\n bottom: 986.1080494357232,\n },\n },\n {\n id: "block_9_lFHLbG",\n type: "text",\n content:\n "In Table 3 rows (B), we observe that reducing the attention key size dk hurts model quality. This suggests that determining compatibility is not easy and that a more sophisticated compatibility function than dot product may be beneficial. We further observe in rows (C) and (D) that, as expected, bigger models are better, and dropout is very helpful in avoiding over-fitting. In row (E) we replace our sinusoidal positional encoding with learned positional embeddings [9], and observe nearly identical results to the base model.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.881,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.0262804240206,\n y: 998.9746651326803,\n },\n {\n x: 1052.338643317675,\n y: 998.9746651326803,\n },\n {\n x: 1052.338643317675,\n y: 1130.1984048140678,\n },\n {\n x: 224.0262804240206,\n y: 1130.1984048140678,\n },\n ],\n boundingBox: {\n left: 224.0262804240206,\n top: 998.9746651326803,\n right: 1052.338643317675,\n bottom: 1130.1984048140678,\n },\n },\n {\n id: "block_9_nnE2Kn",\n type: "section_heading",\n content: "### 6.3 English Constituency Parsing",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.00199723069687,\n y: 1168.0604785546325,\n },\n {\n x: 533.1579584274849,\n y: 1168.0604785546325,\n },\n {\n x: 533.1579584274849,\n y: 1188.5333575485345,\n },\n {\n x: 224.00199723069687,\n y: 1188.5333575485345,\n },\n ],\n boundingBox: {\n left: 224.00199723069687,\n top: 1168.0604785546325,\n right: 533.1579584274849,\n bottom: 1188.5333575485345,\n },\n },\n {\n id: "block_9_UvLm1J",\n type: "text",\n content:\n "To evaluate if the Transformer can generalize to other tasks we performed experiments on English constituency parsing. This task presents specific challenges: the output is subject to strong structural constraints and is significantly longer than the input. Furthermore, RNN sequence-to-sequence models have not been able to attain state-of-the-art results in small-data regimes [37].",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.0787388599702,\n y: 1212.099580979885,\n },\n {\n x: 1049.9080518736457,\n y: 1212.099580979885,\n },\n {\n x: 1049.9080518736457,\n y: 1300.6617424183323,\n },\n {\n x: 223.0787388599702,\n y: 1300.6617424183323,\n },\n ],\n boundingBox: {\n left: 223.0787388599702,\n top: 1212.099580979885,\n right: 1049.9080518736457,\n bottom: 1300.6617424183323,\n },\n },\n {\n id: "block_9_nmNLPf",\n type: "text",\n content:\n "We trained a 4-layer transformer with dmodel = 1024 on the Wall Street Journal (WSJ) portion of the Penn Treebank [25], about 40K training sentences. We also trained it in a semi-supervised setting, using the larger high-confidence and BerkleyParser corpora from with approximately 17M sentences [37]. We used a vocabulary of 16K tokens for the WSJ only setting and a vocabulary of 32K tokens for the semi-supervised setting.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 223.08401678600453,\n y: 1314.1105266370273,\n },\n {\n x: 1051.1732393807738,\n y: 1314.1105266370273,\n },\n {\n x: 1051.1732393807738,\n y: 1425.9921031177494,\n },\n {\n x: 223.08401678600453,\n y: 1425.9921031177494,\n },\n ],\n boundingBox: {\n left: 223.08401678600453,\n top: 1314.1105266370273,\n right: 1051.1732393807738,\n bottom: 1425.9921031177494,\n },\n },\n {\n id: "block_9_kQhH3x",\n type: "text",\n content:\n "We performed only a small number of experiments to select the dropout, both attention and residual (section 5.4), learning rates and beam size on the Section 22 development set, all other parameters remained unchanged from the English-to-German base translation model. During inference, we",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.1762739863709,\n y: 1439.0945411051127,\n },\n {\n x: 1050.7557388639798,\n y: 1439.0945411051127,\n },\n {\n x: 1050.7557388639798,\n y: 1505.8386894168711,\n },\n {\n x: 223.1762739863709,\n y: 1505.8386894168711,\n },\n ],\n boundingBox: {\n left: 223.1762739863709,\n top: 1439.0945411051127,\n right: 1050.7557388639798,\n bottom: 1505.8386894168711,\n },\n },\n {\n id: "block_9_C4QuNg",\n type: "page_number",\n content: "9",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 631.6446262554531,\n y: 1547.2787271370566,\n },\n {\n x: 642.3550765879834,\n y: 1547.2787271370566,\n },\n {\n x: 642.3550765879834,\n y: 1562.906831325445,\n },\n {\n x: 631.6446262554531,\n y: 1562.906831325445,\n },\n ],\n boundingBox: {\n left: 631.6446262554531,\n top: 1547.2787271370566,\n right: 642.3550765879834,\n bottom: 1562.906831325445,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_10_Whfo1k",\n type: "text",\n content:\n "Table 4: The Transformer generalizes well to English constituency parsing (Results are on Section 23 of WSJ)",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.988,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.60232911492787,\n y: 147.913837353986,\n },\n {\n x: 1049.0453121435903,\n y: 147.913837353986,\n },\n {\n x: 1049.0453121435903,\n y: 190.50408882485297,\n },\n {\n x: 222.60232911492787,\n y: 190.50408882485297,\n },\n ],\n boundingBox: {\n left: 222.60232911492787,\n top: 147.913837353986,\n right: 1049.0453121435903,\n bottom: 190.50408882485297,\n },\n },\n {\n id: "block_10_Oq0boE",\n type: "table",\n content:\n "| Parser | Training | WSJ 23 F1 |\\n| --- | --- | --- |\\n| Vinyals & Kaiser el al. (2014) [37] | WSJ only, discriminative | 88.3 |\\n| Petrov et al. (2006) [29] | WSJ only, discriminative | 90.4 |\\n| Zhu et al. (2013) [40] | WSJ only, discriminative | 90.4 |\\n| Dyer et al. (2016) [8] | WSJ only, discriminative | 91.7 |\\n| Transformer (4 layers) | WSJ only, discriminative | 91.3 |\\n| Zhu et al. (2013) [40] | semi-supervised | 91.3 |\\n| Huang & Harper (2009) [14] | semi-supervised | 91.3 |\\n| McClosky et al. (2006) [26] | semi-supervised | 92.1 |\\n| Vinyals & Kaiser el al. (2014) [37] | semi-supervised | 92.1 |\\n| Transformer (4 layers) | semi-supervised | 92.7 |\\n| Luong et al. (2015) [23] | multi-task | 93.0 |\\n| Dyer et al. (2016) [8] | generative | 93.3 |",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.926,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 300.48226962124346,\n y: 193.81453893417702,\n },\n {\n x: 974.1206315312072,\n y: 193.81453893417702,\n },\n {\n x: 974.1206315312072,\n y: 493.68785631567016,\n },\n {\n x: 300.48226962124346,\n y: 493.68785631567016,\n },\n ],\n boundingBox: {\n left: 300.48226962124346,\n top: 193.81453893417702,\n right: 974.1206315312072,\n bottom: 493.68785631567016,\n },\n },\n {\n id: "block_10_wSUPzw",\n type: "text",\n content:\n "increased the maximum output length to input length + 300. We used a beam size of 21 and & = 0.3 for both WSJ only and the semi-supervised setting.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.117,\n avgOcrConfidence: 0.964,\n },\n polygon: [\n {\n x: 223.84354111051908,\n y: 546.3992524398001,\n },\n {\n x: 1049.2353174808252,\n y: 546.3992524398001,\n },\n {\n x: 1049.2353174808252,\n y: 589.787902057619,\n },\n {\n x: 223.84354111051908,\n y: 589.787902057619,\n },\n ],\n boundingBox: {\n left: 223.84354111051908,\n top: 546.3992524398001,\n right: 1049.2353174808252,\n bottom: 589.787902057619,\n },\n },\n {\n id: "block_10_KdYXbX",\n type: "text",\n content:\n "Our results in Table 4 show that despite the lack of task-specific tuning our model performs sur- prisingly well, yielding better results than all previously reported models with the exception of the Recurrent Neural Network Grammar [8].",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.917,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.34470740548016,\n y: 603.5821801379211,\n },\n {\n x: 1052.1757139776746,\n y: 603.5821801379211,\n },\n {\n x: 1052.1757139776746,\n y: 667.7562916691143,\n },\n {\n x: 224.34470740548016,\n y: 667.7562916691143,\n },\n ],\n boundingBox: {\n left: 224.34470740548016,\n top: 603.5821801379211,\n right: 1052.1757139776746,\n bottom: 667.7562916691143,\n },\n },\n {\n id: "block_10_spL6f1",\n type: "text",\n content:\n "In contrast to RNN sequence-to-sequence models [37], the Transformer outperforms the Berkeley- Parser [29] even when training only on the WSJ training set of 40K sentences.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.907,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.93137242672216,\n y: 683.4819921909419,\n },\n {\n x: 1052.021589070341,\n y: 683.4819921909419,\n },\n {\n x: 1052.021589070341,\n y: 725.8283830513632,\n },\n {\n x: 223.93137242672216,\n y: 725.8283830513632,\n },\n ],\n boundingBox: {\n left: 223.93137242672216,\n top: 683.4819921909419,\n right: 1052.021589070341,\n bottom: 725.8283830513632,\n },\n },\n {\n id: "block_10_FpxS4M",\n type: "section_heading",\n content: "### 7 Conclusion",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.87968188654767,\n y: 760.911873552136,\n },\n {\n x: 380.37754949862074,\n y: 760.911873552136,\n },\n {\n x: 380.37754949862074,\n y: 780.8896204439321,\n },\n {\n x: 223.87968188654767,\n y: 780.8896204439321,\n },\n ],\n boundingBox: {\n left: 223.87968188654767,\n top: 760.911873552136,\n right: 380.37754949862074,\n bottom: 780.8896204439321,\n },\n },\n {\n id: "block_10_06Cxhy",\n type: "text",\n content:\n "In this work, we presented the Transformer, the first sequence transduction model based entirely on attention, replacing the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.7800876589587,\n y: 811.1846398948727,\n },\n {\n x: 1049.4503160462762,\n y: 811.1846398948727,\n },\n {\n x: 1049.4503160462762,\n y: 872.951422555106,\n },\n {\n x: 223.7800876589587,\n y: 872.951422555106,\n },\n ],\n boundingBox: {\n left: 223.7800876589587,\n top: 811.1846398948727,\n right: 1049.4503160462762,\n bottom: 872.951422555106,\n },\n },\n {\n id: "block_10_4PqBx5",\n type: "text",\n content:\n "For translation tasks, the Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers. On both WMT 2014 English-to-German and WMT 2014 English-to-French translation tasks, we achieve a new state of the art. In the former task our best model outperforms even all previously reported ensembles.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.91187013500797,\n y: 890.9364237390963,\n },\n {\n x: 1049.8108244290318,\n y: 890.9364237390963,\n },\n {\n x: 1049.8108244290318,\n y: 980.2941302536126,\n },\n {\n x: 223.91187013500797,\n y: 980.2941302536126,\n },\n ],\n boundingBox: {\n left: 223.91187013500797,\n top: 890.9364237390963,\n right: 1049.8108244290318,\n bottom: 980.2941302536126,\n },\n },\n {\n id: "block_10_9Aa2OZ",\n type: "text",\n content:\n "We are excited about the future of attention-based models and plan to apply them to other tasks. We plan to extend the Transformer to problems involving input and output modalities other than text and to investigate local, restricted attention mechanisms to efficiently handle large inputs and outputs such as images, audio and video. Making generation less sequential is another research goals of ours.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.985,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.4691397117002,\n y: 993.4156992059005,\n },\n {\n x: 1051.09778633953,\n y: 993.4156992059005,\n },\n {\n x: 1051.09778633953,\n y: 1081.8706514745727,\n },\n {\n x: 223.4691397117002,\n y: 1081.8706514745727,\n },\n ],\n boundingBox: {\n left: 223.4691397117002,\n top: 993.4156992059005,\n right: 1051.09778633953,\n bottom: 1081.8706514745727,\n },\n },\n {\n id: "block_10_eXUU9v",\n type: "text",\n content:\n "The code we used to train and evaluate our models is available at https://github.com/ tensorflow/tensor2tensor.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.94,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 222.4288912585182,\n y: 1095.2490678371344,\n },\n {\n x: 1050.6089983195284,\n y: 1095.2490678371344,\n },\n {\n x: 1050.6089983195284,\n y: 1136.225321719521,\n },\n {\n x: 222.4288912585182,\n y: 1136.225321719521,\n },\n ],\n boundingBox: {\n left: 222.4288912585182,\n top: 1095.2490678371344,\n right: 1050.6089983195284,\n bottom: 1136.225321719521,\n },\n },\n {\n id: "block_10_HbnFiy",\n type: "text",\n content:\n "Acknowledgements We are grateful to Nal Kalchbrenner and Stephan Gouws for their fruitful comments, corrections and inspiration.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.74068072242457,\n y: 1165.530171673997,\n },\n {\n x: 1049.9162882783987,\n y: 1165.530171673997,\n },\n {\n x: 1049.9162882783987,\n y: 1209.6124608319503,\n },\n {\n x: 223.74068072242457,\n y: 1209.6124608319503,\n },\n ],\n boundingBox: {\n left: 223.74068072242457,\n top: 1165.530171673997,\n right: 1049.9162882783987,\n bottom: 1209.6124608319503,\n },\n },\n {\n id: "block_10_FqHFgA",\n type: "section_heading",\n content: "### References",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.3401158465086,\n y: 1243.4205694557131,\n },\n {\n x: 340.41243086766156,\n y: 1243.4205694557131,\n },\n {\n x: 340.41243086766156,\n y: 1263.1433630921786,\n },\n {\n x: 224.3401158465086,\n y: 1263.1433630921786,\n },\n ],\n boundingBox: {\n left: 224.3401158465086,\n top: 1243.4205694557131,\n right: 340.41243086766156,\n bottom: 1263.1433630921786,\n },\n },\n {\n id: "block_10_PnBCYC",\n type: "text",\n content:\n "[1] Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint arXiv: 1607.06450, 2016.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 234.62492392881074,\n y: 1281.5349446346884,\n },\n {\n x: 1049.520940850251,\n y: 1281.5349446346884,\n },\n {\n x: 1049.520940850251,\n y: 1323.6168167573169,\n },\n {\n x: 234.62492392881074,\n y: 1323.6168167573169,\n },\n ],\n boundingBox: {\n left: 234.62492392881074,\n top: 1281.5349446346884,\n right: 1049.520940850251,\n bottom: 1323.6168167573169,\n },\n },\n {\n id: "block_10_sUAYRJ",\n type: "text",\n content:\n "[2] Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly learning to align and translate. CoRR, abs/1409.0473, 2014.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 233.7351792050104,\n y: 1342.1247941210754,\n },\n {\n x: 1048.5688313950586,\n y: 1342.1247941210754,\n },\n {\n x: 1048.5688313950586,\n y: 1385.6842018070079,\n },\n {\n x: 233.7351792050104,\n y: 1385.6842018070079,\n },\n ],\n boundingBox: {\n left: 233.7351792050104,\n top: 1342.1247941210754,\n right: 1048.5688313950586,\n bottom: 1385.6842018070079,\n },\n },\n {\n id: "block_10_cYNyCb",\n type: "text",\n content:\n "[3] Denny Britz, Anna Goldie, Minh-Thang Luong, and Quoc V. Le. Massive exploration of neural machine translation architectures. CoRR, abs/1703.03906, 2017.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.914,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 234.47555625525703,\n y: 1401.96474766552,\n },\n {\n x: 1050.0915248898693,\n y: 1401.96474766552,\n },\n {\n x: 1050.0915248898693,\n y: 1443.4021335687853,\n },\n {\n x: 234.47555625525703,\n y: 1443.4021335687853,\n },\n ],\n boundingBox: {\n left: 234.47555625525703,\n top: 1401.96474766552,\n right: 1050.0915248898693,\n bottom: 1443.4021335687853,\n },\n },\n {\n id: "block_10_akeHB3",\n type: "text",\n content:\n "[4] Jianpeng Cheng, Li Dong, and Mirella Lapata. Long short-term memory-networks for machine reading. arXiv preprint arXiv: 1601.06733, 2016.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.91,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 235.1935672063897,\n y: 1461.8473196961825,\n },\n {\n x: 1049.3358584216041,\n y: 1461.8473196961825,\n },\n {\n x: 1049.3358584216041,\n y: 1505.7106445427228,\n },\n {\n x: 235.1935672063897,\n y: 1505.7106445427228,\n },\n ],\n boundingBox: {\n left: 235.1935672063897,\n top: 1461.8473196961825,\n right: 1049.3358584216041,\n bottom: 1505.7106445427228,\n },\n },\n {\n id: "block_10_sJYSgt",\n type: "page_number",\n content: "10",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.999,\n avgOcrConfidence: 0.999,\n },\n polygon: [\n {\n x: 628.4902252420022,\n y: 1547.7831405983832,\n },\n {\n x: 647.7796484954166,\n y: 1547.7831405983832,\n },\n {\n x: 647.7796484954166,\n y: 1563.3856736950409,\n },\n {\n x: 628.4902252420022,\n y: 1563.3856736950409,\n },\n ],\n boundingBox: {\n left: 628.4902252420022,\n top: 1547.7831405983832,\n right: 647.7796484954166,\n bottom: 1563.3856736950409,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_11_VBbBwR",\n type: "text",\n content:\n "[5] Kyunghyun Cho, Bart van Merrienboer, Caglar Gulcehre, Fethi Bougares, Holger Schwenk, and Yoshua Bengio. Learning phrase representations using rnn encoder-decoder for statistical machine translation. CoRR, abs/1406.1078, 2014.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.932,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 234.95565818174043,\n y: 155.04768656967278,\n },\n {\n x: 1051.617910566121,\n y: 155.04768656967278,\n },\n {\n x: 1051.617910566121,\n y: 219.22101676195186,\n },\n {\n x: 234.95565818174043,\n y: 219.22101676195186,\n },\n ],\n boundingBox: {\n left: 234.95565818174043,\n top: 155.04768656967278,\n right: 1051.617910566121,\n bottom: 219.22101676195186,\n },\n },\n {\n id: "block_11_fZULb0",\n type: "text",\n content:\n "[6] Francois Chollet. Xception: Deep learning with depthwise separable convolutions. arXiv preprint arXiv: 1610.02357, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.916,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 234.37082610861228,\n y: 242.1581676597882,\n },\n {\n x: 1050.1136779785156,\n y: 242.1581676597882,\n },\n {\n x: 1050.1136779785156,\n y: 284.96119192309845,\n },\n {\n x: 234.37082610861228,\n y: 284.96119192309845,\n },\n ],\n boundingBox: {\n left: 234.37082610861228,\n top: 242.1581676597882,\n right: 1050.1136779785156,\n bottom: 284.96119192309845,\n },\n },\n {\n id: "block_11_KQxaZG",\n type: "text",\n content:\n "[7] Junyoung Chung, \\u00c7aglar G\\u00fcl\\u00e7ehre, Kyunghyun Cho, and Yoshua Bengio. Empirical evaluation of gated recurrent neural networks on sequence modeling. CoRR, abs/1412.3555, 2014.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.937,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 234.59709056102446,\n y: 305.8525607747243,\n },\n {\n x: 1050.252182118214,\n y: 305.8525607747243,\n },\n {\n x: 1050.252182118214,\n y: 348.70033444856347,\n },\n {\n x: 234.59709056102446,\n y: 348.70033444856347,\n },\n ],\n boundingBox: {\n left: 234.59709056102446,\n top: 305.8525607747243,\n right: 1050.252182118214,\n bottom: 348.70033444856347,\n },\n },\n {\n id: "block_11_lSxX1m",\n type: "text",\n content:\n "[8] Chris Dyer, Adhiguna Kuncoro, Miguel Ballesteros, and Noah A. Smith. Recurrent neural network grammars. In Proc. of NAACL, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.92,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 234.54393261540545,\n y: 369.88837531814,\n },\n {\n x: 1049.7648141679972,\n y: 369.88837531814,\n },\n {\n x: 1049.7648141679972,\n y: 412.63161531606113,\n },\n {\n x: 234.54393261540545,\n y: 412.63161531606113,\n },\n ],\n boundingBox: {\n left: 234.54393261540545,\n top: 369.88837531814,\n right: 1049.7648141679972,\n bottom: 412.63161531606113,\n },\n },\n {\n id: "block_11_3YLXoz",\n type: "text",\n content:\n "[9] Jonas Gehring, Michael Auli, David Grangier, Denis Yarats, and Yann N. Dauphin. Convolu- tional sequence to sequence learning. arXiv preprint arXiv: 1705.03122v2, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.927,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 233.81299902922916,\n y: 434.3302966813395,\n },\n {\n x: 1052.8067929901345,\n y: 434.3302966813395,\n },\n {\n x: 1052.8067929901345,\n y: 476.945989020785,\n },\n {\n x: 233.81299902922916,\n y: 476.945989020785,\n },\n ],\n boundingBox: {\n left: 233.81299902922916,\n top: 434.3302966813395,\n right: 1052.8067929901345,\n bottom: 476.945989020785,\n },\n },\n {\n id: "block_11_OkxRaO",\n type: "text",\n content:\n "[10] Alex Graves. Generating sequences with recurrent neural networks. arXiv preprint arXiv: 1308.0850, 2013.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.904,\n avgOcrConfidence: 0.986,\n },\n polygon: [\n {\n x: 224.38643378932983,\n y: 498.1091927836712,\n },\n {\n x: 1050.5877919440723,\n y: 498.1091927836712,\n },\n {\n x: 1050.5877919440723,\n y: 539.0395607625632,\n },\n {\n x: 224.38643378932983,\n y: 539.0395607625632,\n },\n ],\n boundingBox: {\n left: 224.38643378932983,\n top: 498.1091927836712,\n right: 1050.5877919440723,\n bottom: 539.0395607625632,\n },\n },\n {\n id: "block_11_RVnHcs",\n type: "text",\n content:\n "[11] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for im- age recognition. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 770-778, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.919,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.3475475450502,\n y: 561.9494121522832,\n },\n {\n x: 1053.1976908662893,\n y: 561.9494121522832,\n },\n {\n x: 1053.1976908662893,\n y: 627.2271530610278,\n },\n {\n x: 224.3475475450502,\n y: 627.2271530610278,\n },\n ],\n boundingBox: {\n left: 224.3475475450502,\n top: 561.9494121522832,\n right: 1053.1976908662893,\n bottom: 627.2271530610278,\n },\n },\n {\n id: "block_11_s96TQd",\n type: "text",\n content:\n "[12] Sepp Hochreiter, Yoshua Bengio, Paolo Frasconi, and J\\u00fcrgen Schmidhuber. Gradient flow in recurrent nets: the difficulty of learning long-term dependencies, 2001.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.892,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 224.27874516396628,\n y: 647.9830188034173,\n },\n {\n x: 1048.8635432111087,\n y: 647.9830188034173,\n },\n {\n x: 1048.8635432111087,\n y: 692.1669293740639,\n },\n {\n x: 224.27874516396628,\n y: 692.1669293740639,\n },\n ],\n boundingBox: {\n left: 224.27874516396628,\n top: 647.9830188034173,\n right: 1048.8635432111087,\n bottom: 692.1669293740639,\n },\n },\n {\n id: "block_11_bKrlBK",\n type: "text",\n content:\n "[13] Sepp Hochreiter and J\\u00fcrgen Schmidhuber. Long short-term memory. Neural computation, 9(8):1735-1780, 1997.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.903,\n avgOcrConfidence: 0.984,\n },\n polygon: [\n {\n x: 224.36335765532334,\n y: 712.3709330738038,\n },\n {\n x: 1051.7104044447851,\n y: 712.3709330738038,\n },\n {\n x: 1051.7104044447851,\n y: 754.2910917181719,\n },\n {\n x: 224.36335765532334,\n y: 754.2910917181719,\n },\n ],\n boundingBox: {\n left: 224.36335765532334,\n top: 712.3709330738038,\n right: 1051.7104044447851,\n bottom: 754.2910917181719,\n },\n },\n {\n id: "block_11_c3sQ7S",\n type: "text",\n content:\n "[14] Zhongqiang Huang and Mary Harper. Self-training PCFG grammars with latent annotations across languages. In Proceedings of the 2009 Conference on Empirical Methods in Natural Language Processing, pages 832-841. ACL, August 2009.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.70277800177138,\n y: 777.0990849258308,\n },\n {\n x: 1050.1772024335653,\n y: 777.0990849258308,\n },\n {\n x: 1050.1772024335653,\n y: 842.7015786995565,\n },\n {\n x: 224.70277800177138,\n y: 842.7015786995565,\n },\n ],\n boundingBox: {\n left: 224.70277800177138,\n top: 777.0990849258308,\n right: 1050.1772024335653,\n bottom: 842.7015786995565,\n },\n },\n {\n id: "block_11_HmSxMA",\n type: "text",\n content:\n "[15] Rafal Jozefowicz, Oriol Vinyals, Mike Schuster, Noam Shazeer, and Yonghui Wu. Exploring the limits of language modeling. arXiv preprint arXiv: 1602.02410, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.906,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 223.96287430811972,\n y: 863.015632801486,\n },\n {\n x: 1049.822942357864,\n y: 863.015632801486,\n },\n {\n x: 1049.822942357864,\n y: 907.0369301702743,\n },\n {\n x: 223.96287430811972,\n y: 907.0369301702743,\n },\n ],\n boundingBox: {\n left: 223.96287430811972,\n top: 863.015632801486,\n right: 1049.822942357864,\n bottom: 907.0369301702743,\n },\n },\n {\n id: "block_11_XlCObz",\n type: "text",\n content:\n "[16] \\u0141ukasz Kaiser and Samy Bengio. Can active memory replace attention? In Advances in Neural Information Processing Systems, (NIPS), 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.902,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.17545875493627,\n y: 927.1137413655905,\n },\n {\n x: 1050.2528448174469,\n y: 927.1137413655905,\n },\n {\n x: 1050.2528448174469,\n y: 970.5487977795134,\n },\n {\n x: 224.17545875493627,\n y: 970.5487977795134,\n },\n ],\n boundingBox: {\n left: 224.17545875493627,\n top: 927.1137413655905,\n right: 1050.2528448174469,\n bottom: 970.5487977795134,\n },\n },\n {\n id: "block_11_48mMcn",\n type: "text",\n content:\n "[17] \\u0141ukasz Kaiser and Ilya Sutskever. Neural GPUs learn algorithms. In International Conference on Learning Representations (ICLR), 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.903,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 224.42198286961465,\n y: 991.1752927392946,\n },\n {\n x: 1049.7810976348653,\n y: 991.1752927392946,\n },\n {\n x: 1049.7810976348653,\n y: 1034.8329123590227,\n },\n {\n x: 224.42198286961465,\n y: 1034.8329123590227,\n },\n ],\n boundingBox: {\n left: 224.42198286961465,\n top: 991.1752927392946,\n right: 1049.7810976348653,\n bottom: 1034.8329123590227,\n },\n },\n {\n id: "block_11_lBImir",\n type: "text",\n content:\n "[18] Nal Kalchbrenner, Lasse Espeholt, Karen Simonyan, Aaron van den Oord, Alex Graves, and Ko- ray Kavukcuoglu. Neural machine translation in linear time. arXiv preprint arXiv: 1610.10099v2, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.934,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.23202486803933,\n y: 1055.1385374714557,\n },\n {\n x: 1052.4190192675069,\n y: 1055.1385374714557,\n },\n {\n x: 1052.4190192675069,\n y: 1117.975328259002,\n },\n {\n x: 224.23202486803933,\n y: 1117.975328259002,\n },\n ],\n boundingBox: {\n left: 224.23202486803933,\n top: 1055.1385374714557,\n right: 1052.4190192675069,\n bottom: 1117.975328259002,\n },\n },\n {\n id: "block_11_Y0ddKF",\n type: "text",\n content:\n "[19] Yoon Kim, Carl Denton, Luong Hoang, and Alexander M. Rush. Structured attention networks. In International Conference on Learning Representations, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.974,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.29036606837366,\n y: 1142.1438929622334,\n },\n {\n x: 1052.7023705252766,\n y: 1142.1438929622334,\n },\n {\n x: 1052.7023705252766,\n y: 1185.793178300212,\n },\n {\n x: 224.29036606837366,\n y: 1185.793178300212,\n },\n ],\n boundingBox: {\n left: 224.29036606837366,\n top: 1142.1438929622334,\n right: 1052.7023705252766,\n bottom: 1185.793178300212,\n },\n },\n {\n id: "block_11_nehypx",\n type: "text",\n content:\n "[20] Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In ICLR, 2015.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 223.92950266817192,\n y: 1205.8213097134928,\n },\n {\n x: 1052.7550077786411,\n y: 1205.8213097134928,\n },\n {\n x: 1052.7550077786411,\n y: 1227.2851158658366,\n },\n {\n x: 223.92950266817192,\n y: 1227.2851158658366,\n },\n ],\n boundingBox: {\n left: 223.92950266817192,\n top: 1205.8213097134928,\n right: 1052.7550077786411,\n bottom: 1227.2851158658366,\n },\n },\n {\n id: "block_11_af7MVz",\n type: "text",\n content:\n "[21] Oleksii Kuchaiev and Boris Ginsburg. Factorization tricks for LSTM networks. arXiv preprint arXiv: 1703.10722, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.925,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 223.78512890669552,\n y: 1247.11833873548,\n },\n {\n x: 1050.4177622551465,\n y: 1247.11833873548,\n },\n {\n x: 1050.4177622551465,\n y: 1289.109575544085,\n },\n {\n x: 223.78512890669552,\n y: 1289.109575544085,\n },\n ],\n boundingBox: {\n left: 223.78512890669552,\n top: 1247.11833873548,\n right: 1050.4177622551465,\n bottom: 1289.109575544085,\n },\n },\n {\n id: "block_11_vnPlfZ",\n type: "text",\n content:\n "[22] Zhouhan Lin, Minwei Feng, Cicero Nogueira dos Santos, Mo Yu, Bing Xiang, Bowen Zhou, and Yoshua Bengio. A structured self-attentive sentence embedding. arXiv preprint arXiv: 1703.03130, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.74063338676507,\n y: 1311.0246641116034,\n },\n {\n x: 1050.2205618976677,\n y: 1311.0246641116034,\n },\n {\n x: 1050.2205618976677,\n y: 1375.8748468958345,\n },\n {\n x: 223.74063338676507,\n y: 1375.8748468958345,\n },\n ],\n boundingBox: {\n left: 223.74063338676507,\n top: 1311.0246641116034,\n right: 1050.2205618976677,\n bottom: 1375.8748468958345,\n },\n },\n {\n id: "block_11_g0SHxO",\n type: "text",\n content:\n "[23] Minh-Thang Luong, Quoc V. Le, Ilya Sutskever, Oriol Vinyals, and Lukasz Kaiser. Multi-task sequence to sequence learning. arXiv preprint arXiv: 1511.06114, 2015.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.355428932357,\n y: 1397.7982697451025,\n },\n {\n x: 1050.4997476174015,\n y: 1397.7982697451025,\n },\n {\n x: 1050.4997476174015,\n y: 1441.9434448471643,\n },\n {\n x: 224.355428932357,\n y: 1441.9434448471643,\n },\n ],\n boundingBox: {\n left: 224.355428932357,\n top: 1397.7982697451025,\n right: 1050.4997476174015,\n bottom: 1441.9434448471643,\n },\n },\n {\n id: "block_11_gDtqYI",\n type: "text",\n content:\n "[24] Minh-Thang Luong, Hieu Pham, and Christopher D Manning. Effective approaches to attention- based neural machine translation. arXiv preprint arXiv: 1508.04025, 2015.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.927,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 224.7064228475529,\n y: 1461.612349775501,\n },\n {\n x: 1052.9802308465444,\n y: 1461.612349775501,\n },\n {\n x: 1052.9802308465444,\n y: 1506.2439438669305,\n },\n {\n x: 224.7064228475529,\n y: 1506.2439438669305,\n },\n ],\n boundingBox: {\n left: 224.7064228475529,\n top: 1461.612349775501,\n right: 1052.9802308465444,\n bottom: 1506.2439438669305,\n },\n },\n {\n id: "block_11_JWTkzE",\n type: "page_number",\n content: "11",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 629.039650241824,\n y: 1547.854550239735,\n },\n {\n x: 645.38100862155,\n y: 1547.854550239735,\n },\n {\n x: 645.38100862155,\n y: 1563.4467601919532,\n },\n {\n x: 629.039650241824,\n y: 1563.4467601919532,\n },\n ],\n boundingBox: {\n left: 629.039650241824,\n top: 1547.854550239735,\n right: 645.38100862155,\n bottom: 1563.4467601919532,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_12_TQ4Lbe",\n type: "text",\n content:\n "[25] Mitchell P Marcus, Mary Ann Marcinkiewicz, and Beatrice Santorini. Building a large annotated corpus of english: The penn treebank. Computational linguistics, 19(2):313-330, 1993.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.94512343580706,\n y: 154.85743054411464,\n },\n {\n x: 1050.2930801280222,\n y: 154.85743054411464,\n },\n {\n x: 1050.2930801280222,\n y: 198.76930494953817,\n },\n {\n x: 223.94512343580706,\n y: 198.76930494953817,\n },\n ],\n boundingBox: {\n left: 223.94512343580706,\n top: 154.85743054411464,\n right: 1050.2930801280222,\n bottom: 198.76930494953817,\n },\n },\n {\n id: "block_12_LvCkff",\n type: "text",\n content:\n "[26] David McClosky, Eugene Charniak, and Mark Johnson. Effective self-training for parsing. In Proceedings of the Human Language Technology Conference of the NAACL, Main Conference, pages 152-159. ACL, June 2006.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.907,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.21323261121762,\n y: 226.782506971431,\n },\n {\n x: 1051.9384676522582,\n y: 226.782506971431,\n },\n {\n x: 1051.9384676522582,\n y: 292.8687442406676,\n },\n {\n x: 224.21323261121762,\n y: 292.8687442406676,\n },\n ],\n boundingBox: {\n left: 224.21323261121762,\n top: 226.782506971431,\n right: 1051.9384676522582,\n bottom: 292.8687442406676,\n },\n },\n {\n id: "block_12_Rm8AFL",\n type: "text",\n content:\n "[27] Ankur Parikh, Oscar T\\u00e4ckstr\\u00f6m, Dipanjan Das, and Jakob Uszkoreit. A decomposable attention model. In Empirical Methods in Natural Language Processing, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.916,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.08847948060418,\n y: 321.2656073462694,\n },\n {\n x: 1048.8436622341185,\n y: 321.2656073462694,\n },\n {\n x: 1048.8436622341185,\n y: 364.85913349811295,\n },\n {\n x: 224.08847948060418,\n y: 364.85913349811295,\n },\n ],\n boundingBox: {\n left: 224.08847948060418,\n top: 321.2656073462694,\n right: 1048.8436622341185,\n bottom: 364.85913349811295,\n },\n },\n {\n id: "block_12_cqas9e",\n type: "text",\n content:\n "[28] Romain Paulus, Caiming Xiong, and Richard Socher. A deep reinforced model for abstractive summarization. arXiv preprint arXiv: 1705.04304, 2017.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.67392691730583,\n y: 392.7383714116606,\n },\n {\n x: 1049.3349117084142,\n y: 392.7383714116606,\n },\n {\n x: 1049.3349117084142,\n y: 435.42904860991285,\n },\n {\n x: 224.67392691730583,\n y: 435.42904860991285,\n },\n ],\n boundingBox: {\n left: 224.67392691730583,\n top: 392.7383714116606,\n right: 1049.3349117084142,\n bottom: 435.42904860991285,\n },\n },\n {\n id: "block_12_hfa5dB",\n type: "text",\n content:\n "[29] Slav Petrov, Leon Barrett, Romain Thibaux, and Dan Klein. Learning accurate, compact, and interpretable tree annotation. In Proceedings of the 21st International Conference on Computational Linguistics and 44th Annual Meeting of the ACL, pages 433-440. ACL, July 2006.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.899,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.91392923619625,\n y: 463.67279296530813,\n },\n {\n x: 1051.5214404920591,\n y: 463.67279296530813,\n },\n {\n x: 1051.5214404920591,\n y: 549.7230681799408,\n },\n {\n x: 223.91392923619625,\n y: 549.7230681799408,\n },\n ],\n boundingBox: {\n left: 223.91392923619625,\n top: 463.67279296530813,\n right: 1051.5214404920591,\n bottom: 549.7230681799408,\n },\n },\n {\n id: "block_12_H2k7w4",\n type: "text",\n content:\n "[30] Ofir Press and Lior Wolf. Using the output embedding to improve language models. arXiv preprint arXiv: 1608.05859, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.898,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 224.29183347381814,\n y: 581.8894180068396,\n },\n {\n x: 1049.7876299558764,\n y: 581.8894180068396,\n },\n {\n x: 1049.7876299558764,\n y: 624.918793785841,\n },\n {\n x: 224.29183347381814,\n y: 624.918793785841,\n },\n ],\n boundingBox: {\n left: 224.29183347381814,\n top: 581.8894180068396,\n right: 1049.7876299558764,\n bottom: 624.918793785841,\n },\n },\n {\n id: "block_12_UrZIEK",\n type: "text",\n content:\n "[31] Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words with subword units. arXiv preprint arXiv: 1508.07909, 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.925,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.35140540129947,\n y: 653.3260510666926,\n },\n {\n x: 1049.4855337769445,\n y: 653.3260510666926,\n },\n {\n x: 1049.4855337769445,\n y: 696.2955715494944,\n },\n {\n x: 224.35140540129947,\n y: 696.2955715494944,\n },\n ],\n boundingBox: {\n left: 224.35140540129947,\n top: 653.3260510666926,\n right: 1049.4855337769445,\n bottom: 696.2955715494944,\n },\n },\n {\n id: "block_12_IIwlxZ",\n type: "text",\n content:\n "[32] Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz, Andy Davis, Quoc Le, Geoffrey Hinton, and Jeff Dean. Outrageously large neural networks: The sparsely-gated mixture-of-experts layer. arXiv preprint arXiv: 1701.06538, 2017.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.88,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.15238262092979,\n y: 724.7319041087216,\n },\n {\n x: 1051.274348349467,\n y: 724.7319041087216,\n },\n {\n x: 1051.274348349467,\n y: 791.0497254966793,\n },\n {\n x: 224.15238262092979,\n y: 791.0497254966793,\n },\n ],\n boundingBox: {\n left: 224.15238262092979,\n top: 724.7319041087216,\n right: 1051.274348349467,\n bottom: 791.0497254966793,\n },\n },\n {\n id: "block_12_pGLzhM",\n type: "text",\n content:\n "[33] Nitish Srivastava, Geoffrey E Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdi- nov. Dropout: a simple way to prevent neural networks from overfitting. Journal of Machine Learning Research, 15(1):1929-1958, 2014.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.938,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.4417928431156,\n y: 819.0001126052741,\n },\n {\n x: 1053.3042907714844,\n y: 819.0001126052741,\n },\n {\n x: 1053.3042907714844,\n y: 885.2761205228649,\n },\n {\n x: 224.4417928431156,\n y: 885.2761205228649,\n },\n ],\n boundingBox: {\n left: 224.4417928431156,\n top: 819.0001126052741,\n right: 1053.3042907714844,\n bottom: 885.2761205228649,\n },\n },\n {\n id: "block_12_Bz8MfK",\n type: "text",\n content:\n "[34] Sainbayar Sukhbaatar, Arthur Szlam, Jason Weston, and Rob Fergus. End-to-end memory networks. In C. Cortes, N. D. Lawrence, D. D. Lee, M. Sugiyama, and R. Garnett, editors, Advances in Neural Information Processing Systems 28, pages 2440-2448. Curran Associates, Inc., 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.897,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.0948934624665,\n y: 913.8373252467105,\n },\n {\n x: 1051.823347328353,\n y: 913.8373252467105,\n },\n {\n x: 1051.823347328353,\n y: 1000.8878563328793,\n },\n {\n x: 224.0948934624665,\n y: 1000.8878563328793,\n },\n ],\n boundingBox: {\n left: 224.0948934624665,\n top: 913.8373252467105,\n right: 1051.823347328353,\n bottom: 1000.8878563328793,\n },\n },\n {\n id: "block_12_m0nnSr",\n type: "text",\n content:\n "[35] Ilya Sutskever, Oriol Vinyals, and Quoc VV Le. Sequence to sequence learning with neural networks. In Advances in Neural Information Processing Systems, pages 3104-3112, 2014.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.899,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.52872478178818,\n y: 1030.965426796361,\n },\n {\n x: 1050.1110271815835,\n y: 1030.965426796361,\n },\n {\n x: 1050.1110271815835,\n y: 1074.9609636579241,\n },\n {\n x: 224.52872478178818,\n y: 1074.9609636579241,\n },\n ],\n boundingBox: {\n left: 224.52872478178818,\n top: 1030.965426796361,\n right: 1050.1110271815835,\n bottom: 1074.9609636579241,\n },\n },\n {\n id: "block_12_C1nzdD",\n type: "text",\n content:\n "[36] Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, and Zbigniew Wojna. Rethinking the inception architecture for computer vision. CoRR, abs/1512.00567, 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.939,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.60145602261062,\n y: 1102.9526906981505,\n },\n {\n x: 1051.9790816481095,\n y: 1102.9526906981505,\n },\n {\n x: 1051.9790816481095,\n y: 1146.15116715969,\n },\n {\n x: 224.60145602261062,\n y: 1146.15116715969,\n },\n ],\n boundingBox: {\n left: 224.60145602261062,\n top: 1102.9526906981505,\n right: 1051.9790816481095,\n bottom: 1146.15116715969,\n },\n },\n {\n id: "block_12_smJ629",\n type: "text",\n content:\n "[37] Vinyals & Kaiser, Koo, Petrov, Sutskever, and Hinton. Grammar as a foreign language. In Advances in Neural Information Processing Systems, 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.70363004364236,\n y: 1173.716330506748,\n },\n {\n x: 1049.93891472364,\n y: 1173.716330506748,\n },\n {\n x: 1049.93891472364,\n y: 1218.0808487512115,\n },\n {\n x: 224.70363004364236,\n y: 1218.0808487512115,\n },\n ],\n boundingBox: {\n left: 224.70363004364236,\n top: 1173.716330506748,\n right: 1049.93891472364,\n bottom: 1218.0808487512115,\n },\n },\n {\n id: "block_12_oKrqzS",\n type: "text",\n content:\n "[38] Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. Google\'s neural machine translation system: Bridging the gap between human and machine translation. arXiv preprint arXiv: 1609.08144, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.935,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.222865417926,\n y: 1246.0137622804568,\n },\n {\n x: 1050.4285547855127,\n y: 1246.0137622804568,\n },\n {\n x: 1050.4285547855127,\n y: 1332.3901636224045,\n },\n {\n x: 224.222865417926,\n y: 1332.3901636224045,\n },\n ],\n boundingBox: {\n left: 224.222865417926,\n top: 1246.0137622804568,\n right: 1050.4285547855127,\n bottom: 1332.3901636224045,\n },\n },\n {\n id: "block_12_5hQUgX",\n type: "text",\n content:\n "[39] Jie Zhou, Ying Cao, Xuguang Wang, Peng Li, and Wei Xu. Deep recurrent models with fast-forward connections for neural machine translation. CoRR, abs/1606.04199, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.977,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.40534438530025,\n y: 1362.7727877394598,\n },\n {\n x: 1049.6643678985372,\n y: 1362.7727877394598,\n },\n {\n x: 1049.6643678985372,\n y: 1404.796982844073,\n },\n {\n x: 224.40534438530025,\n y: 1404.796982844073,\n },\n ],\n boundingBox: {\n left: 224.40534438530025,\n top: 1362.7727877394598,\n right: 1049.6643678985372,\n bottom: 1404.796982844073,\n },\n },\n {\n id: "block_12_7qyMnf",\n type: "text",\n content:\n "[40] Muhua Zhu, Yue Zhang, Wenliang Chen, Min Zhang, and Jingbo Zhu. Fast and accurate shift-reduce constituent parsing. In Proceedings of the 51st Annual Meeting of the ACL (Volume 1: Long Papers), pages 434-443. ACL, August 2013.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.905,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.04902520841057,\n y: 1434.5126750056904,\n },\n {\n x: 1049.9945814592124,\n y: 1434.5126750056904,\n },\n {\n x: 1049.9945814592124,\n y: 1501.148572362455,\n },\n {\n x: 224.04902520841057,\n y: 1501.148572362455,\n },\n ],\n boundingBox: {\n left: 224.04902520841057,\n top: 1434.5126750056904,\n right: 1049.9945814592124,\n bottom: 1501.148572362455,\n },\n },\n {\n id: "block_12_6o6JUd",\n type: "page_number",\n content: "12",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.998,\n avgOcrConfidence: 0.998,\n },\n polygon: [\n {\n x: 628.997000812614,\n y: 1547.789391309695,\n },\n {\n x: 647.0427269483133,\n y: 1547.789391309695,\n },\n {\n x: 647.0427269483133,\n y: 1563.398364533159,\n },\n {\n x: 628.997000812614,\n y: 1563.398364533159,\n },\n ],\n boundingBox: {\n left: 628.997000812614,\n top: 1547.789391309695,\n right: 647.0427269483133,\n bottom: 1563.398364533159,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_13_KlKk5h",\n type: "page_number",\n content: "13",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.999,\n avgOcrConfidence: 0.999,\n },\n polygon: [\n {\n x: 103.29433033878627,\n y: 628.7723457726248,\n },\n {\n x: 103.29433033878627,\n y: 646.9001519418981,\n },\n {\n x: 87.59273293860883,\n y: 646.9001519418981,\n },\n {\n x: 87.59273293860883,\n y: 628.7723457726248,\n },\n ],\n boundingBox: {\n left: 87.59273293860883,\n top: 628.7723457726248,\n right: 103.29433033878627,\n bottom: 646.9001519418981,\n },\n },\n {\n id: "block_13_PkaOm5",\n type: "text",\n content:\n "the word \'making\'. Different colors represent different heads. Best viewed in color. the verb \'making\', completing the phrase \'making ... more difficult\'. Attentions here shown only for encoder self-attention in layer 5 of 6. Many of the attention heads attend to a distant dependency of Figure 3: An example of the attention mechanism following long-distance dependencies in the",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.937,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 999.8870322148603,\n y: 224.33585563715354,\n },\n {\n x: 999.8870322148603,\n y: 1052.0067256732577,\n },\n {\n x: 911.037953656419,\n y: 1052.0067256732577,\n },\n {\n x: 911.037953656419,\n y: 224.33585563715354,\n },\n ],\n boundingBox: {\n left: 911.037953656419,\n top: 224.33585563715354,\n right: 999.8870322148603,\n bottom: 1052.0067256732577,\n },\n },\n {\n id: "block_13_xamkHQ",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nIt It is is in in this this spirit spirit that that a a majority majority of of American American governments governments have have passed passed new new laws laws since since 2009 2009 making making the the registration registration or or voting voting process process more more difficult difficult\\n\\n. . <EOS> <EOS> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad>\\n<caption>Diagram showing attention mechanism or word alignment between two identical sequences of text. The word \'making\' in the right column is highlighted in gray and acts as the target for connections from the left column. Connections originate from the words \'laws\', \'2009\', \'making\', \'more\', and \'difficult\' in the left column and point to \'making\' in the right column. The sequence of text is: \'It is in this spirit that a majority of American governments have passed new laws since 2009 making the registration or voting process more difficult. <EOS> <pad> <pad> <pad> <pad> <pad> <pad> <pad>\'</caption>\\n</figure>",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.717,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 1444.0009233001479,\n y: 252.8656019781628,\n },\n {\n x: 1444.0009233001479,\n y: 1047.5539548553688,\n },\n {\n x: 1022.9538143416097,\n y: 1047.5539548553688,\n },\n {\n x: 1022.9538143416097,\n y: 252.8656019781628,\n },\n ],\n boundingBox: {\n left: 1022.9538143416097,\n top: 252.8656019781628,\n right: 1444.0009233001479,\n bottom: 1047.5539548553688,\n },\n },\n {\n id: "block_13_5eYqPZ",\n type: "heading",\n content: "# Attention Visualizations",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 1498.6412794643775,\n y: 224.94428453654268,\n },\n {\n x: 1498.6412794643775,\n y: 480.8453803514912,\n },\n {\n x: 1479.199057528847,\n y: 480.8453803514912,\n },\n {\n x: 1479.199057528847,\n y: 224.94428453654268,\n },\n ],\n boundingBox: {\n left: 1479.199057528847,\n top: 224.94428453654268,\n right: 1498.6412794643775,\n bottom: 480.8453803514912,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_14_DaAuYi",\n type: "page_number",\n content: "14",\n metadata: {\n page: {\n number: 14,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.998,\n avgOcrConfidence: 0.998,\n },\n polygon: [\n {\n x: 103.12243577770732,\n y: 628.7327731612825,\n },\n {\n x: 103.12243577770732,\n y: 647.0026336447166,\n },\n {\n x: 87.74237117910752,\n y: 647.0026336447166,\n },\n {\n x: 87.74237117910752,\n y: 628.7327731612825,\n },\n ],\n boundingBox: {\n left: 87.74237117910752,\n top: 628.7327731612825,\n right: 103.12243577770732,\n bottom: 647.0026336447166,\n },\n },\n {\n id: "block_14_VDKMys",\n type: "text",\n content:\n "and 6. Note that the attentions are very sharp for this word. Full attentions for head 5. Bottom: Isolated attentions from just the word \'its\' for attention heads 5 Figure 4: Two attention heads, also in layer 5 of 6, apparently involved in anaphora resolution. Top:",\n metadata: {\n page: {\n number: 14,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.972,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 370.4634644357782,\n y: 224.1528559775248,\n },\n {\n x: 370.4634644357782,\n y: 1051.3102287793681,\n },\n {\n x: 303.81733864232115,\n y: 1051.3102287793681,\n },\n {\n x: 303.81733864232115,\n y: 224.1528559775248,\n },\n ],\n boundingBox: {\n left: 303.81733864232115,\n top: 224.1528559775248,\n right: 370.4634644357782,\n bottom: 1051.3102287793681,\n },\n },\n {\n id: "block_14_QRz2LE",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nThe The The The Law Law Law Law will will will will never never never never be be be be perfect perfect perfect perfect , , , , but but but but its its its its application application application application should should should should be be be be just just just just - - - - this this this this is is is is what what what what we we we we are are are are missing missing missing missing , , , , in in in in my my my my opinion opinion opinion opinion . . . . <EOS> <EOS> <EOS> <EOS> <pad> <pad> <pad> <pad>\\n<caption>Attention weight visualization diagram showing alignment between two sequences of text tokens. The diagram consists of three columns of text, with lines connecting tokens between the columns to represent attention strength. Thicker, more opaque lines indicate higher attention weights. The text sequence is: \'The\', \'Law\', \'will\', \'never\', \'be\', \'perfect\', \',\', \'but\', \'its\', \'application\', \'should\', \'be\', \'just\', \'-\', \'this\', \'is\', \'what\', \'we\', \'are\', \'missing\', \',\', \'in\', \'my\', \'opinion\', \'.\', \'<EOS>\', \'<pad>\'. Specific highlights are present: the word \'Law\' in the first column and \'its\' in the second column are highlighted with a purple/grey background, and lines connect these highlighted tokens to corresponding tokens in the third column.</caption>\\n</figure>",\n metadata: {\n page: {\n number: 14,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.379,\n avgOcrConfidence: 0.963,\n },\n polygon: [\n {\n x: 1294.7974623916741,\n y: 255.12043611846704,\n },\n {\n x: 1294.7974623916741,\n y: 1044.444475382784,\n },\n {\n x: 388.9633916410289,\n y: 1044.444475382784,\n },\n {\n x: 388.9633916410289,\n y: 255.12043611846704,\n },\n ],\n boundingBox: {\n left: 388.9633916410289,\n top: 255.12043611846704,\n right: 1294.7974623916741,\n bottom: 1044.444475382784,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_15_pV91a2",\n type: "page_number",\n content: "15",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.998,\n avgOcrConfidence: 0.998,\n },\n polygon: [\n {\n x: 103.26014084206486,\n y: 628.7008215911197,\n },\n {\n x: 103.26014084206486,\n y: 647.1549124613296,\n },\n {\n x: 87.58487219559515,\n y: 647.1549124613296,\n },\n {\n x: 87.58487219559515,\n y: 628.7008215911197,\n },\n ],\n boundingBox: {\n left: 87.58487219559515,\n top: 628.7008215911197,\n right: 103.26014084206486,\n bottom: 647.1549124613296,\n },\n },\n {\n id: "block_15_2igWoi",\n type: "text",\n content:\n "at layer 5 of 6. The heads clearly learned to perform different tasks. sentence. We give two such examples above, from two different heads from the encoder self-attention Figure 5: Many of the attention heads exhibit behaviour that seems related to the structure of the",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.976,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 394.6980404387739,\n y: 223.74716570777616,\n },\n {\n x: 394.6980404387739,\n y: 1049.736980800211,\n },\n {\n x: 328.87227315113955,\n y: 1049.736980800211,\n },\n {\n x: 328.87227315113955,\n y: 223.74716570777616,\n },\n ],\n boundingBox: {\n left: 328.87227315113955,\n top: 223.74716570777616,\n right: 394.6980404387739,\n bottom: 1049.736980800211,\n },\n },\n {\n id: "block_15_OqCqJD",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nThe The Law Law will will never never be be perfect perfect , , but but its its application application should should be be just just - - this this is is what what we we are are missing missing , , in in my my opinion opinion\\n\\n. . <EOS> <EOS> <pad> <pad>\\n<caption>Attention weight visualization showing connections between two identical sequences of text: \'The Law will never be perfect , but its application should be just - this is what we are missing , in my opinion . <EOS> <pad>\'. The diagram uses lines of varying thickness and red color intensity to indicate the strength of attention between words in the left sequence and words in the right sequence. Stronger connections are represented by thicker, more opaque red lines, while weaker connections are represented by thinner, more transparent red lines.</caption>\\n</figure>",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.651,\n avgOcrConfidence: 0.969,\n },\n polygon: [\n {\n x: 810.314180990807,\n y: 253.4944325467966,\n },\n {\n x: 810.314180990807,\n y: 1035.3522419059364,\n },\n {\n x: 421.96601087527165,\n y: 1035.3522419059364,\n },\n {\n x: 421.96601087527165,\n y: 253.4944325467966,\n },\n ],\n boundingBox: {\n left: 421.96601087527165,\n top: 253.4944325467966,\n right: 810.314180990807,\n bottom: 1035.3522419059364,\n },\n },\n {\n id: "block_15_sK8Nre",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nThe The Law Law will will never never be be perfect perfect , , but but its its application application should should be be just just - - this this is is what what we we are are missing missing , , in in my my opinion opinion\\n\\n. . <EOS> <EOS> <pad> <pad>\\n<caption>Attention weight visualization diagram showing connections between two identical sequences of text: \'The\', \'Law\', \'will\', \'never\', \'be\', \'perfect\', \',\', \'but\', \'its\', \'application\', \'should\', \'be\', \'just\', \'-\', \'this\', \'is\', \'what\', \'we\', \'are\', \'missing\', \',\', \'in\', \'my\', \'opinion\', \'.\', \'<EOS>\', \'<pad>\'. The diagram displays lines connecting tokens from the left sequence to the right sequence, where line thickness and opacity represent the strength of the attention weight. Notable high-attention connections include: \'Law\' to \'Law\', \'application\' to \'application\', \'missing\' to \'missing\', \'opinion\' to \'opinion\', and \'<pad>\' to \'<pad>\'.</caption>\\n</figure>",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.6,\n avgOcrConfidence: 0.968,\n },\n polygon: [\n {\n x: 1255.9501913113702,\n y: 254.50874105857238,\n },\n {\n x: 1255.9501913113702,\n y: 1034.3072598868043,\n },\n {\n x: 882.2701913360366,\n y: 1034.3072598868043,\n },\n {\n x: 882.2701913360366,\n y: 254.50874105857238,\n },\n ],\n boundingBox: {\n left: 882.2701913360366,\n top: 254.50874105857238,\n right: 1255.9501913113702,\n bottom: 1034.3072598868043,\n },\n },\n ],\n },\n ],\n} satisfies ParsedOcrOutput\n\nconst BLOCK_STYLES: Record<\n OcrBlockType,\n {\n label: string\n icon: React.ComponentType<React.ComponentProps<"svg">>\n overlay: string\n mutedOverlay: string\n ring: string\n badge: string\n }\n> = {\n heading: {\n label: "Heading",\n icon: Heading01Glyph,\n overlay: "border-violet-500/70 bg-violet-500/10",\n mutedOverlay: "border-violet-500/35 bg-violet-500/5",\n ring: "border-violet-500/60 bg-violet-500/5 text-violet-600",\n badge:\n "bg-violet-50 text-violet-600 dark:bg-violet-300/10 dark:text-violet-300",\n },\n paragraph: {\n label: "Paragraph",\n icon: ParagraphGlyph,\n overlay: "border-blue-500/70 bg-blue-500/10",\n mutedOverlay: "border-blue-500/35 bg-blue-500/5",\n ring: "border-blue-500/60 bg-blue-500/5 text-blue-600",\n badge: "bg-blue-50 text-blue-600 dark:bg-blue-300/10 dark:text-blue-300",\n },\n list: {\n label: "List",\n icon: LeftToRightListBulletGlyph,\n overlay: "border-emerald-500/70 bg-emerald-500/10",\n mutedOverlay: "border-emerald-500/35 bg-emerald-500/5",\n ring: "border-emerald-500/60 bg-emerald-500/5 text-emerald-600",\n badge:\n "bg-emerald-50 text-emerald-600 dark:bg-emerald-300/10 dark:text-emerald-300",\n },\n table: {\n label: "Table",\n icon: Table01Glyph,\n overlay: "border-amber-500/70 bg-amber-500/10",\n mutedOverlay: "border-amber-500/35 bg-amber-500/5",\n ring: "border-amber-500/60 bg-amber-500/5 text-amber-700",\n badge:\n "bg-amber-50 text-amber-600 dark:bg-amber-300/10 dark:text-amber-300",\n },\n figure: {\n label: "Figure",\n icon: ImageCompositionGlyph,\n overlay: "border-rose-500/70 bg-rose-500/10",\n mutedOverlay: "border-rose-500/35 bg-rose-500/5",\n ring: "border-rose-500/60 bg-rose-500/5 text-rose-600",\n badge: "bg-rose-50 text-rose-600 dark:bg-rose-300/10 dark:text-rose-300",\n },\n header: {\n label: "Header",\n icon: TextCenterlineCenterTopGlyph,\n overlay: "border-cyan-500/70 bg-cyan-500/10",\n mutedOverlay: "border-cyan-500/35 bg-cyan-500/5",\n ring: "border-cyan-500/60 bg-cyan-500/5 text-cyan-700",\n badge: "bg-cyan-50 text-cyan-600 dark:bg-cyan-300/10 dark:text-cyan-300",\n },\n footer: {\n label: "Footer",\n icon: AlignBoxBottomCenterGlyph,\n overlay: "border-slate-500/70 bg-slate-500/10",\n mutedOverlay: "border-slate-500/35 bg-slate-500/5",\n ring: "border-slate-500/60 bg-slate-500/5 text-slate-700",\n badge:\n "bg-slate-50 text-slate-600 dark:bg-slate-300/10 dark:text-slate-300",\n },\n page_number: {\n label: "Page number",\n icon: TextNumberSignGlyph,\n overlay: "border-zinc-500/70 bg-zinc-500/10",\n mutedOverlay: "border-zinc-500/35 bg-zinc-500/5",\n ring: "border-zinc-500/60 bg-zinc-500/5 text-zinc-700",\n badge: "bg-zinc-50 text-zinc-600 dark:bg-zinc-300/10 dark:text-zinc-300",\n },\n}\n\nfunction getBlockType(block: ParsedOcrBlock): OcrBlockType | undefined {\n if (block.type === "heading" || block.type === "section_heading") {\n return "heading"\n }\n\n if (block.type === "header") {\n return "header"\n }\n\n if (block.type === "footer") {\n return "footer"\n }\n\n if (block.type === "page_number") {\n return "page_number"\n }\n\n if (block.type === "figure" || block.type === "image") {\n return "figure"\n }\n\n if (block.type === "table") {\n return "table"\n }\n\n if (block.metadata.layoutClass === "List Item") {\n return "list"\n }\n\n if (block.type === "text") {\n return "paragraph"\n }\n}\n\nexport function getOcrBlocks(output: ParsedOcrOutput): OcrBlock[] {\n return output.chunks.flatMap((chunk) =>\n chunk.blocks.flatMap((block) => {\n const type = getBlockType(block)\n const { page } = block.metadata\n\n if (!type || page.width <= 0 || page.height <= 0) {\n return []\n }\n\n return {\n id: block.id,\n type,\n text: block.content,\n page: page.number,\n pageWidth: page.width,\n pageHeight: page.height,\n confidence:\n block.metadata.avgOcrConfidence ??\n block.metadata.minOcrConfidence ??\n 1,\n polygon: block.polygon,\n boundingBox: block.boundingBox,\n }\n })\n )\n}\n\nfunction getBoundingBox(block: OcrBlock): BoundingBox {\n if (block.boundingBox) {\n return block.boundingBox\n }\n\n const polygon = block.polygon ?? []\n const xValues = polygon.map((point) => point.x)\n const yValues = polygon.map((point) => point.y)\n const left = Math.min(...xValues)\n const right = Math.max(...xValues)\n const top = Math.min(...yValues)\n const bottom = Math.max(...yValues)\n\n return { left, top, right, bottom }\n}\n\nfunction getBlockCoordinateRotation(\n block: OcrBlock,\n pageSize?: { width: number; height: number }\n) {\n const blockIsLandscape = block.pageWidth > block.pageHeight\n\n if (!pageSize) return blockIsLandscape ? 1 : 0\n\n const pageIsLandscape = pageSize.width > pageSize.height\n\n if (blockIsLandscape && !pageIsLandscape) return 1\n if (!blockIsLandscape && pageIsLandscape) return 3\n\n return 0\n}\n\nfunction normalizeHighlightAreaForRotation(\n area: HighlightArea,\n rotation: number\n): HighlightArea {\n if (rotation === 1) {\n return {\n left: area.top,\n top: 100 - area.left - area.width,\n width: area.height,\n height: area.width,\n }\n }\n\n if (rotation === 3) {\n return {\n left: 100 - area.top - area.height,\n top: area.left,\n width: area.height,\n height: area.width,\n }\n }\n\n return area\n}\n\nexport function blockToHighlightArea(\n block: OcrBlock,\n pageSize?: { width: number; height: number }\n): HighlightArea {\n const { left, top, right, bottom } = getBoundingBox(block)\n\n const area = {\n left: (left / block.pageWidth) * 100,\n top: (top / block.pageHeight) * 100,\n width: ((right - left) / block.pageWidth) * 100,\n height: ((bottom - top) / block.pageHeight) * 100,\n }\n\n return normalizeHighlightAreaForRotation(\n area,\n getBlockCoordinateRotation(block, pageSize)\n )\n}\n\nexport function blockToArea(\n block: OcrBlock,\n pageSize?: { width: number; height: number }\n): React.CSSProperties {\n const area = blockToHighlightArea(block, pageSize)\n\n return {\n left: `${area.left}%`,\n top: `${area.top}%`,\n width: `${area.width}%`,\n height: `${area.height}%`,\n }\n}\n\nconst OcrBlockMarkdown = React.memo(function OcrBlockMarkdown({\n text,\n}: {\n text: string\n}) {\n const markdown = text.replace(OCR_MARKDOWN_FIGURE_CAPTION_PATTERN, (tag) =>\n tag.startsWith("</") ? "</figcaption>" : "<figcaption>"\n )\n\n return (\n <div className="space-y-1 text-sm leading-5 text-foreground/90">\n <ReactMarkdown\n rehypePlugins={OCR_MARKDOWN_REHYPE_PLUGINS}\n remarkPlugins={OCR_MARKDOWN_REMARK_PLUGINS}\n components={{\n h1: ({ node: _node, ...props }) => (\n <h1\n className="my-0 text-base leading-5 font-semibold text-foreground"\n {...props}\n />\n ),\n p: ({ node: _node, ...props }) => (\n <p className="my-0 text-[13px] leading-5" {...props} />\n ),\n ol: ({ node: _node, ...props }) => (\n <ol className="my-0 list-decimal space-y-0.5 pl-4" {...props} />\n ),\n table: ({ node: _node, ...props }) => (\n <div className="overflow-hidden rounded-md border bg-background">\n <table className="w-full border-collapse text-xs" {...props} />\n </div>\n ),\n figure: ({ node: _node, ...props }) => (\n <figure\n className="my-0 space-y-2 rounded-md border bg-muted/20 p-2 text-[13px]"\n {...props}\n />\n ),\n figcaption: ({ node: _node, ...props }) => (\n <figcaption\n className="border-t pt-2 text-xs leading-5 text-muted-foreground"\n {...props}\n />\n ),\n caption: ({ node: _node, ...props }) => (\n <figcaption\n className="block border-t pt-2 text-xs leading-5 text-muted-foreground"\n {...props}\n />\n ),\n th: ({ node: _node, ...props }) => (\n <th className="border-b bg-muted px-2 py-1 text-left" {...props} />\n ),\n td: ({ node: _node, ...props }) => (\n <td className="border-t px-2 py-1" {...props} />\n ),\n }}\n >\n {markdown}\n </ReactMarkdown>\n </div>\n )\n})\n\nconst OcrBlockButton = React.memo(function OcrBlockButton({\n block,\n isActive,\n onFocusBlock,\n}: {\n block: OcrBlock\n isActive: boolean\n onFocusBlock: (block: OcrBlock) => void\n}) {\n const style = BLOCK_STYLES[block.type]\n\n return (\n <button\n type="button"\n onMouseEnter={() => onFocusBlock(block)}\n onFocus={() => onFocusBlock(block)}\n className={cn(\n "w-full rounded-lg border bg-background p-3 text-left hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",\n isActive && style.ring\n )}\n >\n <div className="min-w-0">\n <div className="flex items-center justify-between gap-2">\n <div className="flex min-w-0 items-center gap-2">\n <div\n className={cn(\n "inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium",\n style.badge\n )}\n >\n <style.icon className="size-3.5" />\n {style.label}\n </div>\n <div className="truncate text-xs text-muted-foreground">\n {Math.round(block.confidence * 100)}%\n </div>\n </div>\n <div className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">\n p. {block.page}\n </div>\n </div>\n <div className="mt-2 text-sm text-foreground/90">\n <OcrBlockMarkdown text={block.text} />\n </div>\n </div>\n </button>\n )\n})\n\nexport const OcrBlockOverlay = React.memo(function OcrBlockOverlay({\n block,\n isActive,\n pageHeight,\n pageWidth,\n}: {\n block: OcrBlock\n isActive?: boolean\n pageHeight?: number\n pageWidth?: number\n}) {\n const style = BLOCK_STYLES[block.type]\n\n return (\n <div\n className={cn(\n "pointer-events-none absolute z-10 border",\n isActive ? style.overlay : style.mutedOverlay\n )}\n style={blockToArea(\n block,\n pageWidth && pageHeight\n ? { width: pageWidth, height: pageHeight }\n : undefined\n )}\n />\n )\n})\n\nexport function OcrBlocksPanel({\n activeBlockId,\n blocks,\n className,\n onBlockFocus,\n}: {\n activeBlockId?: string\n blocks: OcrBlock[]\n className?: string\n onBlockFocus?: (block: OcrBlock) => void\n}) {\n const scrollViewportRef = React.useRef<HTMLDivElement | null>(null)\n const [localActiveBlockId, setLocalActiveBlockId] = React.useState(\n activeBlockId ?? blocks[0]?.id\n )\n const firstBlock = blocks[0]\n const focusedBlockId = activeBlockId ?? localActiveBlockId\n const activeBlock =\n blocks.find((block) => block.id === focusedBlockId) ?? firstBlock\n const focusedBlockIdRef = React.useRef(focusedBlockId)\n\n React.useEffect(() => {\n focusedBlockIdRef.current = focusedBlockId\n }, [focusedBlockId])\n\n const estimateBlockSize = React.useCallback(\n (index: number) => {\n const block = blocks[index]\n return block\n ? getEstimatedOcrBlockRowHeight(block)\n : OCR_BLOCK_ROW_MIN_ESTIMATE\n },\n [blocks]\n )\n const virtualizer = useVirtualizer({\n count: blocks.length,\n estimateSize: estimateBlockSize,\n getItemKey: (index) => blocks[index]?.id ?? index,\n getScrollElement: () => scrollViewportRef.current,\n overscan: 6,\n })\n\n const focusBlock = React.useCallback(\n (block: OcrBlock) => {\n if (block.id === focusedBlockIdRef.current) return\n\n focusedBlockIdRef.current = block.id\n setLocalActiveBlockId(block.id)\n onBlockFocus?.(block)\n },\n [onBlockFocus]\n )\n\n React.useEffect(() => {\n if (!firstBlock) return\n if (\n activeBlockId ||\n blocks.some((block) => block.id === localActiveBlockId)\n ) {\n return\n }\n\n setLocalActiveBlockId(firstBlock.id)\n }, [activeBlockId, blocks, firstBlock, localActiveBlockId])\n\n return (\n <aside\n className={cn("flex h-[420px] min-h-0 flex-col bg-background", className)}\n >\n <ScrollArea\n className="min-h-0 flex-1"\n scrollFade\n viewportRef={scrollViewportRef}\n >\n {blocks.length ? (\n <div\n className="relative"\n style={{\n height: virtualizer.getTotalSize() + OCR_BLOCK_LIST_PADDING * 2,\n }}\n >\n {virtualizer.getVirtualItems().map((virtualRow) => {\n const block = blocks[virtualRow.index]\n if (!block) return null\n\n return (\n <div\n key={virtualRow.key}\n ref={virtualizer.measureElement}\n data-index={virtualRow.index}\n className="absolute top-0 right-3 left-3 pb-2 [contain:layout_paint]"\n style={{\n transform: `translateY(${\n virtualRow.start + OCR_BLOCK_LIST_PADDING\n }px)`,\n }}\n >\n <OcrBlockButton\n block={block}\n isActive={block.id === activeBlock?.id}\n onFocusBlock={focusBlock}\n />\n </div>\n )\n })}\n </div>\n ) : (\n <div className="p-3">\n <div className="rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground">\n No layout blocks found.\n </div>\n </div>\n )}\n </ScrollArea>\n </aside>\n )\n}\n\nexport function OcrBlocks() {\n return (\n <OcrBlocksPanel blocks={getOcrBlocks(ATTENTION_OCR_OUTPUT).slice(0, 12)} />\n )\n}\n'--export function OcrBlocksSource() {- return (- <DocsSourceCodeBlock- code={ocrBlocksSourceCode}- fileName="components/extend/layout-blocks.tsx"- />- )-}diff --git a/apps/v4/components/layout-blocks-source-code.tsx b/apps/v4/components/layout-blocks-source-code.tsxnew file mode 100644index 0000000..1a23851--- /dev/null+++ b/apps/v4/components/layout-blocks-source-code.tsx@@ -0,0 +1,15 @@+"use client"++import { DocsSourceCodeBlock } from "@/components/docs-code-block"++const ocrBlocksSourceCode =+ '"use client"\n\nimport * as React from "react"\nimport ReactMarkdown from "react-markdown"\nimport rehypeRaw from "rehype-raw"\nimport rehypeSanitize, { defaultSchema } from "rehype-sanitize"\nimport remarkGfm from "remark-gfm"\n\nimport { cn } from "@/lib/utils"\nimport {\n LayoutBlocksPanel,\n layoutBlockStyles,\n type LayoutBlockType,\n} from "@/components/extend/layout-blocks-panel"\n\nexport type Point = {\n x: number\n y: number\n}\n\nexport type BoundingBox = {\n left: number\n top: number\n right: number\n bottom: number\n}\n\nexport type OcrBlockType = LayoutBlockType\n\nexport type ParsedOcrBlock = {\n id: string\n type: string\n content: string\n metadata: {\n page: {\n number: number\n width: number\n height: number\n }\n layoutClass?: string\n minOcrConfidence?: number\n avgOcrConfidence?: number\n }\n polygon?: Point[]\n boundingBox?: BoundingBox\n}\n\nexport type ParsedOcrOutput = {\n chunks: {\n blocks: ParsedOcrBlock[]\n }[]\n}\n\nexport type OcrBlock = {\n id: string\n type: OcrBlockType\n text: string\n page: number\n pageWidth: number\n pageHeight: number\n confidence: number\n polygon?: Point[]\n boundingBox?: BoundingBox\n}\n\nexport type HighlightArea = {\n left: number\n top: number\n width: number\n height: number\n}\n\nexport const PDF_URL = "/samples/attention.pdf"\nconst OCR_MARKDOWN_SCHEMA = {\n ...defaultSchema,\n attributes: {\n ...defaultSchema.attributes,\n figure: [...(defaultSchema.attributes?.figure ?? []), "type"],\n },\n tagNames: [\n ...(defaultSchema.tagNames ?? []),\n "caption",\n "figcaption",\n "figure",\n ],\n}\nconst OCR_MARKDOWN_REHYPE_PLUGINS: NonNullable<\n React.ComponentProps<typeof ReactMarkdown>["rehypePlugins"]\n> = [rehypeRaw, [rehypeSanitize, OCR_MARKDOWN_SCHEMA]]\nconst OCR_MARKDOWN_REMARK_PLUGINS: NonNullable<\n React.ComponentProps<typeof ReactMarkdown>["remarkPlugins"]\n> = [remarkGfm]\nconst OCR_MARKDOWN_FIGURE_CAPTION_PATTERN = /<\\/?caption>/gi\n\nexport const ATTENTION_OCR_OUTPUT = {\n chunks: [\n {\n blocks: [\n {\n id: "block_1_IKDP4i",\n type: "header",\n content: "arXiv:1706.03762v7 [cs.CL] 2 Aug 2023",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Header",\n minOcrConfidence: 0.959,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 36.16179897837395,\n y: 447.38040863840206,\n },\n {\n x: 75.85163708150822,\n y: 447.38040863840206,\n },\n {\n x: 75.85163708150822,\n y: 1155.1796566956025,\n },\n {\n x: 36.16179897837395,\n y: 1155.1796566956025,\n },\n ],\n boundingBox: {\n left: 36.16179897837395,\n top: 447.38040863840206,\n right: 75.85163708150822,\n bottom: 1155.1796566956025,\n },\n },\n {\n id: "block_1_rtNdsr",\n type: "header",\n content:\n "Provided proper attribution is provided, Google hereby grants permission to reproduce the tables and figures in this paper solely for use in journalistic or scholarly works.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Header",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 258.50183528705236,\n y: 151.7837261257315,\n },\n {\n x: 1016.8830982960054,\n y: 151.7837261257315,\n },\n {\n x: 1016.8830982960054,\n y: 233.84929126366637,\n },\n {\n x: 258.50183528705236,\n y: 233.84929126366637,\n },\n ],\n boundingBox: {\n left: 258.50183528705236,\n top: 151.7837261257315,\n right: 1016.8830982960054,\n bottom: 233.84929126366637,\n },\n },\n {\n id: "block_1_eo9AoV",\n type: "heading",\n content: "# Attention Is All You Need",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 440.0215455215343,\n y: 312.01490975860366,\n },\n {\n x: 831.4373211268961,\n y: 312.01490975860366,\n },\n {\n x: 831.4373211268961,\n y: 339.0022611402928,\n },\n {\n x: 440.0215455215343,\n y: 339.0022611402928,\n },\n ],\n boundingBox: {\n left: 440.0215455215343,\n top: 312.01490975860366,\n right: 831.4373211268961,\n bottom: 339.0022611402928,\n },\n },\n {\n id: "block_1_Kdt5Cu",\n type: "text",\n content: "Ashish Vaswani* Google Brain [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.977,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 242.9606625633518,\n y: 490.4495616712068,\n },\n {\n x: 449.64758323056856,\n y: 490.4495616712068,\n },\n {\n x: 449.64758323056856,\n y: 555.9028907431696,\n },\n {\n x: 242.9606625633518,\n y: 555.9028907431696,\n },\n ],\n boundingBox: {\n left: 242.9606625633518,\n top: 490.4495616712068,\n right: 449.64758323056856,\n bottom: 555.9028907431696,\n },\n },\n {\n id: "block_1_6Xv6uR",\n type: "text",\n content: "Llion Jones* Google Research [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.927,\n avgOcrConfidence: 0.982,\n },\n polygon: [\n {\n x: 264.3723327748097,\n y: 594.5307239733245,\n },\n {\n x: 438.3605845653227,\n y: 594.5307239733245,\n },\n {\n x: 438.3605845653227,\n y: 660.7685646688132,\n },\n {\n x: 264.3723327748097,\n y: 660.7685646688132,\n },\n ],\n boundingBox: {\n left: 264.3723327748097,\n top: 594.5307239733245,\n right: 438.3605845653227,\n bottom: 660.7685646688132,\n },\n },\n {\n id: "block_1_Lx35WU",\n type: "text",\n content: "Noam Shazeer* Google Brain [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.983,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 479.08373644752226,\n y: 490.1169480632122,\n },\n {\n x: 643.7573955006842,\n y: 490.1169480632122,\n },\n {\n x: 643.7573955006842,\n y: 556.2343205043247,\n },\n {\n x: 479.08373644752226,\n y: 556.2343205043247,\n },\n ],\n boundingBox: {\n left: 479.08373644752226,\n top: 490.1169480632122,\n right: 643.7573955006842,\n bottom: 556.2343205043247,\n },\n },\n {\n id: "block_1_VxOJIL",\n type: "text",\n content:\n "Aidan N. Gomez* * University of Toronto [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.095,\n avgOcrConfidence: 0.875,\n },\n polygon: [\n {\n x: 489.9820146769503,\n y: 593.5908916444707,\n },\n {\n x: 708.1676900821881,\n y: 593.5908916444707,\n },\n {\n x: 708.1676900821881,\n y: 657.7173651788468,\n },\n {\n x: 489.9820146769503,\n y: 657.7173651788468,\n },\n ],\n boundingBox: {\n left: 489.9820146769503,\n top: 593.5908916444707,\n right: 708.1676900821881,\n bottom: 657.7173651788468,\n },\n },\n {\n id: "block_1_m1Gb17",\n type: "text",\n content: "Niki Parmar* Google Research [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 673.3537325893875,\n y: 490.2837284059453,\n },\n {\n x: 848.6601168221802,\n y: 490.2837284059453,\n },\n {\n x: 848.6601168221802,\n y: 556.287735673718,\n },\n {\n x: 673.3537325893875,\n y: 556.287735673718,\n },\n ],\n boundingBox: {\n left: 673.3537325893875,\n top: 490.2837284059453,\n right: 848.6601168221802,\n bottom: 556.287735673718,\n },\n },\n {\n id: "block_1_otnY8T",\n type: "text",\n content: "\\u0141ukasz Kaiser* Google Brain [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.984,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 759.3324257509552,\n y: 594.2661578816579,\n },\n {\n x: 1011.1333304078039,\n y: 594.2661578816579,\n },\n {\n x: 1011.1333304078039,\n y: 660.9298993160851,\n },\n {\n x: 759.3324257509552,\n y: 660.9298993160851,\n },\n ],\n boundingBox: {\n left: 759.3324257509552,\n top: 594.2661578816579,\n right: 1011.1333304078039,\n bottom: 660.9298993160851,\n },\n },\n {\n id: "block_1_ICaos6",\n type: "text",\n content: "Illia Polosukhin* * [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.107,\n avgOcrConfidence: 0.766,\n },\n polygon: [\n {\n x: 495.9563429338219,\n y: 697.325802423004,\n },\n {\n x: 778.5449758933407,\n y: 697.325802423004,\n },\n {\n x: 778.5449758933407,\n y: 742.1158899292909,\n },\n {\n x: 495.9563429338219,\n y: 742.1158899292909,\n },\n ],\n boundingBox: {\n left: 495.9563429338219,\n top: 697.325802423004,\n right: 778.5449758933407,\n bottom: 742.1158899292909,\n },\n },\n {\n id: "block_1_zNN0g5",\n type: "section_heading",\n content: "### Abstract",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 590.8429918498018,\n y: 804.3203170891095,\n },\n {\n x: 683.8031267597728,\n y: 804.3203170891095,\n },\n {\n x: 683.8031267597728,\n y: 823.7656170264223,\n },\n {\n x: 590.8429918498018,\n y: 823.7656170264223,\n },\n ],\n boundingBox: {\n left: 590.8429918498018,\n top: 804.3203170891095,\n right: 683.8031267597728,\n bottom: 823.7656170264223,\n },\n },\n {\n id: "block_1_Pzc7ia",\n type: "text",\n content:\n "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014 English- to-German translation task, improving over the existing best results, including ensembles, by over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training costs of the best models from the literature. We show that the Transformer generalizes well to other tasks by applying it successfully to English constituency parsing both with large and limited training data.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.987,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 298.2268201173657,\n y: 861.5167879950731,\n },\n {\n x: 978.0244980415288,\n y: 861.5167879950731,\n },\n {\n x: 978.0244980415288,\n y: 1201.6481075430274,\n },\n {\n x: 298.2268201173657,\n y: 1201.6481075430274,\n },\n ],\n boundingBox: {\n left: 298.2268201173657,\n top: 861.5167879950731,\n right: 978.0244980415288,\n bottom: 1201.6481075430274,\n },\n },\n {\n id: "block_1_bHnLKj",\n type: "text",\n content:\n "*Equal contribution. Listing order is random. Jakob proposed replacing RNNs with self-attention and started the effort to evaluate this idea. Ashish, with Illia, designed and implemented the first Transformer models and has been crucially involved in every aspect of this work. Noam proposed scaled dot-product attention, multi-head attention and the parameter-free position representation and became the other person involved in nearly every detail. Niki designed, implemented, tuned and evaluated countless model variants in our original codebase and tensor2tensor. Llion also experimented with novel model variants, was responsible for our initial codebase, and efficient inference and visualizations. Lukasz and Aidan spent countless long days designing various parts of and implementing tensor2tensor, replacing our earlier codebase, greatly improving results and massively accelerating our research.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.951,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.8755505415645,\n y: 1247.2573697082978,\n },\n {\n x: 1049.6971241749116,\n y: 1247.2573697082978,\n },\n {\n x: 1049.6971241749116,\n y: 1429.7100451476592,\n },\n {\n x: 222.8755505415645,\n y: 1429.7100451476592,\n },\n ],\n boundingBox: {\n left: 222.8755505415645,\n top: 1247.2573697082978,\n right: 1049.6971241749116,\n bottom: 1429.7100451476592,\n },\n },\n {\n id: "block_1_J3Olku",\n type: "text",\n content: "+ Work performed while at Google Brain.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.11,\n avgOcrConfidence: 0.869,\n },\n polygon: [\n {\n x: 250.1677060649343,\n y: 1434.3817888991277,\n },\n {\n x: 555.1793119333087,\n y: 1434.3817888991277,\n },\n {\n x: 555.1793119333087,\n y: 1456.532320926064,\n },\n {\n x: 250.1677060649343,\n y: 1456.532320926064,\n },\n ],\n boundingBox: {\n left: 250.1677060649343,\n top: 1434.3817888991277,\n right: 555.1793119333087,\n bottom: 1456.532320926064,\n },\n },\n {\n id: "block_1_aQsakB",\n type: "text",\n content: "#Work performed while at Google Research.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.652,\n avgOcrConfidence: 0.94,\n },\n polygon: [\n {\n x: 249.36288151427775,\n y: 1458.4100914288283,\n },\n {\n x: 582.4047478446125,\n y: 1458.4100914288283,\n },\n {\n x: 582.4047478446125,\n y: 1479.773507369192,\n },\n {\n x: 249.36288151427775,\n y: 1479.773507369192,\n },\n ],\n boundingBox: {\n left: 249.36288151427775,\n top: 1458.4100914288283,\n right: 582.4047478446125,\n bottom: 1479.773507369192,\n },\n },\n {\n id: "block_1_iKp4Ae",\n type: "footer",\n content:\n "31st Conference on Neural Information Processing Systems (NIPS 2017), Long Beach, CA, USA.",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Footer",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.27405893367575,\n y: 1527.1945287374626,\n },\n {\n x: 958.2568426201814,\n y: 1527.1945287374626,\n },\n {\n x: 958.2568426201814,\n y: 1546.3855383736748,\n },\n {\n x: 224.27405893367575,\n y: 1546.3855383736748,\n },\n ],\n boundingBox: {\n left: 224.27405893367575,\n top: 1527.1945287374626,\n right: 958.2568426201814,\n bottom: 1546.3855383736748,\n },\n },\n {\n id: "block_1_zPHQaR",\n type: "text",\n content: "Jakob Uszkoreit* Google Research [email protected]",\n metadata: {\n page: {\n number: 1,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 879.2488933479699,\n y: 489.58686880240765,\n },\n {\n x: 1035.003756780694,\n y: 489.58686880240765,\n },\n {\n x: 1035.003756780694,\n y: 555.848623204052,\n },\n {\n x: 879.2488933479699,\n y: 555.848623204052,\n },\n ],\n boundingBox: {\n left: 879.2488933479699,\n top: 489.58686880240765,\n right: 1035.003756780694,\n bottom: 555.848623204052,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_2_UD1C1k",\n type: "heading",\n content: "# 1 Introduction",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 225.86025321570625,\n y: 152.1792611932396,\n },\n {\n x: 396.86960095036636,\n y: 152.1792611932396,\n },\n {\n x: 396.86960095036636,\n y: 171.96800693712737,\n },\n {\n x: 225.86025321570625,\n y: 171.96800693712737,\n },\n ],\n boundingBox: {\n left: 225.86025321570625,\n top: 152.1792611932396,\n right: 396.86960095036636,\n bottom: 171.96800693712737,\n },\n },\n {\n id: "block_2_C25o9D",\n type: "text",\n content:\n "Recurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks in particular, have been firmly established as state of the art approaches in sequence modeling and transduction problems such as language modeling and machine translation [35, 2, 5]. Numerous efforts have since continued to push the boundaries of recurrent language models and encoder-decoder architectures [38, 24, 15].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 223.64054213475134,\n y: 206.4059457563816,\n },\n {\n x: 1050.9159227357293,\n y: 206.4059457563816,\n },\n {\n x: 1050.9159227357293,\n y: 316.89823061720773,\n },\n {\n x: 223.64054213475134,\n y: 316.89823061720773,\n },\n ],\n boundingBox: {\n left: 223.64054213475134,\n top: 206.4059457563816,\n right: 1050.9159227357293,\n bottom: 316.89823061720773,\n },\n },\n {\n id: "block_2_Cw1VyU",\n type: "text",\n content:\n "Recurrent models typically factor computation along the symbol positions of the input and output sequences. Aligning the positions to steps in computation time, they generate a sequence of hidden states ht, as a function of the previous hidden state ht-1 and the input for position t. This inherently sequential nature precludes parallelization within training examples, which becomes critical at longer sequence lengths, as memory constraints limit batching across examples. Recent work has achieved significant improvements in computational efficiency through factorization tricks [21] and conditional computation [32], while also improving model performance in case of the latter. The fundamental constraint of sequential computation, however, remains.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.9,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.69928568819142,\n y: 331.227654822787,\n },\n {\n x: 1049.6158961832089,\n y: 331.227654822787,\n },\n {\n x: 1049.6158961832089,\n y: 511.80734250061494,\n },\n {\n x: 223.69928568819142,\n y: 511.80734250061494,\n },\n ],\n boundingBox: {\n left: 223.69928568819142,\n top: 331.227654822787,\n right: 1049.6158961832089,\n bottom: 511.80734250061494,\n },\n },\n {\n id: "block_2_FR7zlH",\n type: "text",\n content:\n "Attention mechanisms have become an integral part of compelling sequence modeling and transduc- tion models in various tasks, allowing modeling of dependencies without regard to their distance in the input or output sequences [2, 19]. In all but a few cases [27], however, such attention mechanisms are used in conjunction with a recurrent network.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.959,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.38852708357095,\n y: 525.5238181666324,\n },\n {\n x: 1052.1732525233804,\n y: 525.5238181666324,\n },\n {\n x: 1052.1732525233804,\n y: 613.7107948647406,\n },\n {\n x: 223.38852708357095,\n y: 613.7107948647406,\n },\n ],\n boundingBox: {\n left: 223.38852708357095,\n top: 525.5238181666324,\n right: 1052.1732525233804,\n bottom: 613.7107948647406,\n },\n },\n {\n id: "block_2_ZyhlFh",\n type: "text",\n content:\n "In this work we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output. The Transformer allows for significantly more parallelization and can reach a new state of the art in translation quality after being trained for as little as twelve hours on eight P100 GPUs.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.991,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.20226126343667,\n y: 627.2328828797304,\n },\n {\n x: 1052.7354108156078,\n y: 627.2328828797304,\n },\n {\n x: 1052.7354108156078,\n y: 716.0174654623619,\n },\n {\n x: 223.20226126343667,\n y: 716.0174654623619,\n },\n ],\n boundingBox: {\n left: 223.20226126343667,\n top: 627.2328828797304,\n right: 1052.7354108156078,\n bottom: 716.0174654623619,\n },\n },\n {\n id: "block_2_MZBXjP",\n type: "section_heading",\n content: "### 2 Background",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.22355178498873,\n y: 757.4257287333783,\n },\n {\n x: 392.45446198178036,\n y: 757.4257287333783,\n },\n {\n x: 392.45446198178036,\n y: 781.2853567654029,\n },\n {\n x: 224.22355178498873,\n y: 781.2853567654029,\n },\n ],\n boundingBox: {\n left: 224.22355178498873,\n top: 757.4257287333783,\n right: 392.45446198178036,\n bottom: 781.2853567654029,\n },\n },\n {\n id: "block_2_JeOnOk",\n type: "text",\n content:\n "The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU [16], ByteNet [18] and ConvS2S [9], all of which use convolutional neural networks as basic building block, computing hidden representations in parallel for all input and output positions. In these models, the number of operations required to relate signals from two arbitrary input or output positions grows in the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes it more difficult to learn dependencies between distant positions [12]. In the Transformer this is reduced to a constant number of operations, albeit at the cost of reduced effective resolution due to averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as described in section 3.2.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.893,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.30221050847186,\n y: 810.9956032315591,\n },\n {\n x: 1051.187440078624,\n y: 810.9956032315591,\n },\n {\n x: 1051.187440078624,\n y: 1010.7095232511822,\n },\n {\n x: 223.30221050847186,\n y: 1010.7095232511822,\n },\n ],\n boundingBox: {\n left: 223.30221050847186,\n top: 810.9956032315591,\n right: 1051.187440078624,\n bottom: 1010.7095232511822,\n },\n },\n {\n id: "block_2_tEzlrD",\n type: "text",\n content:\n "Self-attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence. Self-attention has been used successfully in a variety of tasks including reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations [4, 27, 28, 22].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.984,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.00045882176306,\n y: 1028.0413251030714,\n },\n {\n x: 1051.4467448213675,\n y: 1028.0413251030714,\n },\n {\n x: 1051.4467448213675,\n y: 1116.9915041815966,\n },\n {\n x: 224.00045882176306,\n y: 1116.9915041815966,\n },\n ],\n boundingBox: {\n left: 224.00045882176306,\n top: 1028.0413251030714,\n right: 1051.4467448213675,\n bottom: 1116.9915041815966,\n },\n },\n {\n id: "block_2_AFJ4ch",\n type: "text",\n content:\n "End-to-end memory networks are based on a recurrent attention mechanism instead of sequence- aligned recurrence and have been shown to perform well on simple-language question answering and language modeling tasks [34].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.05524984763485,\n y: 1129.9793457949072,\n },\n {\n x: 1052.8165441359918,\n y: 1129.9793457949072,\n },\n {\n x: 1052.8165441359918,\n y: 1196.1117767678168,\n },\n {\n x: 224.05524984763485,\n y: 1196.1117767678168,\n },\n ],\n boundingBox: {\n left: 224.05524984763485,\n top: 1129.9793457949072,\n right: 1052.8165441359918,\n bottom: 1196.1117767678168,\n },\n },\n {\n id: "block_2_CBbJP3",\n type: "text",\n content:\n "To the best of our knowledge, however, the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence- aligned RNNs or convolution. In the following sections, we will describe the Transformer, motivate self-attention and discuss its advantages over models such as [17, 18] and [9].",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.898,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 222.86987026242443,\n y: 1210.5673043387276,\n },\n {\n x: 1052.2374396776631,\n y: 1210.5673043387276,\n },\n {\n x: 1052.2374396776631,\n y: 1298.352294004053,\n },\n {\n x: 222.86987026242443,\n y: 1298.352294004053,\n },\n ],\n boundingBox: {\n left: 222.86987026242443,\n top: 1210.5673043387276,\n right: 1052.2374396776631,\n bottom: 1298.352294004053,\n },\n },\n {\n id: "block_2_RlRHBW",\n type: "section_heading",\n content: "### 3 Model Architecture",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.20267675914906,\n y: 1339.2827093368187,\n },\n {\n x: 470.2105250671832,\n y: 1339.2827093368187,\n },\n {\n x: 470.2105250671832,\n y: 1359.0320211424864,\n },\n {\n x: 224.20267675914906,\n y: 1359.0320211424864,\n },\n ],\n boundingBox: {\n left: 224.20267675914906,\n top: 1339.2827093368187,\n right: 470.2105250671832,\n bottom: 1359.0320211424864,\n },\n },\n {\n id: "block_2_OhVaOm",\n type: "text",\n content:\n "Most competitive neural sequence transduction models have an encoder-decoder structure [5, 2, 35]. Here, the encoder maps an input sequence of symbol representations (x1, ... , In) to a sequence of continuous representations z = (Z1, ... , Zn). Given z, the decoder then generates an output sequence (31, ... , ym) of symbols one element at a time. At each step the model is auto-regressive [10], consuming the previously generated symbols as additional input when generating the next.",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.619,\n avgOcrConfidence: 0.969,\n },\n polygon: [\n {\n x: 223.9033023806384,\n y: 1394.2295871247027,\n },\n {\n x: 1051.703398767179,\n y: 1394.2295871247027,\n },\n {\n x: 1051.703398767179,\n y: 1505.850527885265,\n },\n {\n x: 223.9033023806384,\n y: 1505.850527885265,\n },\n ],\n boundingBox: {\n left: 223.9033023806384,\n top: 1394.2295871247027,\n right: 1051.703398767179,\n bottom: 1505.850527885265,\n },\n },\n {\n id: "block_2_MzhUlf",\n type: "page_number",\n content: "2",\n metadata: {\n page: {\n number: 2,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 631.4816022441336,\n y: 1547.6769732138268,\n },\n {\n x: 642.0810031194757,\n y: 1547.6769732138268,\n },\n {\n x: 642.0810031194757,\n y: 1563.2578182363868,\n },\n {\n x: 631.4816022441336,\n y: 1563.2578182363868,\n },\n ],\n boundingBox: {\n left: 631.4816022441336,\n top: 1547.6769732138268,\n right: 642.0810031194757,\n bottom: 1563.2578182363868,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_3_afwbz8",\n type: "figure",\n content:\n \'<figure type="diagram">\\nOutput Probabilities\\n\\nSoftmax\\n\\nLinear\\n\\nAdd & Norm Feed Forward\\n\\nAdd & Norm\\n\\nAdd & Norm\\n\\nMulti-Head Feed Attention Forward Nx\\n\\nAdd & Norm\\n\\nNx Add & Norm\\n\\nMasked Multi-Head Multi-Head Attention Attention\\n\\nPositional Positional Encoding Encoding Input Output Embedding Embedding\\n\\nInputs Outputs (shifted right)\\n<caption>Transformer Architecture Diagram\\n\\nLeft Side: Encoder (Nx)\\n- Inputs\\n\\u2193\\n- Input Embedding\\n\\u2193\\n- Positional Encoding (added to Input Embedding)\\n\\u2193\\n- Multi-Head Attention\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Feed Forward\\n\\u2193\\n- Add & Norm\\n\\nRight Side: Decoder (Nx)\\n- Outputs (shifted right)\\n\\u2193\\n- Output Embedding\\n\\u2193\\n- Positional Encoding (added to Output Embedding)\\n\\u2193\\n- Masked Multi-Head Attention\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Multi-Head Attention (receives input from Encoder\\\'s Add & Norm)\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Feed Forward\\n\\u2193\\n- Add & Norm\\n\\u2193\\n- Linear\\n\\u2193\\n- Softmax\\n\\u2193\\n- Output Probabilities</caption>\\n</figure>\',\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.868,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 409.83791490540887,\n y: 150.86351013900642,\n },\n {\n x: 863.1759754932709,\n y: 150.86351013900642,\n },\n {\n x: 863.1759754932709,\n y: 821.7723977798806,\n },\n {\n x: 409.83791490540887,\n y: 821.7723977798806,\n },\n ],\n boundingBox: {\n left: 409.83791490540887,\n top: 150.86351013900642,\n right: 863.1759754932709,\n bottom: 821.7723977798806,\n },\n },\n {\n id: "block_3_1WIk1S",\n type: "text",\n content: "Figure 1: The Transformer - model architecture.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 436.4703770101505,\n y: 843.2910397178248,\n },\n {\n x: 836.1937028648209,\n y: 843.2910397178248,\n },\n {\n x: 836.1937028648209,\n y: 863.7018851373429,\n },\n {\n x: 436.4703770101505,\n y: 863.7018851373429,\n },\n ],\n boundingBox: {\n left: 436.4703770101505,\n top: 843.2910397178248,\n right: 836.1937028648209,\n bottom: 863.7018851373429,\n },\n },\n {\n id: "block_3_jyPEOL",\n type: "text",\n content:\n "The Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1, respectively.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.973,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.86804783953366,\n y: 910.1303693154701,\n },\n {\n x: 1051.9256870241932,\n y: 910.1303693154701,\n },\n {\n x: 1051.9256870241932,\n y: 977.3362178945899,\n },\n {\n x: 222.86804783953366,\n y: 977.3362178945899,\n },\n ],\n boundingBox: {\n left: 222.86804783953366,\n top: 910.1303693154701,\n right: 1051.9256870241932,\n bottom: 977.3362178945899,\n },\n },\n {\n id: "block_3_nEQfm1",\n type: "section_heading",\n content: "### 3.1 Encoder and Decoder Stacks",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.72352154585568,\n y: 1007.3903008367782,\n },\n {\n x: 527.4041196725664,\n y: 1007.3903008367782,\n },\n {\n x: 527.4041196725664,\n y: 1023.9329030316575,\n },\n {\n x: 223.72352154585568,\n y: 1023.9329030316575,\n },\n ],\n boundingBox: {\n left: 223.72352154585568,\n top: 1007.3903008367782,\n right: 527.4041196725664,\n bottom: 1023.9329030316575,\n },\n },\n {\n id: "block_3_W2U9b2",\n type: "text",\n content:\n "Encoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position- wise fully connected feed-forward network. We employ a residual connection [11] around each of the two sub-layers, followed by layer normalization [1]. That is, the output of each sub-layer is LayerNorm(x + Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer itself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding layers, produce outputs of dimension dmodel = 512.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.657,\n avgOcrConfidence: 0.984,\n },\n polygon: [\n {\n x: 223.8025010937322,\n y: 1048.091523421438,\n },\n {\n x: 1053.5889674277203,\n y: 1048.091523421438,\n },\n {\n x: 1053.5889674277203,\n y: 1206.3018568225373,\n },\n {\n x: 223.8025010937322,\n y: 1206.3018568225373,\n },\n ],\n boundingBox: {\n left: 223.8025010937322,\n top: 1048.091523421438,\n right: 1053.5889674277203,\n bottom: 1206.3018568225373,\n },\n },\n {\n id: "block_3_8wxg0F",\n type: "text",\n content:\n "Decoder: The decoder is also composed of a stack of N = 6 identical layers. In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head attention over the output of the encoder stack. Similar to the encoder, we employ residual connections around each of the sub-layers, followed by layer normalization. We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position i can depend only on the known outputs at positions less than i.",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.633,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 224.16407452882643,\n y: 1233.3413921729066,\n },\n {\n x: 1049.721170689938,\n y: 1233.3413921729066,\n },\n {\n x: 1049.721170689938,\n y: 1391.0596241198086,\n },\n {\n x: 224.16407452882643,\n y: 1391.0596241198086,\n },\n ],\n boundingBox: {\n left: 224.16407452882643,\n top: 1233.3413921729066,\n right: 1049.721170689938,\n bottom: 1391.0596241198086,\n },\n },\n {\n id: "block_3_i0stGS",\n type: "section_heading",\n content: "### 3.2 Attention",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 224.0832962258889,\n y: 1421.7722100279386,\n },\n {\n x: 354.57085797386446,\n y: 1421.7722100279386,\n },\n {\n x: 354.57085797386446,\n y: 1437.668053017523,\n },\n {\n x: 224.0832962258889,\n y: 1437.668053017523,\n },\n ],\n boundingBox: {\n left: 224.0832962258889,\n top: 1421.7722100279386,\n right: 354.57085797386446,\n bottom: 1437.668053017523,\n },\n },\n {\n id: "block_3_LwJLS3",\n type: "text",\n content:\n "An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.986,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.38670466068018,\n y: 1462.3713376611695,\n },\n {\n x: 1052.432178580848,\n y: 1462.3713376611695,\n },\n {\n x: 1052.432178580848,\n y: 1506.3117546138906,\n },\n {\n x: 223.38670466068018,\n y: 1506.3117546138906,\n },\n ],\n boundingBox: {\n left: 223.38670466068018,\n top: 1462.3713376611695,\n right: 1052.432178580848,\n bottom: 1506.3117546138906,\n },\n },\n {\n id: "block_3_gqT8MC",\n type: "page_number",\n content: "3",\n metadata: {\n page: {\n number: 3,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.997,\n avgOcrConfidence: 0.997,\n },\n polygon: [\n {\n x: 632.2706403523466,\n y: 1547.236487481827,\n },\n {\n x: 642.0801037419451,\n y: 1547.236487481827,\n },\n {\n x: 642.0801037419451,\n y: 1562.977578012567,\n },\n {\n x: 632.2706403523466,\n y: 1562.977578012567,\n },\n ],\n boundingBox: {\n left: 632.2706403523466,\n top: 1547.236487481827,\n right: 642.0801037419451,\n bottom: 1562.977578012567,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_4_PplY2k",\n type: "header",\n content: "Scaled Dot-Product Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Header",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 307.9120037329458,\n y: 148.57123934236685,\n },\n {\n x: 554.1308270753735,\n y: 148.57123934236685,\n },\n {\n x: 554.1308270753735,\n y: 164.4924521697195,\n },\n {\n x: 307.9120037329458,\n y: 164.4924521697195,\n },\n ],\n boundingBox: {\n left: 307.9120037329458,\n top: 148.57123934236685,\n right: 554.1308270753735,\n bottom: 164.4924521697195,\n },\n },\n {\n id: "block_4_TZACGH",\n type: "text",\n content: "Multi-Head Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 756.6973442578839,\n y: 148.30866211339045,\n },\n {\n x: 937.5759876557511,\n y: 148.30866211339045,\n },\n {\n x: 937.5759876557511,\n y: 164.44492071911804,\n },\n {\n x: 756.6973442578839,\n y: 164.44492071911804,\n },\n ],\n boundingBox: {\n left: 756.6973442578839,\n top: 148.30866211339045,\n right: 937.5759876557511,\n bottom: 164.44492071911804,\n },\n },\n {\n id: "block_4_yRQL9Y",\n type: "figure",\n content:\n \'<figure type="diagram">\\n1 MatMul\\n\\n1 SoftMax 1 Mask (opt.) 1 Scale 1 MatMul 1 1 Q K V\\n<caption>Scaled Dot-Product Attention Diagram\\n\\nInputs: Q, K, V\\n\\n1. MatMul (Q, K)\\n \\u2193\\n2. Scale\\n \\u2193\\n3. Mask (opt.)\\n \\u2193\\n4. SoftMax\\n \\u2193\\n5. MatMul (Result of SoftMax, V)\\n \\u2193\\nOutput</caption>\\n</figure>\',\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.226,\n avgOcrConfidence: 0.815,\n },\n polygon: [\n {\n x: 364.7714322500855,\n y: 195.77549835434533,\n },\n {\n x: 497.28713766501767,\n y: 195.77549835434533,\n },\n {\n x: 497.28713766501767,\n y: 457.62115733784844,\n },\n {\n x: 364.7714322500855,\n y: 457.62115733784844,\n },\n ],\n boundingBox: {\n left: 364.7714322500855,\n top: 195.77549835434533,\n right: 497.28713766501767,\n bottom: 457.62115733784844,\n },\n },\n {\n id: "block_4_goCdts",\n type: "figure",\n content:\n \'<figure type="diagram">\\nLinear\\n\\nConcat\\n\\nScaled Dot-Product\\n\\nh\\n\\nAttention\\n\\nLinear Linear Linear\\n\\nV K Q\\n<caption>Multi-Head Attention\\n\\nInputs: V, K, Q\\n\\u2193\\nLinear (x3) \\u2192 Scaled Dot-Product Attention (h heads)\\n\\u2193\\nConcat\\n\\u2193\\nLinear</caption>\\n</figure>\',\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.981,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 723.0441991430129,\n y: 171.2063080421964,\n },\n {\n x: 971.0292342805515,\n y: 171.2063080421964,\n },\n {\n x: 971.0292342805515,\n y: 495.8982404264292,\n },\n {\n x: 723.0441991430129,\n y: 495.8982404264292,\n },\n ],\n boundingBox: {\n left: 723.0441991430129,\n top: 171.2063080421964,\n right: 971.0292342805515,\n bottom: 495.8982404264292,\n },\n },\n {\n id: "block_4_ZQ6XHX",\n type: "text",\n content:\n "Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.991,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.32437673972473,\n y: 572.2067347074809,\n },\n {\n x: 1050.060662039875,\n y: 572.2067347074809,\n },\n {\n x: 1050.060662039875,\n y: 615.706381804961,\n },\n {\n x: 224.32437673972473,\n y: 615.706381804961,\n },\n ],\n boundingBox: {\n left: 224.32437673972473,\n top: 572.2067347074809,\n right: 1050.060662039875,\n bottom: 615.706381804961,\n },\n },\n {\n id: "block_4_seZO33",\n type: "text",\n content:\n "of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.44408862260138,\n y: 661.3754045586836,\n },\n {\n x: 1049.3653012018135,\n y: 661.3754045586836,\n },\n {\n x: 1049.3653012018135,\n y: 705.0281940833071,\n },\n {\n x: 224.44408862260138,\n y: 705.0281940833071,\n },\n ],\n boundingBox: {\n left: 224.44408862260138,\n top: 661.3754045586836,\n right: 1049.3653012018135,\n bottom: 705.0281940833071,\n },\n },\n {\n id: "block_4_CMgLHk",\n type: "section_heading",\n content: "### 3.2.1 Scaled Dot-Product Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.53467593227862,\n y: 732.4767248397483,\n },\n {\n x: 549.2687448097842,\n y: 732.4767248397483,\n },\n {\n x: 549.2687448097842,\n y: 748.6887496431967,\n },\n {\n x: 223.53467593227862,\n y: 748.6887496431967,\n },\n ],\n boundingBox: {\n left: 223.53467593227862,\n top: 732.4767248397483,\n right: 549.2687448097842,\n bottom: 748.6887496431967,\n },\n },\n {\n id: "block_4_fmfLoy",\n type: "text",\n content:\n \'We call our particular attention "Scaled Dot-Product Attention" (Figure 2). The input consists of queries and keys of dimension dk, and values of dimension dy. We compute the dot products of the\\n\\nquery with all keys, divide each by Vdk, and apply a softmafunction to obtain the weights on the [x]\\n\\nvalues.\',\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.594,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 223.39593511428276,\n y: 771.1101458269851,\n },\n {\n x: 1051.4275265436104,\n y: 771.1101458269851,\n },\n {\n x: 1051.4275265436104,\n y: 856.1295272138783,\n },\n {\n x: 223.39593511428276,\n y: 856.1295272138783,\n },\n ],\n boundingBox: {\n left: 223.39593511428276,\n top: 771.1101458269851,\n right: 1051.4275265436104,\n bottom: 856.1295272138783,\n },\n },\n {\n id: "block_4_cDuW6h",\n type: "text",\n content:\n "In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix Q. The keys and values are also packed together into matrices K and V. We compute the matrix of outputs as:",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.976,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.08788778486044,\n y: 873.4355685585424,\n },\n {\n x: 1050.3812191260122,\n y: 873.4355685585424,\n },\n {\n x: 1050.3812191260122,\n y: 938.6725377821385,\n },\n {\n x: 224.08788778486044,\n y: 938.6725377821385,\n },\n ],\n boundingBox: {\n left: 224.08788778486044,\n top: 873.4355685585424,\n right: 1050.3812191260122,\n bottom: 938.6725377821385,\n },\n },\n {\n id: "block_4_VaSWNE",\n type: "text",\n content: "QKT Attention(Q, K, V) = softmax( V Vdk",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.961,\n },\n polygon: [\n {\n x: 458.52888900868214,\n y: 968.9788274549901,\n },\n {\n x: 816.6205023327013,\n y: 968.9788274549901,\n },\n {\n x: 816.6205023327013,\n y: 1021.9395890773686,\n },\n {\n x: 458.52888900868214,\n y: 1021.9395890773686,\n },\n ],\n boundingBox: {\n left: 458.52888900868214,\n top: 968.9788274549901,\n right: 816.6205023327013,\n bottom: 1021.9395890773686,\n },\n },\n {\n id: "block_4_Wtl7xI",\n type: "text",\n content: "(1)",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 1026.9459968065694,\n y: 986.4570474839747,\n },\n {\n x: 1051.0514920645387,\n y: 986.4570474839747,\n },\n {\n x: 1051.0514920645387,\n y: 1005.8566982871607,\n },\n {\n x: 1026.9459968065694,\n y: 1005.8566982871607,\n },\n ],\n boundingBox: {\n left: 1026.9459968065694,\n top: 986.4570474839747,\n right: 1051.0514920645387,\n bottom: 1005.8566982871607,\n },\n },\n {\n id: "block_4_HVInAp",\n type: "text",\n content:\n "The two most commonly used attention functions are additive attention [2], and dot-product (multi- plicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor\\n\\nof . Additive attention computes the compatibility function using a feed-forward network with [x] Vdk\\n\\na single hidden layer. While the two are similar in theoretical complexity, dot-product attention is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.098,\n avgOcrConfidence: 0.981,\n },\n polygon: [\n {\n x: 223.11696240501684,\n y: 1041.6009173859331,\n },\n {\n x: 1052.8067929901345,\n y: 1041.6009173859331,\n },\n {\n x: 1052.8067929901345,\n y: 1180.0422397699572,\n },\n {\n x: 223.11696240501684,\n y: 1180.0422397699572,\n },\n ],\n boundingBox: {\n left: 223.11696240501684,\n top: 1041.6009173859331,\n right: 1052.8067929901345,\n bottom: 1180.0422397699572,\n },\n },\n {\n id: "block_4_6NHlzf",\n type: "text",\n content:\n "While for small values of dk the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of dk [3]. We suspect that for large values of dk, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients 4. To counteract this effect, we scale the dot products by.",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.58,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 223.18699551324775,\n y: 1194.0708248167111,\n },\n {\n x: 1050.8364934990875,\n y: 1194.0708248167111,\n },\n {\n x: 1050.8364934990875,\n y: 1289.5664457163416,\n },\n {\n x: 223.18699551324775,\n y: 1289.5664457163416,\n },\n ],\n boundingBox: {\n left: 223.18699551324775,\n top: 1194.0708248167111,\n right: 1050.8364934990875,\n bottom: 1289.5664457163416,\n },\n },\n {\n id: "block_4_4VWmvI",\n type: "section_heading",\n content: "### 3.2.2 Multi-Head Attention",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.5976323594142,\n y: 1315.4335938647278,\n },\n {\n x: 479.8474026422431,\n y: 1315.4335938647278,\n },\n {\n x: 479.8474026422431,\n y: 1331.4542616650574,\n },\n {\n x: 223.5976323594142,\n y: 1331.4542616650574,\n },\n ],\n boundingBox: {\n left: 223.5976323594142,\n top: 1315.4335938647278,\n right: 479.8474026422431,\n bottom: 1331.4542616650574,\n },\n },\n {\n id: "block_4_n7aPpb",\n type: "text",\n content:\n "Instead of performing a single attention function with dmodel-dimensional keys, values and queries, we found it beneficial to linearly project the queries, keys and values h times with different, learned linear projections to dk, dk and dy dimensions, respectively. On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding dy-dimensional",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.619,\n avgOcrConfidence: 0.979,\n },\n polygon: [\n {\n x: 223.83094982509195,\n y: 1354.33461159154,\n },\n {\n x: 1052.0098498267848,\n y: 1354.33461159154,\n },\n {\n x: 1052.0098498267848,\n y: 1442.8801044664883,\n },\n {\n x: 223.83094982509195,\n y: 1442.8801044664883,\n },\n ],\n boundingBox: {\n left: 223.83094982509195,\n top: 1354.33461159154,\n right: 1052.0098498267848,\n bottom: 1442.8801044664883,\n },\n },\n {\n id: "block_4_rfqNPC",\n type: "text",\n content:\n "4To illustrate why the dot products get large, assume that the components of q and k are independent random variables with mean 0 and variance 1. Then their dot product, q \\u00b7 k = >i=1 qiki, has mean 0 and variance dk-",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.105,\n avgOcrConfidence: 0.921,\n },\n polygon: [\n {\n x: 224.42529636577967,\n y: 1459.9841341864794,\n },\n {\n x: 1049.4534401998033,\n y: 1459.9841341864794,\n },\n {\n x: 1049.4534401998033,\n y: 1506.815978659723,\n },\n {\n x: 224.42529636577967,\n y: 1506.815978659723,\n },\n ],\n boundingBox: {\n left: 224.42529636577967,\n top: 1459.9841341864794,\n right: 1049.4534401998033,\n bottom: 1506.815978659723,\n },\n },\n {\n id: "block_4_35BhDQ",\n type: "page_number",\n content: "4",\n metadata: {\n page: {\n number: 4,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.996,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 631.2688757903385,\n y: 1548.1330857241064,\n },\n {\n x: 642.0564832478544,\n y: 1548.1330857241064,\n },\n {\n x: 642.0564832478544,\n y: 1562.0727401962854,\n },\n {\n x: 631.2688757903385,\n y: 1562.0727401962854,\n },\n ],\n boundingBox: {\n left: 631.2688757903385,\n top: 1548.1330857241064,\n right: 642.0564832478544,\n bottom: 1562.0727401962854,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_5_Zc8VSW",\n type: "text",\n content:\n "output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure 2.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.988,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.67903916853186,\n y: 155.68632458564932,\n },\n {\n x: 1049.4719957783275,\n y: 155.68632458564932,\n },\n {\n x: 1049.4719957783275,\n y: 199.30535079841326,\n },\n {\n x: 224.67903916853186,\n y: 199.30535079841326,\n },\n ],\n boundingBox: {\n left: 224.67903916853186,\n top: 155.68632458564932,\n right: 1049.4719957783275,\n bottom: 199.30535079841326,\n },\n },\n {\n id: "block_5_P72mUL",\n type: "text",\n content:\n "Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 224.58133836732293,\n y: 212.29537068990837,\n },\n {\n x: 1049.5524663994781,\n y: 212.29537068990837,\n },\n {\n x: 1049.5524663994781,\n y: 255.9039790504857,\n },\n {\n x: 224.58133836732293,\n y: 255.9039790504857,\n },\n ],\n boundingBox: {\n left: 224.58133836732293,\n top: 212.29537068990837,\n right: 1049.5524663994781,\n bottom: 255.9039790504857,\n },\n },\n {\n id: "block_5_zTpvNY",\n type: "text",\n content:\n "MultiHead(Q,K,V)=Concat(head1, ... , headh)W\\u00ba where head; = Attention(Qw?, KWK,VW)",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.581,\n avgOcrConfidence: 0.796,\n },\n polygon: [\n {\n x: 388.73733464818804,\n y: 302.5467395065422,\n },\n {\n x: 883.3280911410811,\n y: 302.5467395065422,\n },\n {\n x: 883.3280911410811,\n y: 364.6030674267532,\n },\n {\n x: 388.73733464818804,\n y: 364.6030674267532,\n },\n ],\n boundingBox: {\n left: 388.73733464818804,\n top: 302.5467395065422,\n right: 883.3280911410811,\n bottom: 364.6030674267532,\n },\n },\n {\n id: "block_5_cOSQOc",\n type: "text",\n content:\n "Where the projections are parameter matrices Wo E Rdmodel X dk , WK \\u20ac Rdmodel X dk , WY \\u20ac Rdmodel X dy and WO E Rhdy Xdmodel",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.252,\n avgOcrConfidence: 0.682,\n },\n polygon: [\n {\n x: 223.51567066498916,\n y: 424.5787134959285,\n },\n {\n x: 1047.1388211215499,\n y: 424.5787134959285,\n },\n {\n x: 1047.1388211215499,\n y: 472.1556711698833,\n },\n {\n x: 223.51567066498916,\n y: 472.1556711698833,\n },\n ],\n boundingBox: {\n left: 223.51567066498916,\n top: 424.5787134959285,\n right: 1047.1388211215499,\n bottom: 472.1556711698833,\n },\n },\n {\n id: "block_5_4oR3J2",\n type: "text",\n content:\n "In this work we employ h = 8 parallel attention layers, or heads. For each of these we use dk = dy = dmodel/h = 64. Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.557,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 223.83189653828197,\n y: 488.323372747665,\n },\n {\n x: 1049.9097559573877,\n y: 488.323372747665,\n },\n {\n x: 1049.9097559573877,\n y: 555.0531728357302,\n },\n {\n x: 223.83189653828197,\n y: 555.0531728357302,\n },\n ],\n boundingBox: {\n left: 223.83189653828197,\n top: 488.323372747665,\n right: 1049.9097559573877,\n bottom: 555.0531728357302,\n },\n },\n {\n id: "block_5_oGR7Tp",\n type: "section_heading",\n content: "### 3.2.3 Applications of Attention in our Model",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.9031130380004,\n y: 584.1135347409356,\n },\n {\n x: 629.6546824657133,\n y: 584.1135347409356,\n },\n {\n x: 629.6546824657133,\n y: 605.02614180486,\n },\n {\n x: 223.9031130380004,\n y: 605.02614180486,\n },\n ],\n boundingBox: {\n left: 223.9031130380004,\n top: 584.1135347409356,\n right: 629.6546824657133,\n bottom: 605.02614180486,\n },\n },\n {\n id: "block_5_b34egv",\n type: "text",\n content:\n "The Transformer uses multi-head attention in three different ways:",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.3985859112148,\n y: 623.9660812033746,\n },\n {\n x: 775.7513199409428,\n y: 623.9660812033746,\n },\n {\n x: 775.7513199409428,\n y: 644.7702005429376,\n },\n {\n x: 223.3985859112148,\n y: 644.7702005429376,\n },\n ],\n boundingBox: {\n left: 223.3985859112148,\n top: 623.9660812033746,\n right: 775.7513199409428,\n bottom: 644.7702005429376,\n },\n },\n {\n id: "block_5_NSYaLO",\n type: "text",\n content:\n \'\\u00b7 In "encoder-decoder attention" layers, the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder. This allows every position in the decoder to attend over all positions in the input sequence. This mimics the typical encoder-decoder attention mechanisms in sequence-to-sequence models such as [38, 2, 9].\',\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.586,\n avgOcrConfidence: 0.984,\n },\n polygon: [\n {\n x: 281.7719981618171,\n y: 667.4162908568419,\n },\n {\n x: 1052.1352893244612,\n y: 667.4162908568419,\n },\n {\n x: 1052.1352893244612,\n y: 778.3123385207098,\n },\n {\n x: 281.7719981618171,\n y: 778.3123385207098,\n },\n ],\n boundingBox: {\n left: 281.7719981618171,\n top: 667.4162908568419,\n right: 1052.1352893244612,\n bottom: 778.3123385207098,\n },\n },\n {\n id: "block_5_ZbEUX6",\n type: "text",\n content:\n "\\u00b7 The encoder contains self-attention layers. In a self-attention layer all of the keys, values and queries come from the same place, in this case, the output of the previous layer in the encoder. Each position in the encoder can attend to all positions in the previous layer of the encoder.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.407,\n avgOcrConfidence: 0.983,\n },\n polygon: [\n {\n x: 282.1731915439132,\n y: 791.5420637202442,\n },\n {\n x: 1049.6795153095775,\n y: 791.5420637202442,\n },\n {\n x: 1049.6795153095775,\n y: 876.9418387735697,\n },\n {\n x: 282.1731915439132,\n y: 876.9418387735697,\n },\n ],\n boundingBox: {\n left: 282.1731915439132,\n top: 791.5420637202442,\n right: 1049.6795153095775,\n bottom: 876.9418387735697,\n },\n },\n {\n id: "block_5_wkxEH8",\n type: "text",\n content:\n "\\u00b7 Similarly, self-attention layers in the decoder allow each position in the decoder to attend to all positions in the decoder up to and including that position. We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to -oo) all values in the input of the softmax which correspond to illegal connections. See Figure 2.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.543,\n avgOcrConfidence: 0.985,\n },\n polygon: [\n {\n x: 281.12820952478114,\n y: 893.687589086088,\n },\n {\n x: 1049.8325041610829,\n y: 893.687589086088,\n },\n {\n x: 1049.8325041610829,\n y: 1005.0602061336201,\n },\n {\n x: 281.12820952478114,\n y: 1005.0602061336201,\n },\n ],\n boundingBox: {\n left: 281.12820952478114,\n top: 893.687589086088,\n right: 1049.8325041610829,\n bottom: 1005.0602061336201,\n },\n },\n {\n id: "block_5_vVMF0e",\n type: "section_heading",\n content: "### 3.3 Position-wise Feed-Forward Networks",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.59919443617773,\n y: 1037.180243872162,\n },\n {\n x: 609.3837069768975,\n y: 1037.180243872162,\n },\n {\n x: 609.3837069768975,\n y: 1053.935843790384,\n },\n {\n x: 223.59919443617773,\n y: 1053.935843790384,\n },\n ],\n boundingBox: {\n left: 223.59919443617773,\n top: 1037.180243872162,\n right: 609.3837069768975,\n bottom: 1053.935843790384,\n },\n },\n {\n id: "block_5_WtW3Xc",\n type: "text",\n content:\n "In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forward network, which is applied to each position separately and identically. This consists of two linear transformations with a ReLU activation in between.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.986,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.937928415563,\n y: 1079.1571798109471,\n },\n {\n x: 1049.736412772297,\n y: 1079.1571798109471,\n },\n {\n x: 1049.736412772297,\n y: 1142.9025967246607,\n },\n {\n x: 223.937928415563,\n y: 1142.9025967246607,\n },\n ],\n boundingBox: {\n left: 223.937928415563,\n top: 1079.1571798109471,\n right: 1049.736412772297,\n bottom: 1142.9025967246607,\n },\n },\n {\n id: "block_5_TCB4QK",\n type: "text",\n content: "FFN(x)=max(0,xW1+b1)W2+b2",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.668,\n avgOcrConfidence: 0.668,\n },\n polygon: [\n {\n x: 471.6477776965956,\n y: 1184.1576702146604,\n },\n {\n x: 801.1487473536581,\n y: 1184.1576702146604,\n },\n {\n x: 801.1487473536581,\n y: 1206.444581397494,\n },\n {\n x: 471.6477776965956,\n y: 1206.444581397494,\n },\n ],\n boundingBox: {\n left: 471.6477776965956,\n top: 1184.1576702146604,\n right: 801.1487473536581,\n bottom: 1206.444581397494,\n },\n },\n {\n id: "block_5_olGJjx",\n type: "text",\n content: "(2)",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.997,\n avgOcrConfidence: 0.997,\n },\n polygon: [\n {\n x: 1026.9936164800267,\n y: 1185.5856736262042,\n },\n {\n x: 1051.1806237436558,\n y: 1185.5856736262042,\n },\n {\n x: 1051.1806237436558,\n y: 1204.3962422421102,\n },\n {\n x: 1026.9936164800267,\n y: 1204.3962422421102,\n },\n ],\n boundingBox: {\n left: 1026.9936164800267,\n top: 1185.5856736262042,\n right: 1051.1806237436558,\n bottom: 1204.3962422421102,\n },\n },\n {\n id: "block_5_KTjDsL",\n type: "text",\n content:\n "While the linear transformations are the same across different positions, they use different parameters from layer to layer. Another way of describing this is as two convolutions with kernel size 1. The dimensionality of input and output is dmodel = 512, and the inner-layer has dimensionality dff =2048.",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.881,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 222.78797957148865,\n y: 1230.1093008858818,\n },\n {\n x: 1052.541145269018,\n y: 1230.1093008858818,\n },\n {\n x: 1052.541145269018,\n y: 1320.3967533541802,\n },\n {\n x: 222.78797957148865,\n y: 1320.3967533541802,\n },\n ],\n boundingBox: {\n left: 222.78797957148865,\n top: 1230.1093008858818,\n right: 1052.541145269018,\n bottom: 1320.3967533541802,\n },\n },\n {\n id: "block_5_Pwzvu2",\n type: "section_heading",\n content: "### 3.4 Embeddings and Softmax",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.997,\n },\n polygon: [\n {\n x: 223.80512822283447,\n y: 1351.0096120045598,\n },\n {\n x: 499.655388045485,\n y: 1351.0096120045598,\n },\n {\n x: 499.655388045485,\n y: 1371.2419333206979,\n },\n {\n x: 223.80512822283447,\n y: 1371.2419333206979,\n },\n ],\n boundingBox: {\n left: 223.80512822283447,\n top: 1351.0096120045598,\n right: 499.655388045485,\n bottom: 1371.2419333206979,\n },\n },\n {\n id: "block_5_6y9ZGB",\n type: "text",\n content:\n "Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension dmodel. We also use the usual learned linear transfor- mation and softmax function to convert the decoder output to predicted next-token probabilities. In our model, we share the same weight matrix between the two embedding layers and the pre-softmax linear transformation, similar to [30]. In the embedding layers, we multiply those weights by Vdmodel -",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.275,\n avgOcrConfidence: 0.983,\n },\n polygon: [\n {\n x: 224.49331770848184,\n y: 1394.318801822519,\n },\n {\n x: 1052.2855327077154,\n y: 1394.318801822519,\n },\n {\n x: 1052.2855327077154,\n y: 1505.8341434450076,\n },\n {\n x: 224.49331770848184,\n y: 1505.8341434450076,\n },\n ],\n boundingBox: {\n left: 224.49331770848184,\n top: 1394.318801822519,\n right: 1052.2855327077154,\n bottom: 1505.8341434450076,\n },\n },\n {\n id: "block_5_o8MKrc",\n type: "page_number",\n content: "5",\n metadata: {\n page: {\n number: 5,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 631.5606054598397,\n y: 1547.4356578740858,\n },\n {\n x: 641.9868998283888,\n y: 1547.4356578740858,\n },\n {\n x: 641.9868998283888,\n y: 1563.1716341864794,\n },\n {\n x: 631.5606054598397,\n y: 1563.1716341864794,\n },\n ],\n boundingBox: {\n left: 631.5606054598397,\n top: 1547.4356578740858,\n right: 641.9868998283888,\n bottom: 1563.1716341864794,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_6_YmUPFZ",\n type: "text",\n content:\n "Table 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations for different layer types. n is the sequence length, d is the representation dimension, k is the kernel size of convolutions and r the size of the neighborhood in restricted self-attention.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.977,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.7798615058843,\n y: 148.2273318355245,\n },\n {\n x: 1048.906618661254,\n y: 148.2273318355245,\n },\n {\n x: 1048.906618661254,\n y: 214.40370720311216,\n },\n {\n x: 222.7798615058843,\n y: 214.40370720311216,\n },\n ],\n boundingBox: {\n left: 222.7798615058843,\n top: 148.2273318355245,\n right: 1048.906618661254,\n bottom: 214.40370720311216,\n },\n },\n {\n id: "block_6_kibLxu",\n type: "table",\n content:\n "| Layer Type | Complexity per Layer | Sequential Operations | Maximum Path Length |\\n| --- | --- | --- | --- |\\n| Self-Attention | O(n2 \\u00b7 d) | O(1) | O(1) |\\n| Recurrent | O(n \\u00b7 d2) | O(n) | O(n) |\\n| Convolutional | O(k \\u00b7 n \\u00b7 d2) | O(1) | O(logk(n)) |\\n| Self-Attention (restricted) | O(r . n . d) [ ] | O(1) | O(n/r) [ ] |",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.256,\n avgOcrConfidence: 0.856,\n },\n polygon: [\n {\n x: 246.08119491243013,\n y: 233.8958637983279,\n },\n {\n x: 1028.2713006012632,\n y: 233.8958637983279,\n },\n {\n x: 1028.2713006012632,\n y: 389.94297754674926,\n },\n {\n x: 246.08119491243013,\n y: 389.94297754674926,\n },\n ],\n boundingBox: {\n left: 246.08119491243013,\n top: 233.8958637983279,\n right: 1028.2713006012632,\n bottom: 389.94297754674926,\n },\n },\n {\n id: "block_6_tUIpoY",\n type: "section_heading",\n content: "### 3.5 Positional Encoding",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.00651778617916,\n y: 445.9595083078944,\n },\n {\n x: 448.20427163674015,\n y: 445.9595083078944,\n },\n {\n x: 448.20427163674015,\n y: 466.69903696390026,\n },\n {\n x: 224.00651778617916,\n y: 466.69903696390026,\n },\n ],\n boundingBox: {\n left: 224.00651778617916,\n top: 445.9595083078944,\n right: 448.20427163674015,\n bottom: 466.69903696390026,\n },\n },\n {\n id: "block_6_mmxGrc",\n type: "text",\n content:\n \'Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence. To this end, we add "positional encodings" to the input embeddings at the bottoms of the encoder and decoder stacks. The positional encodings have the same dimension dmodel as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed [9].\',\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.83698512167825,\n y: 487.3354288832586,\n },\n {\n x: 1050.4121766473256,\n y: 487.3354288832586,\n },\n {\n x: 1050.4121766473256,\n y: 620.7750930786133,\n },\n {\n x: 223.83698512167825,\n y: 620.7750930786133,\n },\n ],\n boundingBox: {\n left: 223.83698512167825,\n top: 487.3354288832586,\n right: 1050.4121766473256,\n bottom: 620.7750930786133,\n },\n },\n {\n id: "block_6_NG2aN8",\n type: "text",\n content:\n "In this work, we use sine and cosine functions of different frequencies:",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.39521455416715,\n y: 635.0555533789154,\n },\n {\n x: 810.5588871197108,\n y: 635.0555533789154,\n },\n {\n x: 810.5588871197108,\n y: 655.9754529393705,\n },\n {\n x: 224.39521455416715,\n y: 655.9754529393705,\n },\n ],\n boundingBox: {\n left: 224.39521455416715,\n top: 635.0555533789154,\n right: 810.5588871197108,\n bottom: 655.9754529393705,\n },\n },\n {\n id: "block_6_ktOzAP",\n type: "text",\n content:\n "PE(pos,2i) = sin(pos/100002i/dmodel ) PE(pos,2i+1) = cos(pos/100002i/dmodel) )",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.646,\n avgOcrConfidence: 0.856,\n },\n polygon: [\n {\n x: 470.62755222738224,\n y: 700.6432727440855,\n },\n {\n x: 804.2361684089159,\n y: 700.6432727440855,\n },\n {\n x: 804.2361684089159,\n y: 763.5065343469606,\n },\n {\n x: 470.62755222738224,\n y: 763.5065343469606,\n },\n ],\n boundingBox: {\n left: 470.62755222738224,\n top: 700.6432727440855,\n right: 804.2361684089159,\n bottom: 763.5065343469606,\n },\n },\n {\n id: "block_6_L0vHNu",\n type: "text",\n content:\n "where pos is the position and i is the dimension. That is, each dimension of the positional encoding corresponds to a sinusoid. The wavelengths form a geometric progression from 27 to 10000 . 27. We chose this function because we hypothesized it would allow the model to easily learn to attend by relative positions, since for any fixed offset k, PEpos+k can be represented as a linear function of PEpos.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.291,\n avgOcrConfidence: 0.967,\n },\n polygon: [\n {\n x: 223.63699196028884,\n y: 787.3148307800293,\n },\n {\n x: 1050.8335586881985,\n y: 787.3148307800293,\n },\n {\n x: 1050.8335586881985,\n y: 900.202535012611,\n },\n {\n x: 223.63699196028884,\n y: 900.202535012611,\n },\n ],\n boundingBox: {\n left: 223.63699196028884,\n top: 787.3148307800293,\n right: 1050.8335586881985,\n bottom: 900.202535012611,\n },\n },\n {\n id: "block_6_Sai49H",\n type: "text",\n content:\n "We also experimented with using learned positional embeddings [9] instead, and found that the two versions produced nearly identical results (see Table 3 row (E)). We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.868,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 223.15007369883736,\n y: 912.2991767252298,\n },\n {\n x: 1049.522644933993,\n y: 912.2991767252298,\n },\n {\n x: 1049.522644933993,\n y: 1000.5864015736975,\n },\n {\n x: 223.15007369883736,\n y: 1000.5864015736975,\n },\n ],\n boundingBox: {\n left: 223.15007369883736,\n top: 912.2991767252298,\n right: 1049.522644933993,\n bottom: 1000.5864015736975,\n },\n },\n {\n id: "block_6_545oKE",\n type: "section_heading",\n content: "### 4 Why Self-Attention",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.44270274586924,\n y: 1036.185907234823,\n },\n {\n x: 468.14631162768734,\n y: 1036.185907234823,\n },\n {\n x: 468.14631162768734,\n y: 1059.806398205291,\n },\n {\n x: 223.44270274586924,\n y: 1059.806398205291,\n },\n ],\n boundingBox: {\n left: 223.44270274586924,\n top: 1036.185907234823,\n right: 468.14631162768734,\n bottom: 1059.806398205291,\n },\n },\n {\n id: "block_6_rdkytl",\n type: "text",\n content:\n "In this section we compare various aspects of self-attention layers to the recurrent and convolu- tional layers commonly used for mapping one variable-length sequence of symbol representations (x1, ... , In) to another sequence of equal length (21, ... , Zn), with xi, Zi E Rd, such as a hidden layer in a typical sequence transduction encoder or decoder. Motivating our use of self-attention we consider three desiderata.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.298,\n avgOcrConfidence: 0.936,\n },\n polygon: [\n {\n x: 222.55295802206888,\n y: 1087.3066867455505,\n },\n {\n x: 1052.7677884067061,\n y: 1087.3066867455505,\n },\n {\n x: 1052.7677884067061,\n y: 1195.3768446499244,\n },\n {\n x: 222.55295802206888,\n y: 1195.3768446499244,\n },\n ],\n boundingBox: {\n left: 222.55295802206888,\n top: 1087.3066867455505,\n right: 1052.7677884067061,\n bottom: 1195.3768446499244,\n },\n },\n {\n id: "block_6_y2UJTk",\n type: "text",\n content:\n "One is the total computational complexity per layer. Another is the amount of computation that can be parallelized, as measured by the minimum number of sequential operations required.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.43593374656064,\n y: 1212.4905345601246,\n },\n {\n x: 1048.7435946499345,\n y: 1212.4905345601246,\n },\n {\n x: 1048.7435946499345,\n y: 1255.7911059730932,\n },\n {\n x: 223.43593374656064,\n y: 1255.7911059730932,\n },\n ],\n boundingBox: {\n left: 223.43593374656064,\n top: 1212.4905345601246,\n right: 1048.7435946499345,\n bottom: 1255.7911059730932,\n },\n },\n {\n id: "block_6_OGHshO",\n type: "text",\n content:\n "The third is the path length between long-range dependencies in the network. Learning long-range dependencies is a key challenge in many sequence transduction tasks. One key factor affecting the ability to learn such dependencies is the length of the paths forward and backward signals have to traverse in the network. The shorter these paths between any combination of positions in the input and output sequences, the easier it is to learn long-range dependencies [12]. Hence we also compare the maximum path length between any two input and output positions in networks composed of the different layer types.",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.983,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.87737296445525,\n y: 1268.8657945905413,\n },\n {\n x: 1049.749950770914,\n y: 1268.8657945905413,\n },\n {\n x: 1049.749950770914,\n y: 1426.1352065236945,\n },\n {\n x: 222.87737296445525,\n y: 1426.1352065236945,\n },\n ],\n boundingBox: {\n left: 222.87737296445525,\n top: 1268.8657945905413,\n right: 1049.749950770914,\n bottom: 1426.1352065236945,\n },\n },\n {\n id: "block_6_zgN3wO",\n type: "text",\n content:\n "As noted in Table 1, a self-attention layer connects all positions with a constant number of sequentially executed operations, whereas a recurrent layer requires O(n) sequential operations. In terms of computational complexity, self-attention layers are faster than recurrent layers when the sequence",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.4352473794979,\n y: 1439.235182109632,\n },\n {\n x: 1051.6017217705719,\n y: 1439.235182109632,\n },\n {\n x: 1051.6017217705719,\n y: 1506.1062388025728,\n },\n {\n x: 223.4352473794979,\n y: 1506.1062388025728,\n },\n ],\n boundingBox: {\n left: 223.4352473794979,\n top: 1439.235182109632,\n right: 1051.6017217705719,\n bottom: 1506.1062388025728,\n },\n },\n {\n id: "block_6_aNgpKT",\n type: "page_number",\n content: "6",\n metadata: {\n page: {\n number: 6,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 631.7702550957673,\n y: 1548.2886905526757,\n },\n {\n x: 642.7105200551722,\n y: 1548.2886905526757,\n },\n {\n x: 642.7105200551722,\n y: 1563.5418467700931,\n },\n {\n x: 631.7702550957673,\n y: 1563.5418467700931,\n },\n ],\n boundingBox: {\n left: 631.7702550957673,\n top: 1548.2886905526757,\n right: 642.7105200551722,\n bottom: 1563.5418467700931,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_7_u723hy",\n type: "text",\n content:\n "length n is smaller than the representation dimensionality d, which is most often the case with sentence representations used by state-of-the-art models in machine translations, such as word-piece [38] and byte-pair [31] representations. To improve computational performance for tasks involving very long sequences, self-attention could be restricted to considering only a neighborhood of size r in the input sequence centered around the respective output position. This would increase the maximum path length to O(n/r). We plan to investigate this approach further in future work.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.909,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.89144479793353,\n y: 155.39061148363845,\n },\n {\n x: 1050.0338700565978,\n y: 155.39061148363845,\n },\n {\n x: 1050.0338700565978,\n y: 290.11272512163436,\n },\n {\n x: 223.89144479793353,\n y: 290.11272512163436,\n },\n ],\n boundingBox: {\n left: 223.89144479793353,\n top: 155.39061148363845,\n right: 1050.0338700565978,\n bottom: 290.11272512163436,\n },\n },\n {\n id: "block_7_SLgoxa",\n type: "text",\n content:\n "A single convolutional layer with kernel width k < n does not connect all pairs of input and output positions. Doing so requires a stack of O(n/k) convolutional layers in the case of contiguous kernels, or O(logk(n)) in the case of dilated convolutions [18], increasing the length of the longest paths between any two positions in the network. Convolutional layers are generally more expensive than recurrent layers, by a factor of k. Separable convolutions [6], however, decrease the complexity considerably, to O(k . n . d + n . d2). Even with k = n, however, the complexity of a separable convolution is equal to the combination of a self-attention layer and a point-wise feed-forward layer, the approach we take in our model.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.525,\n avgOcrConfidence: 0.977,\n },\n polygon: [\n {\n x: 223.84822734080961,\n y: 303.4973448416344,\n },\n {\n x: 1051.7048188369638,\n y: 303.4973448416344,\n },\n {\n x: 1051.7048188369638,\n y: 482.7421505003047,\n },\n {\n x: 223.84822734080961,\n y: 482.7421505003047,\n },\n ],\n boundingBox: {\n left: 223.84822734080961,\n top: 303.4973448416344,\n right: 1051.7048188369638,\n bottom: 482.7421505003047,\n },\n },\n {\n id: "block_7_lGN5L0",\n type: "text",\n content:\n "As side benefit, self-attention could yield more interpretable models. We inspect attention distributions from our models and present and discuss examples in the appendix. Not only do individual attention heads clearly learn to perform different tasks, many appear to exhibit behavior related to the syntactic and semantic structure of the sentences.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.94,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.7218884656029,\n y: 496.4417208334557,\n },\n {\n x: 1049.5183847246378,\n y: 496.4417208334557,\n },\n {\n x: 1049.5183847246378,\n y: 581.3287481437052,\n },\n {\n x: 223.7218884656029,\n y: 581.3287481437052,\n },\n ],\n boundingBox: {\n left: 223.7218884656029,\n top: 496.4417208334557,\n right: 1049.5183847246378,\n bottom: 581.3287481437052,\n },\n },\n {\n id: "block_7_FOtl5B",\n type: "heading",\n content: "# 5 Training",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.4122553915873,\n y: 625.3390120599503,\n },\n {\n x: 354.91415984439146,\n y: 625.3390120599503,\n },\n {\n x: 354.91415984439146,\n y: 649.7166914688913,\n },\n {\n x: 224.4122553915873,\n y: 649.7166914688913,\n },\n ],\n boundingBox: {\n left: 224.4122553915873,\n top: 625.3390120599503,\n right: 354.91415984439146,\n bottom: 649.7166914688913,\n },\n },\n {\n id: "block_7_3jYBCf",\n type: "text",\n content: "This section describes the training regime for our models.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.4527957665659,\n y: 679.1303132709704,\n },\n {\n x: 701.988161741382,\n y: 679.1303132709704,\n },\n {\n x: 701.988161741382,\n y: 699.7081758025894,\n },\n {\n x: 222.4527957665659,\n y: 699.7081758025894,\n },\n ],\n boundingBox: {\n left: 222.4527957665659,\n top: 679.1303132709704,\n right: 701.988161741382,\n bottom: 699.7081758025894,\n },\n },\n {\n id: "block_7_PIafds",\n type: "section_heading",\n content: "### 5.1 Training Data and Batching",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.68002007477475,\n y: 735.0401794318866,\n },\n {\n x: 519.6398407873446,\n y: 735.0401794318866,\n },\n {\n x: 519.6398407873446,\n y: 755.8565634247055,\n },\n {\n x: 223.68002007477475,\n y: 755.8565634247055,\n },\n ],\n boundingBox: {\n left: 223.68002007477475,\n top: 735.0401794318866,\n right: 519.6398407873446,\n bottom: 755.8565634247055,\n },\n },\n {\n id: "block_7_8RhsHH",\n type: "text",\n content:\n "We trained on the standard WMT 2014 English-German dataset consisting of about 4.5 million sentence pairs. Sentences were encoded using byte-pair encoding [3], which has a shared source- target vocabulary of about 37000 tokens. For English-French, we used the significantly larger WMT 2014 English-French dataset consisting of 36M sentences and split tokens into a 32000 word-piece vocabulary [38]. Sentence pairs were batched together by approximate sequence length. Each training batch contained a set of sentence pairs containing approximately 25000 source tokens and 25000 target tokens.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.911,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.70165247116648,\n y: 778.8621643467953,\n },\n {\n x: 1052.1871692072737,\n y: 778.8621643467953,\n },\n {\n x: 1052.1871692072737,\n y: 935.23512009929,\n },\n {\n x: 223.70165247116648,\n y: 935.23512009929,\n },\n ],\n boundingBox: {\n left: 223.70165247116648,\n top: 778.8621643467953,\n right: 1052.1871692072737,\n bottom: 935.23512009929,\n },\n },\n {\n id: "block_7_2fOgoW",\n type: "section_heading",\n content: "### 5.2 Hardware and Schedule",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.9209349138023,\n y: 971.4598863071069,\n },\n {\n x: 484.7486314982394,\n y: 971.4598863071069,\n },\n {\n x: 484.7486314982394,\n y: 987.6652342143811,\n },\n {\n x: 223.9209349138023,\n y: 987.6652342143811,\n },\n ],\n boundingBox: {\n left: 223.9209349138023,\n top: 971.4598863071069,\n right: 484.7486314982394,\n bottom: 987.6652342143811,\n },\n },\n {\n id: "block_7_7vykWe",\n type: "text",\n content:\n "We trained our models on one machine with 8 NVIDIA P100 GPUs. For our base models using the hyperparameters described throughout the paper, each training step took about 0.4 seconds. We trained the base models for a total of 100,000 steps or 12 hours. For our big models,(described on the bottom line of table 3), step time was 1.0 seconds. The big models were trained for 300,000 steps (3.5 days).",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.961,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 223.2459757449853,\n y: 1014.9955223485043,\n },\n {\n x: 1049.3973947789548,\n y: 1014.9955223485043,\n },\n {\n x: 1049.3973947789548,\n y: 1126.7015106660083,\n },\n {\n x: 223.2459757449853,\n y: 1126.7015106660083,\n },\n ],\n boundingBox: {\n left: 223.2459757449853,\n top: 1014.9955223485043,\n right: 1049.3973947789548,\n bottom: 1126.7015106660083,\n },\n },\n {\n id: "block_7_Xjy6qb",\n type: "section_heading",\n content: "### 5.3 Optimizer",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.84361211400832,\n y: 1161.1210525053784,\n },\n {\n x: 361.9454223744191,\n y: 1161.1210525053784,\n },\n {\n x: 361.9454223744191,\n y: 1181.9203891037102,\n },\n {\n x: 223.84361211400832,\n y: 1181.9203891037102,\n },\n ],\n boundingBox: {\n left: 223.84361211400832,\n top: 1161.1210525053784,\n right: 361.9454223744191,\n bottom: 1181.9203891037102,\n },\n },\n {\n id: "block_7_uZS3FC",\n type: "text",\n content:\n "We used the Adam optimizer [20] with 31 = 0.9, 32 = 0.98 and \\u20ac = 10-9. We varied the learning rate over the course of training, according to the formula:",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.472,\n avgOcrConfidence: 0.947,\n },\n polygon: [\n {\n x: 223.18536243299496,\n y: 1203.7906809068263,\n },\n {\n x: 1049.5936484232436,\n y: 1203.7906809068263,\n },\n {\n x: 1049.5936484232436,\n y: 1249.0720648514596,\n },\n {\n x: 223.18536243299496,\n y: 1249.0720648514596,\n },\n ],\n boundingBox: {\n left: 223.18536243299496,\n top: 1203.7906809068263,\n right: 1049.5936484232436,\n bottom: 1249.0720648514596,\n },\n },\n {\n id: "block_7_qvJczg",\n type: "text",\n content:\n "lrate = dmodel . min(step_num-0.5, step_num . warmup_steps-1.5)",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Formula",\n minOcrConfidence: 0.563,\n avgOcrConfidence: 0.786,\n },\n polygon: [\n {\n x: 338.51696905428474,\n y: 1286.921258338412,\n },\n {\n x: 933.735361586522,\n y: 1286.921258338412,\n },\n {\n x: 933.735361586522,\n y: 1314.0637410099346,\n },\n {\n x: 338.51696905428474,\n y: 1314.0637410099346,\n },\n ],\n boundingBox: {\n left: 338.51696905428474,\n top: 1286.921258338412,\n right: 933.735361586522,\n bottom: 1314.0637410099346,\n },\n },\n {\n id: "block_7_ZRnl1T",\n type: "text",\n content: "(3)",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 1026.6387883764114,\n y: 1291.0368781986094,\n },\n {\n x: 1051.2767151324417,\n y: 1291.0368781986094,\n },\n {\n x: 1051.2767151324417,\n y: 1311.080825805664,\n },\n {\n x: 1026.6387883764114,\n y: 1311.080825805664,\n },\n ],\n boundingBox: {\n left: 1026.6387883764114,\n top: 1291.0368781986094,\n right: 1051.2767151324417,\n bottom: 1311.080825805664,\n },\n },\n {\n id: "block_7_M71nL9",\n type: "text",\n content:\n "This corresponds to increasing the learning rate linearly for the first warmup_steps training steps, and decreasing it thereafter proportionally to the inverse square root of the step number. We used warmup_steps = 4000.",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.916,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 222.72840764400732,\n y: 1340.2761936044335,\n },\n {\n x: 1052.0266066502481,\n y: 1340.2761936044335,\n },\n {\n x: 1052.0266066502481,\n y: 1406.6737115616188,\n },\n {\n x: 222.72840764400732,\n y: 1406.6737115616188,\n },\n ],\n boundingBox: {\n left: 222.72840764400732,\n top: 1340.2761936044335,\n right: 1052.0266066502481,\n bottom: 1406.6737115616188,\n },\n },\n {\n id: "block_7_ACakMa",\n type: "section_heading",\n content: "### 5.4 Regularization",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.81116351942077,\n y: 1441.41800626597,\n },\n {\n x: 402.1996435457773,\n y: 1441.41800626597,\n },\n {\n x: 402.1996435457773,\n y: 1461.9926013803124,\n },\n {\n x: 223.81116351942077,\n y: 1461.9926013803124,\n },\n ],\n boundingBox: {\n left: 223.81116351942077,\n top: 1441.41800626597,\n right: 402.1996435457773,\n bottom: 1461.9926013803124,\n },\n },\n {\n id: "block_7_rR8JeL",\n type: "text",\n content: "We employ three types of regularization during training:",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.88627206844134,\n y: 1484.7892296583134,\n },\n {\n x: 690.987449144795,\n y: 1484.7892296583134,\n },\n {\n x: 690.987449144795,\n y: 1505.950728681751,\n },\n {\n x: 222.88627206844134,\n y: 1505.950728681751,\n },\n ],\n boundingBox: {\n left: 222.88627206844134,\n top: 1484.7892296583134,\n right: 690.987449144795,\n bottom: 1505.950728681751,\n },\n },\n {\n id: "block_7_I7j7Uy",\n type: "page_number",\n content: "7",\n metadata: {\n page: {\n number: 7,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.996,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 631.8865114755004,\n y: 1547.4189893105872,\n },\n {\n x: 642.4512153124288,\n y: 1547.4189893105872,\n },\n {\n x: 642.4512153124288,\n y: 1562.541448836936,\n },\n {\n x: 631.8865114755004,\n y: 1562.541448836936,\n },\n ],\n boundingBox: {\n left: 631.8865114755004,\n top: 1547.4189893105872,\n right: 642.4512153124288,\n bottom: 1562.541448836936,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_8_8rtbBp",\n type: "text",\n content:\n "Table 2: The Transformer achieves better BLEU scores than previous state-of-the-art models on the English-to-German and English-to-French newstest2014 tests at a fraction of the training cost.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 222.40285664579295,\n y: 148.11078211418666,\n },\n {\n x: 1048.695596291201,\n y: 148.11078211418666,\n },\n {\n x: 1048.695596291201,\n y: 191.8824890538266,\n },\n {\n x: 222.40285664579295,\n y: 191.8824890538266,\n },\n ],\n boundingBox: {\n left: 222.40285664579295,\n top: 148.11078211418666,\n right: 1048.695596291201,\n bottom: 191.8824890538266,\n },\n },\n {\n id: "block_8_M3V7h9",\n type: "table",\n content:\n "| Model | BLEU | | Training Cost (FLOPs) | |\\n| --- | --- | --- | --- | --- |\\n| | EN-DE | EN-FR | EN-DE | EN-FR |\\n| ByteNet [18] | 23.75 | | | |\\n| Deep-Att + PosUnk [39] | | 39.2 | | 1.0 . 1020 |\\n| GNMT + RL [38] | 24.6 | 39.92 | 2.3 . 1019 | 1.4 . 1020 |\\n| ConvS2S [9] | 25.16 | 40.46 | 9.6 . 1018 | 1.5 . 1020 |\\n| MoE [32] | 26.03 | 40.56 | 2.0 \\u00b7 1019 | 1.2 . 1020 |\\n| Deep-Att + PosUnk Ensemble [39] | | 40.4 | | 8.0 . 1020 |\\n| GNMT + RL Ensemble [38] | 26.30 | 41.16 | 1.8 . 1020 | 1.1 . 1021 |\\n| ConvS2S Ensemble [9] | 26.36 | 41.29 | 7.7 . 1019 | 1.2 . 1021 |\\n| Transformer (base model) | 27.3 | 38.1 | 3.3 . | 1018 |\\n| Transformer (big) | 28.4 | 41.8 | 2.3. 1019 | |",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.141,\n avgOcrConfidence: 0.893,\n },\n polygon: [\n {\n x: 271.150136516042,\n y: 195.3426247575229,\n },\n {\n x: 1004.1704442379248,\n y: 195.3426247575229,\n },\n {\n x: 1004.1704442379248,\n y: 508.6132290201976,\n },\n {\n x: 271.150136516042,\n y: 508.6132290201976,\n },\n ],\n boundingBox: {\n left: 271.150136516042,\n top: 195.3426247575229,\n right: 1004.1704442379248,\n bottom: 508.6132290201976,\n },\n },\n {\n id: "block_8_Wl0xmI",\n type: "text",\n content:\n "Residual Dropout We apply dropout [33] to the output of each sub-layer, before it is added to the sub-layer input and normalized. In addition, we apply dropout to the sums of the embeddings and the positional encodings in both the encoder and decoder stacks. For the base model, we use a rate of Pdrop =0.1.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.893,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 223.9333605244212,\n y: 569.1121117154458,\n },\n {\n x: 1051.605887308608,\n y: 569.1121117154458,\n },\n {\n x: 1051.605887308608,\n y: 660.0886577520155,\n },\n {\n x: 223.9333605244212,\n y: 660.0886577520155,\n },\n ],\n boundingBox: {\n left: 223.9333605244212,\n top: 569.1121117154458,\n right: 1051.605887308608,\n bottom: 660.0886577520155,\n },\n },\n {\n id: "block_8_CtqTnb",\n type: "text",\n content:\n "Label Smoothing During training, we employed label smoothing of value Els = 0.1 [36]. This hurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.518,\n avgOcrConfidence: 0.977,\n },\n polygon: [\n {\n x: 223.52019122047145,\n y: 690.790115499855,\n },\n {\n x: 1049.6801780088103,\n y: 690.790115499855,\n },\n {\n x: 1049.6801780088103,\n y: 734.1354363233523,\n },\n {\n x: 223.52019122047145,\n y: 734.1354363233523,\n },\n ],\n boundingBox: {\n left: 223.52019122047145,\n top: 690.790115499855,\n right: 1049.6801780088103,\n bottom: 734.1354363233523,\n },\n },\n {\n id: "block_8_KA1kZT",\n type: "heading",\n content: "# 6 Results",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.16400352533717,\n y: 774.585115131579,\n },\n {\n x: 339.42863018843383,\n y: 774.585115131579,\n },\n {\n x: 339.42863018843383,\n y: 793.809935433524,\n },\n {\n x: 224.16400352533717,\n y: 793.809935433524,\n },\n ],\n boundingBox: {\n left: 224.16400352533717,\n top: 774.585115131579,\n right: 339.42863018843383,\n bottom: 793.809935433524,\n },\n },\n {\n id: "block_8_LYkEL8",\n type: "section_heading",\n content: "### 6.1 Machine Translation",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 224.2968510537252,\n y: 828.3471990026029,\n },\n {\n x: 455.2866330111984,\n y: 828.3471990026029,\n },\n {\n x: 455.2866330111984,\n y: 844.3720339438072,\n },\n {\n x: 224.2968510537252,\n y: 844.3720339438072,\n },\n ],\n boundingBox: {\n left: 224.2968510537252,\n top: 828.3471990026029,\n right: 455.2866330111984,\n bottom: 844.3720339438072,\n },\n },\n {\n id: "block_8_UnI1Ea",\n type: "text",\n content:\n "On the WMT 2014 English-to-German translation task, the big transformer model (Transformer (big) in Table 2) outperforms the best previously reported models (including ensembles) by more than 2.0 BLEU, establishing a new state-of-the-art BLEU score of 28.4. The configuration of this model is listed in the bottom line of Table 3. Training took 3.5 days on 8 P100 GPUs. Even our base model surpasses all previously published models and ensembles, at a fraction of the training cost of any of the competitive models.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.973,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.56291165317063,\n y: 872.0711140453367,\n },\n {\n x: 1050.5385628581919,\n y: 872.0711140453367,\n },\n {\n x: 1050.5385628581919,\n y: 1006.0390107004266,\n },\n {\n x: 223.56291165317063,\n y: 1006.0390107004266,\n },\n ],\n boundingBox: {\n left: 223.56291165317063,\n top: 872.0711140453367,\n right: 1050.5385628581919,\n bottom: 1006.0390107004266,\n },\n },\n {\n id: "block_8_pkBARc",\n type: "text",\n content:\n "On the WMT 2014 English-to-French translation task, our big model achieves a BLEU score of 41.0, outperforming all of the previously published single models, at less than 1/4 the training cost of the previous state-of-the-art model. The Transformer (big) model trained for English-to-French used dropout rate Pdrop = 0.1, instead of 0.3.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.945,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.05139199138557,\n y: 1019.1086798072756,\n },\n {\n x: 1052.2523977460653,\n y: 1019.1086798072756,\n },\n {\n x: 1052.2523977460653,\n y: 1109.5784446888401,\n },\n {\n x: 224.05139199138557,\n y: 1109.5784446888401,\n },\n ],\n boundingBox: {\n left: 224.05139199138557,\n top: 1019.1086798072756,\n right: 1052.2523977460653,\n bottom: 1109.5784446888401,\n },\n },\n {\n id: "block_8_vKs7Yg",\n type: "text",\n content:\n "For the base models, we used a single model obtained by averaging the last 5 checkpoints, which were written at 10-minute intervals. For the big models, we averaged the last 20 checkpoints. We used beam search with a beam size of 4 and length penalty & = 0.6 [38]. These hyperparameters were chosen after experimentation on the development set. We set the maximum output length during inference to input length + 50, but terminate early when possible [38].",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.099,\n avgOcrConfidence: 0.983,\n },\n polygon: [\n {\n x: 223.50279536560504,\n y: 1122.2645474197273,\n },\n {\n x: 1050.043905216412,\n y: 1122.2645474197273,\n },\n {\n x: 1050.043905216412,\n y: 1233.5787297872673,\n },\n {\n x: 223.50279536560504,\n y: 1233.5787297872673,\n },\n ],\n boundingBox: {\n left: 223.50279536560504,\n top: 1122.2645474197273,\n right: 1050.043905216412,\n bottom: 1233.5787297872673,\n },\n },\n {\n id: "block_8_42PSVl",\n type: "text",\n content:\n "Table 2 summarizes our results and compares our translation quality and training costs to other model architectures from the literature. We estimate the number of floating point operations used to train a model by multiplying the training time, the number of GPUs used, and an estimate of the sustained single-precision floating-point capacity of each GPU 5.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.975,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 222.3879459130503,\n y: 1247.2785842436597,\n },\n {\n x: 1049.63284234931,\n y: 1247.2785842436597,\n },\n {\n x: 1049.63284234931,\n y: 1336.1913537620603,\n },\n {\n x: 222.3879459130503,\n y: 1336.1913537620603,\n },\n ],\n boundingBox: {\n left: 222.3879459130503,\n top: 1247.2785842436597,\n right: 1049.63284234931,\n bottom: 1336.1913537620603,\n },\n },\n {\n id: "block_8_pDx0nB",\n type: "section_heading",\n content: "### 6.2 Model Variations",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.05955739264942,\n y: 1370.9984397027727,\n },\n {\n x: 424.93188398597886,\n y: 1370.9984397027727,\n },\n {\n x: 424.93188398597886,\n y: 1387.4261614003576,\n },\n {\n x: 224.05955739264942,\n y: 1387.4261614003576,\n },\n ],\n boundingBox: {\n left: 224.05955739264942,\n top: 1370.9984397027727,\n right: 424.93188398597886,\n bottom: 1387.4261614003576,\n },\n },\n {\n id: "block_8_XCLvsN",\n type: "text",\n content:\n "To evaluate the importance of different components of the Transformer, we varied our base model in different ways, measuring the change in performance on English-to-German translation on the",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 222.6526705888066,\n y: 1413.835037862448,\n },\n {\n x: 1049.9819901737853,\n y: 1413.835037862448,\n },\n {\n x: 1049.9819901737853,\n y: 1458.0598621798638,\n },\n {\n x: 222.6526705888066,\n y: 1458.0598621798638,\n },\n ],\n boundingBox: {\n left: 222.6526705888066,\n top: 1413.835037862448,\n right: 1049.9819901737853,\n bottom: 1458.0598621798638,\n },\n },\n {\n id: "block_8_6e9VRc",\n type: "text",\n content:\n "5We used values of 2.8, 3.7, 6.0 and 9.5 TFLOPS for K80, K40, M40 and P100, respectively.",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.976,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 249.0640041601919,\n y: 1482.8447849015545,\n },\n {\n x: 944.2274051861172,\n y: 1482.8447849015545,\n },\n {\n x: 944.2274051861172,\n y: 1505.4603319670025,\n },\n {\n x: 249.0640041601919,\n y: 1505.4603319670025,\n },\n ],\n boundingBox: {\n left: 249.0640041601919,\n top: 1482.8447849015545,\n right: 944.2274051861172,\n bottom: 1505.4603319670025,\n },\n },\n {\n id: "block_8_HHxEh9",\n type: "page_number",\n content: "8",\n metadata: {\n page: {\n number: 8,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.996,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 631.7743259624843,\n y: 1547.954182789738,\n },\n {\n x: 642.6607229413778,\n y: 1547.954182789738,\n },\n {\n x: 642.6607229413778,\n y: 1563.2957013352473,\n },\n {\n x: 631.7743259624843,\n y: 1563.2957013352473,\n },\n ],\n boundingBox: {\n left: 631.7743259624843,\n top: 1547.954182789738,\n right: 642.6607229413778,\n bottom: 1563.2957013352473,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_9_2CG18E",\n type: "text",\n content:\n "Table 3: Variations on the Transformer architecture. Unlisted values are identical to those of the base model. All metrics are on the English-to-German translation development set, newstest2013. Listed perplexities are per-wordpiece, according to our byte-pair encoding, and should not be compared to per-word perplexities.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.99,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 222.6654748847015,\n y: 147.86792777355453,\n },\n {\n x: 1049.6700481776775,\n y: 147.86792777355453,\n },\n {\n x: 1049.6700481776775,\n y: 237.19010704442076,\n },\n {\n x: 222.6654748847015,\n y: 237.19010704442076,\n },\n ],\n boundingBox: {\n left: 222.6654748847015,\n top: 147.86792777355453,\n right: 1049.6700481776775,\n bottom: 237.19010704442076,\n },\n },\n {\n id: "block_9_0WToWH",\n type: "table",\n content:\n "| | N | dmodel | dff | h | dk | dv | Pdrop | Els | train steps | PPL (dev) | BLEU (dev) | params \\u00d7106 |\\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\\n| base | 6 | 512 | 2048 | 8 | 64 | 64 | 0.1 | 0.1 | 100K | 4.92 | 25.8 | 65 |\\n| (A) | | | | 1 | 512 | 512 | | | | 5.29 | 24.9 | |\\n| | | | | 4 | 128 | 128 | | | | 5.00 | 25.5 | |\\n| | | | | 16 | 32 | 32 | | | | 4.91 | 25.8 | |\\n| | | | | 32 | 16 | 16 | | | | 5.01 | 25.4 | |\\n| (B) | | | | | 16 | | | | | 5.16 | 25.1 | 58 |\\n| | | | | | 32 | | | | | 5.01 | 25.4 | 60 |\\n| (C) | 2 | | | | | | | | | 6.11 | 23.7 | 36 |\\n| | 4 | | | | | | | | | 5.19 | 25.3 | 50 |\\n| | 8 | | | | | | | | | 4.88 | 25.5 | 80 |\\n| | | 256 | | | 32 | 32 | | | | 5.75 | 24.5 | 28 |\\n| | | 1024 | | | 128 | 128 | | | | 4.66 | 26.0 | 168 |\\n| | | | 1024 | | | | | | | 5.12 | 25.4 | 53 |\\n| | | | 4096 | | | | | | | 4.75 | 26.2 | 90 |\\n| (D) | | | | | | | 0.0 | | | 5.77 | 24.6 | |\\n| | | | | | | | 0.2 | | | 4.95 | 25.5 | |\\n| | | | | | | | | 0.0 | | 4.67 | 25.3 | |\\n| | | | | | | | | 0.2 | | 5.47 | 25.7 | |\\n| (E) | positional embedding | | | | | instead of | sinusoids | | | 4.92 | 25.7 | |\\n| big | 6 | 1024 | 4096 | 16 | | | 0.3 | | 300K | 4.33 | 26.4 | 213 |",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.612,\n avgOcrConfidence: 0.986,\n },\n polygon: [\n {\n x: 224.84461930546448,\n y: 268.65403318763674,\n },\n {\n x: 1060.6742636130673,\n y: 268.65403318763674,\n },\n {\n x: 1060.6742636130673,\n y: 801.2216690178204,\n },\n {\n x: 224.84461930546448,\n y: 801.2216690178204,\n },\n ],\n boundingBox: {\n left: 224.84461930546448,\n top: 268.65403318763674,\n right: 1060.6742636130673,\n bottom: 801.2216690178204,\n },\n },\n {\n id: "block_9_p8WB9c",\n type: "text",\n content:\n "development set, newstest2013. We used beam search as described in the previous section, but no checkpoint averaging. We present these results in Table 3.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.42882287241247,\n y: 862.6040329323675,\n },\n {\n x: 1049.5265264580719,\n y: 862.6040329323675,\n },\n {\n x: 1049.5265264580719,\n y: 905.6541023541213,\n },\n {\n x: 224.42882287241247,\n y: 905.6541023541213,\n },\n ],\n boundingBox: {\n left: 224.42882287241247,\n top: 862.6040329323675,\n right: 1049.5265264580719,\n bottom: 905.6541023541213,\n },\n },\n {\n id: "block_9_XvsIA2",\n type: "text",\n content:\n "In Table 3 rows (A), we vary the number of attention heads and the attention key and value dimensions, keeping the amount of computation constant, as described in Section 3.2.2. While single-head attention is 0.9 BLEU worse than the best setting, quality also drops off with too many heads.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.967,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 224.23600106343736,\n y: 918.8913094656807,\n },\n {\n x: 1052.034559041044,\n y: 918.8913094656807,\n },\n {\n x: 1052.034559041044,\n y: 986.1080494357232,\n },\n {\n x: 224.23600106343736,\n y: 986.1080494357232,\n },\n ],\n boundingBox: {\n left: 224.23600106343736,\n top: 918.8913094656807,\n right: 1052.034559041044,\n bottom: 986.1080494357232,\n },\n },\n {\n id: "block_9_lFHLbG",\n type: "text",\n content:\n "In Table 3 rows (B), we observe that reducing the attention key size dk hurts model quality. This suggests that determining compatibility is not easy and that a more sophisticated compatibility function than dot product may be beneficial. We further observe in rows (C) and (D) that, as expected, bigger models are better, and dropout is very helpful in avoiding over-fitting. In row (E) we replace our sinusoidal positional encoding with learned positional embeddings [9], and observe nearly identical results to the base model.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.881,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.0262804240206,\n y: 998.9746651326803,\n },\n {\n x: 1052.338643317675,\n y: 998.9746651326803,\n },\n {\n x: 1052.338643317675,\n y: 1130.1984048140678,\n },\n {\n x: 224.0262804240206,\n y: 1130.1984048140678,\n },\n ],\n boundingBox: {\n left: 224.0262804240206,\n top: 998.9746651326803,\n right: 1052.338643317675,\n bottom: 1130.1984048140678,\n },\n },\n {\n id: "block_9_nnE2Kn",\n type: "section_heading",\n content: "### 6.3 English Constituency Parsing",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.994,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 224.00199723069687,\n y: 1168.0604785546325,\n },\n {\n x: 533.1579584274849,\n y: 1168.0604785546325,\n },\n {\n x: 533.1579584274849,\n y: 1188.5333575485345,\n },\n {\n x: 224.00199723069687,\n y: 1188.5333575485345,\n },\n ],\n boundingBox: {\n left: 224.00199723069687,\n top: 1168.0604785546325,\n right: 533.1579584274849,\n bottom: 1188.5333575485345,\n },\n },\n {\n id: "block_9_UvLm1J",\n type: "text",\n content:\n "To evaluate if the Transformer can generalize to other tasks we performed experiments on English constituency parsing. This task presents specific challenges: the output is subject to strong structural constraints and is significantly longer than the input. Furthermore, RNN sequence-to-sequence models have not been able to attain state-of-the-art results in small-data regimes [37].",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.963,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.0787388599702,\n y: 1212.099580979885,\n },\n {\n x: 1049.9080518736457,\n y: 1212.099580979885,\n },\n {\n x: 1049.9080518736457,\n y: 1300.6617424183323,\n },\n {\n x: 223.0787388599702,\n y: 1300.6617424183323,\n },\n ],\n boundingBox: {\n left: 223.0787388599702,\n top: 1212.099580979885,\n right: 1049.9080518736457,\n bottom: 1300.6617424183323,\n },\n },\n {\n id: "block_9_nmNLPf",\n type: "text",\n content:\n "We trained a 4-layer transformer with dmodel = 1024 on the Wall Street Journal (WSJ) portion of the Penn Treebank [25], about 40K training sentences. We also trained it in a semi-supervised setting, using the larger high-confidence and BerkleyParser corpora from with approximately 17M sentences [37]. We used a vocabulary of 16K tokens for the WSJ only setting and a vocabulary of 32K tokens for the semi-supervised setting.",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 223.08401678600453,\n y: 1314.1105266370273,\n },\n {\n x: 1051.1732393807738,\n y: 1314.1105266370273,\n },\n {\n x: 1051.1732393807738,\n y: 1425.9921031177494,\n },\n {\n x: 223.08401678600453,\n y: 1425.9921031177494,\n },\n ],\n boundingBox: {\n left: 223.08401678600453,\n top: 1314.1105266370273,\n right: 1051.1732393807738,\n bottom: 1425.9921031177494,\n },\n },\n {\n id: "block_9_kQhH3x",\n type: "text",\n content:\n "We performed only a small number of experiments to select the dropout, both attention and residual (section 5.4), learning rates and beam size on the Section 22 development set, all other parameters remained unchanged from the English-to-German base translation model. During inference, we",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.1762739863709,\n y: 1439.0945411051127,\n },\n {\n x: 1050.7557388639798,\n y: 1439.0945411051127,\n },\n {\n x: 1050.7557388639798,\n y: 1505.8386894168711,\n },\n {\n x: 223.1762739863709,\n y: 1505.8386894168711,\n },\n ],\n boundingBox: {\n left: 223.1762739863709,\n top: 1439.0945411051127,\n right: 1050.7557388639798,\n bottom: 1505.8386894168711,\n },\n },\n {\n id: "block_9_C4QuNg",\n type: "page_number",\n content: "9",\n metadata: {\n page: {\n number: 9,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 631.6446262554531,\n y: 1547.2787271370566,\n },\n {\n x: 642.3550765879834,\n y: 1547.2787271370566,\n },\n {\n x: 642.3550765879834,\n y: 1562.906831325445,\n },\n {\n x: 631.6446262554531,\n y: 1562.906831325445,\n },\n ],\n boundingBox: {\n left: 631.6446262554531,\n top: 1547.2787271370566,\n right: 642.3550765879834,\n bottom: 1562.906831325445,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_10_Whfo1k",\n type: "text",\n content:\n "Table 4: The Transformer generalizes well to English constituency parsing (Results are on Section 23 of WSJ)",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.988,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 222.60232911492787,\n y: 147.913837353986,\n },\n {\n x: 1049.0453121435903,\n y: 147.913837353986,\n },\n {\n x: 1049.0453121435903,\n y: 190.50408882485297,\n },\n {\n x: 222.60232911492787,\n y: 190.50408882485297,\n },\n ],\n boundingBox: {\n left: 222.60232911492787,\n top: 147.913837353986,\n right: 1049.0453121435903,\n bottom: 190.50408882485297,\n },\n },\n {\n id: "block_10_Oq0boE",\n type: "table",\n content:\n "| Parser | Training | WSJ 23 F1 |\\n| --- | --- | --- |\\n| Vinyals & Kaiser el al. (2014) [37] | WSJ only, discriminative | 88.3 |\\n| Petrov et al. (2006) [29] | WSJ only, discriminative | 90.4 |\\n| Zhu et al. (2013) [40] | WSJ only, discriminative | 90.4 |\\n| Dyer et al. (2016) [8] | WSJ only, discriminative | 91.7 |\\n| Transformer (4 layers) | WSJ only, discriminative | 91.3 |\\n| Zhu et al. (2013) [40] | semi-supervised | 91.3 |\\n| Huang & Harper (2009) [14] | semi-supervised | 91.3 |\\n| McClosky et al. (2006) [26] | semi-supervised | 92.1 |\\n| Vinyals & Kaiser el al. (2014) [37] | semi-supervised | 92.1 |\\n| Transformer (4 layers) | semi-supervised | 92.7 |\\n| Luong et al. (2015) [23] | multi-task | 93.0 |\\n| Dyer et al. (2016) [8] | generative | 93.3 |",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Table",\n minOcrConfidence: 0.926,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 300.48226962124346,\n y: 193.81453893417702,\n },\n {\n x: 974.1206315312072,\n y: 193.81453893417702,\n },\n {\n x: 974.1206315312072,\n y: 493.68785631567016,\n },\n {\n x: 300.48226962124346,\n y: 493.68785631567016,\n },\n ],\n boundingBox: {\n left: 300.48226962124346,\n top: 193.81453893417702,\n right: 974.1206315312072,\n bottom: 493.68785631567016,\n },\n },\n {\n id: "block_10_wSUPzw",\n type: "text",\n content:\n "increased the maximum output length to input length + 300. We used a beam size of 21 and & = 0.3 for both WSJ only and the semi-supervised setting.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.117,\n avgOcrConfidence: 0.964,\n },\n polygon: [\n {\n x: 223.84354111051908,\n y: 546.3992524398001,\n },\n {\n x: 1049.2353174808252,\n y: 546.3992524398001,\n },\n {\n x: 1049.2353174808252,\n y: 589.787902057619,\n },\n {\n x: 223.84354111051908,\n y: 589.787902057619,\n },\n ],\n boundingBox: {\n left: 223.84354111051908,\n top: 546.3992524398001,\n right: 1049.2353174808252,\n bottom: 589.787902057619,\n },\n },\n {\n id: "block_10_KdYXbX",\n type: "text",\n content:\n "Our results in Table 4 show that despite the lack of task-specific tuning our model performs sur- prisingly well, yielding better results than all previously reported models with the exception of the Recurrent Neural Network Grammar [8].",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.917,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.34470740548016,\n y: 603.5821801379211,\n },\n {\n x: 1052.1757139776746,\n y: 603.5821801379211,\n },\n {\n x: 1052.1757139776746,\n y: 667.7562916691143,\n },\n {\n x: 224.34470740548016,\n y: 667.7562916691143,\n },\n ],\n boundingBox: {\n left: 224.34470740548016,\n top: 603.5821801379211,\n right: 1052.1757139776746,\n bottom: 667.7562916691143,\n },\n },\n {\n id: "block_10_spL6f1",\n type: "text",\n content:\n "In contrast to RNN sequence-to-sequence models [37], the Transformer outperforms the Berkeley- Parser [29] even when training only on the WSJ training set of 40K sentences.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.907,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.93137242672216,\n y: 683.4819921909419,\n },\n {\n x: 1052.021589070341,\n y: 683.4819921909419,\n },\n {\n x: 1052.021589070341,\n y: 725.8283830513632,\n },\n {\n x: 223.93137242672216,\n y: 725.8283830513632,\n },\n ],\n boundingBox: {\n left: 223.93137242672216,\n top: 683.4819921909419,\n right: 1052.021589070341,\n bottom: 725.8283830513632,\n },\n },\n {\n id: "block_10_FpxS4M",\n type: "section_heading",\n content: "### 7 Conclusion",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.993,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.87968188654767,\n y: 760.911873552136,\n },\n {\n x: 380.37754949862074,\n y: 760.911873552136,\n },\n {\n x: 380.37754949862074,\n y: 780.8896204439321,\n },\n {\n x: 223.87968188654767,\n y: 780.8896204439321,\n },\n ],\n boundingBox: {\n left: 223.87968188654767,\n top: 760.911873552136,\n right: 380.37754949862074,\n bottom: 780.8896204439321,\n },\n },\n {\n id: "block_10_06Cxhy",\n type: "text",\n content:\n "In this work, we presented the Transformer, the first sequence transduction model based entirely on attention, replacing the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.7800876589587,\n y: 811.1846398948727,\n },\n {\n x: 1049.4503160462762,\n y: 811.1846398948727,\n },\n {\n x: 1049.4503160462762,\n y: 872.951422555106,\n },\n {\n x: 223.7800876589587,\n y: 872.951422555106,\n },\n ],\n boundingBox: {\n left: 223.7800876589587,\n top: 811.1846398948727,\n right: 1049.4503160462762,\n bottom: 872.951422555106,\n },\n },\n {\n id: "block_10_4PqBx5",\n type: "text",\n content:\n "For translation tasks, the Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers. On both WMT 2014 English-to-German and WMT 2014 English-to-French translation tasks, we achieve a new state of the art. In the former task our best model outperforms even all previously reported ensembles.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.989,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 223.91187013500797,\n y: 890.9364237390963,\n },\n {\n x: 1049.8108244290318,\n y: 890.9364237390963,\n },\n {\n x: 1049.8108244290318,\n y: 980.2941302536126,\n },\n {\n x: 223.91187013500797,\n y: 980.2941302536126,\n },\n ],\n boundingBox: {\n left: 223.91187013500797,\n top: 890.9364237390963,\n right: 1049.8108244290318,\n bottom: 980.2941302536126,\n },\n },\n {\n id: "block_10_9Aa2OZ",\n type: "text",\n content:\n "We are excited about the future of attention-based models and plan to apply them to other tasks. We plan to extend the Transformer to problems involving input and output modalities other than text and to investigate local, restricted attention mechanisms to efficiently handle large inputs and outputs such as images, audio and video. Making generation less sequential is another research goals of ours.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.985,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 223.4691397117002,\n y: 993.4156992059005,\n },\n {\n x: 1051.09778633953,\n y: 993.4156992059005,\n },\n {\n x: 1051.09778633953,\n y: 1081.8706514745727,\n },\n {\n x: 223.4691397117002,\n y: 1081.8706514745727,\n },\n ],\n boundingBox: {\n left: 223.4691397117002,\n top: 993.4156992059005,\n right: 1051.09778633953,\n bottom: 1081.8706514745727,\n },\n },\n {\n id: "block_10_eXUU9v",\n type: "text",\n content:\n "The code we used to train and evaluate our models is available at https://github.com/ tensorflow/tensor2tensor.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.94,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 222.4288912585182,\n y: 1095.2490678371344,\n },\n {\n x: 1050.6089983195284,\n y: 1095.2490678371344,\n },\n {\n x: 1050.6089983195284,\n y: 1136.225321719521,\n },\n {\n x: 222.4288912585182,\n y: 1136.225321719521,\n },\n ],\n boundingBox: {\n left: 222.4288912585182,\n top: 1095.2490678371344,\n right: 1050.6089983195284,\n bottom: 1136.225321719521,\n },\n },\n {\n id: "block_10_HbnFiy",\n type: "text",\n content:\n "Acknowledgements We are grateful to Nal Kalchbrenner and Stephan Gouws for their fruitful comments, corrections and inspiration.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Text",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.996,\n },\n polygon: [\n {\n x: 223.74068072242457,\n y: 1165.530171673997,\n },\n {\n x: 1049.9162882783987,\n y: 1165.530171673997,\n },\n {\n x: 1049.9162882783987,\n y: 1209.6124608319503,\n },\n {\n x: 223.74068072242457,\n y: 1209.6124608319503,\n },\n ],\n boundingBox: {\n left: 223.74068072242457,\n top: 1165.530171673997,\n right: 1049.9162882783987,\n bottom: 1209.6124608319503,\n },\n },\n {\n id: "block_10_FqHFgA",\n type: "section_heading",\n content: "### References",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Subheading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.3401158465086,\n y: 1243.4205694557131,\n },\n {\n x: 340.41243086766156,\n y: 1243.4205694557131,\n },\n {\n x: 340.41243086766156,\n y: 1263.1433630921786,\n },\n {\n x: 224.3401158465086,\n y: 1263.1433630921786,\n },\n ],\n boundingBox: {\n left: 224.3401158465086,\n top: 1243.4205694557131,\n right: 340.41243086766156,\n bottom: 1263.1433630921786,\n },\n },\n {\n id: "block_10_PnBCYC",\n type: "text",\n content:\n "[1] Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint arXiv: 1607.06450, 2016.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 234.62492392881074,\n y: 1281.5349446346884,\n },\n {\n x: 1049.520940850251,\n y: 1281.5349446346884,\n },\n {\n x: 1049.520940850251,\n y: 1323.6168167573169,\n },\n {\n x: 234.62492392881074,\n y: 1323.6168167573169,\n },\n ],\n boundingBox: {\n left: 234.62492392881074,\n top: 1281.5349446346884,\n right: 1049.520940850251,\n bottom: 1323.6168167573169,\n },\n },\n {\n id: "block_10_sUAYRJ",\n type: "text",\n content:\n "[2] Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly learning to align and translate. CoRR, abs/1409.0473, 2014.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 233.7351792050104,\n y: 1342.1247941210754,\n },\n {\n x: 1048.5688313950586,\n y: 1342.1247941210754,\n },\n {\n x: 1048.5688313950586,\n y: 1385.6842018070079,\n },\n {\n x: 233.7351792050104,\n y: 1385.6842018070079,\n },\n ],\n boundingBox: {\n left: 233.7351792050104,\n top: 1342.1247941210754,\n right: 1048.5688313950586,\n bottom: 1385.6842018070079,\n },\n },\n {\n id: "block_10_cYNyCb",\n type: "text",\n content:\n "[3] Denny Britz, Anna Goldie, Minh-Thang Luong, and Quoc V. Le. Massive exploration of neural machine translation architectures. CoRR, abs/1703.03906, 2017.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.914,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 234.47555625525703,\n y: 1401.96474766552,\n },\n {\n x: 1050.0915248898693,\n y: 1401.96474766552,\n },\n {\n x: 1050.0915248898693,\n y: 1443.4021335687853,\n },\n {\n x: 234.47555625525703,\n y: 1443.4021335687853,\n },\n ],\n boundingBox: {\n left: 234.47555625525703,\n top: 1401.96474766552,\n right: 1050.0915248898693,\n bottom: 1443.4021335687853,\n },\n },\n {\n id: "block_10_akeHB3",\n type: "text",\n content:\n "[4] Jianpeng Cheng, Li Dong, and Mirella Lapata. Long short-term memory-networks for machine reading. arXiv preprint arXiv: 1601.06733, 2016.",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.91,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 235.1935672063897,\n y: 1461.8473196961825,\n },\n {\n x: 1049.3358584216041,\n y: 1461.8473196961825,\n },\n {\n x: 1049.3358584216041,\n y: 1505.7106445427228,\n },\n {\n x: 235.1935672063897,\n y: 1505.7106445427228,\n },\n ],\n boundingBox: {\n left: 235.1935672063897,\n top: 1461.8473196961825,\n right: 1049.3358584216041,\n bottom: 1505.7106445427228,\n },\n },\n {\n id: "block_10_sJYSgt",\n type: "page_number",\n content: "10",\n metadata: {\n page: {\n number: 10,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.999,\n avgOcrConfidence: 0.999,\n },\n polygon: [\n {\n x: 628.4902252420022,\n y: 1547.7831405983832,\n },\n {\n x: 647.7796484954166,\n y: 1547.7831405983832,\n },\n {\n x: 647.7796484954166,\n y: 1563.3856736950409,\n },\n {\n x: 628.4902252420022,\n y: 1563.3856736950409,\n },\n ],\n boundingBox: {\n left: 628.4902252420022,\n top: 1547.7831405983832,\n right: 647.7796484954166,\n bottom: 1563.3856736950409,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_11_VBbBwR",\n type: "text",\n content:\n "[5] Kyunghyun Cho, Bart van Merrienboer, Caglar Gulcehre, Fethi Bougares, Holger Schwenk, and Yoshua Bengio. Learning phrase representations using rnn encoder-decoder for statistical machine translation. CoRR, abs/1406.1078, 2014.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.932,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 234.95565818174043,\n y: 155.04768656967278,\n },\n {\n x: 1051.617910566121,\n y: 155.04768656967278,\n },\n {\n x: 1051.617910566121,\n y: 219.22101676195186,\n },\n {\n x: 234.95565818174043,\n y: 219.22101676195186,\n },\n ],\n boundingBox: {\n left: 234.95565818174043,\n top: 155.04768656967278,\n right: 1051.617910566121,\n bottom: 219.22101676195186,\n },\n },\n {\n id: "block_11_fZULb0",\n type: "text",\n content:\n "[6] Francois Chollet. Xception: Deep learning with depthwise separable convolutions. arXiv preprint arXiv: 1610.02357, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.916,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 234.37082610861228,\n y: 242.1581676597882,\n },\n {\n x: 1050.1136779785156,\n y: 242.1581676597882,\n },\n {\n x: 1050.1136779785156,\n y: 284.96119192309845,\n },\n {\n x: 234.37082610861228,\n y: 284.96119192309845,\n },\n ],\n boundingBox: {\n left: 234.37082610861228,\n top: 242.1581676597882,\n right: 1050.1136779785156,\n bottom: 284.96119192309845,\n },\n },\n {\n id: "block_11_KQxaZG",\n type: "text",\n content:\n "[7] Junyoung Chung, \\u00c7aglar G\\u00fcl\\u00e7ehre, Kyunghyun Cho, and Yoshua Bengio. Empirical evaluation of gated recurrent neural networks on sequence modeling. CoRR, abs/1412.3555, 2014.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.937,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 234.59709056102446,\n y: 305.8525607747243,\n },\n {\n x: 1050.252182118214,\n y: 305.8525607747243,\n },\n {\n x: 1050.252182118214,\n y: 348.70033444856347,\n },\n {\n x: 234.59709056102446,\n y: 348.70033444856347,\n },\n ],\n boundingBox: {\n left: 234.59709056102446,\n top: 305.8525607747243,\n right: 1050.252182118214,\n bottom: 348.70033444856347,\n },\n },\n {\n id: "block_11_lSxX1m",\n type: "text",\n content:\n "[8] Chris Dyer, Adhiguna Kuncoro, Miguel Ballesteros, and Noah A. Smith. Recurrent neural network grammars. In Proc. of NAACL, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.92,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 234.54393261540545,\n y: 369.88837531814,\n },\n {\n x: 1049.7648141679972,\n y: 369.88837531814,\n },\n {\n x: 1049.7648141679972,\n y: 412.63161531606113,\n },\n {\n x: 234.54393261540545,\n y: 412.63161531606113,\n },\n ],\n boundingBox: {\n left: 234.54393261540545,\n top: 369.88837531814,\n right: 1049.7648141679972,\n bottom: 412.63161531606113,\n },\n },\n {\n id: "block_11_3YLXoz",\n type: "text",\n content:\n "[9] Jonas Gehring, Michael Auli, David Grangier, Denis Yarats, and Yann N. Dauphin. Convolu- tional sequence to sequence learning. arXiv preprint arXiv: 1705.03122v2, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.927,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 233.81299902922916,\n y: 434.3302966813395,\n },\n {\n x: 1052.8067929901345,\n y: 434.3302966813395,\n },\n {\n x: 1052.8067929901345,\n y: 476.945989020785,\n },\n {\n x: 233.81299902922916,\n y: 476.945989020785,\n },\n ],\n boundingBox: {\n left: 233.81299902922916,\n top: 434.3302966813395,\n right: 1052.8067929901345,\n bottom: 476.945989020785,\n },\n },\n {\n id: "block_11_OkxRaO",\n type: "text",\n content:\n "[10] Alex Graves. Generating sequences with recurrent neural networks. arXiv preprint arXiv: 1308.0850, 2013.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.904,\n avgOcrConfidence: 0.986,\n },\n polygon: [\n {\n x: 224.38643378932983,\n y: 498.1091927836712,\n },\n {\n x: 1050.5877919440723,\n y: 498.1091927836712,\n },\n {\n x: 1050.5877919440723,\n y: 539.0395607625632,\n },\n {\n x: 224.38643378932983,\n y: 539.0395607625632,\n },\n ],\n boundingBox: {\n left: 224.38643378932983,\n top: 498.1091927836712,\n right: 1050.5877919440723,\n bottom: 539.0395607625632,\n },\n },\n {\n id: "block_11_RVnHcs",\n type: "text",\n content:\n "[11] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for im- age recognition. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 770-778, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.919,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.3475475450502,\n y: 561.9494121522832,\n },\n {\n x: 1053.1976908662893,\n y: 561.9494121522832,\n },\n {\n x: 1053.1976908662893,\n y: 627.2271530610278,\n },\n {\n x: 224.3475475450502,\n y: 627.2271530610278,\n },\n ],\n boundingBox: {\n left: 224.3475475450502,\n top: 561.9494121522832,\n right: 1053.1976908662893,\n bottom: 627.2271530610278,\n },\n },\n {\n id: "block_11_s96TQd",\n type: "text",\n content:\n "[12] Sepp Hochreiter, Yoshua Bengio, Paolo Frasconi, and J\\u00fcrgen Schmidhuber. Gradient flow in recurrent nets: the difficulty of learning long-term dependencies, 2001.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.892,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 224.27874516396628,\n y: 647.9830188034173,\n },\n {\n x: 1048.8635432111087,\n y: 647.9830188034173,\n },\n {\n x: 1048.8635432111087,\n y: 692.1669293740639,\n },\n {\n x: 224.27874516396628,\n y: 692.1669293740639,\n },\n ],\n boundingBox: {\n left: 224.27874516396628,\n top: 647.9830188034173,\n right: 1048.8635432111087,\n bottom: 692.1669293740639,\n },\n },\n {\n id: "block_11_bKrlBK",\n type: "text",\n content:\n "[13] Sepp Hochreiter and J\\u00fcrgen Schmidhuber. Long short-term memory. Neural computation, 9(8):1735-1780, 1997.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.903,\n avgOcrConfidence: 0.984,\n },\n polygon: [\n {\n x: 224.36335765532334,\n y: 712.3709330738038,\n },\n {\n x: 1051.7104044447851,\n y: 712.3709330738038,\n },\n {\n x: 1051.7104044447851,\n y: 754.2910917181719,\n },\n {\n x: 224.36335765532334,\n y: 754.2910917181719,\n },\n ],\n boundingBox: {\n left: 224.36335765532334,\n top: 712.3709330738038,\n right: 1051.7104044447851,\n bottom: 754.2910917181719,\n },\n },\n {\n id: "block_11_c3sQ7S",\n type: "text",\n content:\n "[14] Zhongqiang Huang and Mary Harper. Self-training PCFG grammars with latent annotations across languages. In Proceedings of the 2009 Conference on Empirical Methods in Natural Language Processing, pages 832-841. ACL, August 2009.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.70277800177138,\n y: 777.0990849258308,\n },\n {\n x: 1050.1772024335653,\n y: 777.0990849258308,\n },\n {\n x: 1050.1772024335653,\n y: 842.7015786995565,\n },\n {\n x: 224.70277800177138,\n y: 842.7015786995565,\n },\n ],\n boundingBox: {\n left: 224.70277800177138,\n top: 777.0990849258308,\n right: 1050.1772024335653,\n bottom: 842.7015786995565,\n },\n },\n {\n id: "block_11_HmSxMA",\n type: "text",\n content:\n "[15] Rafal Jozefowicz, Oriol Vinyals, Mike Schuster, Noam Shazeer, and Yonghui Wu. Exploring the limits of language modeling. arXiv preprint arXiv: 1602.02410, 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.906,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 223.96287430811972,\n y: 863.015632801486,\n },\n {\n x: 1049.822942357864,\n y: 863.015632801486,\n },\n {\n x: 1049.822942357864,\n y: 907.0369301702743,\n },\n {\n x: 223.96287430811972,\n y: 907.0369301702743,\n },\n ],\n boundingBox: {\n left: 223.96287430811972,\n top: 863.015632801486,\n right: 1049.822942357864,\n bottom: 907.0369301702743,\n },\n },\n {\n id: "block_11_XlCObz",\n type: "text",\n content:\n "[16] \\u0141ukasz Kaiser and Samy Bengio. Can active memory replace attention? In Advances in Neural Information Processing Systems, (NIPS), 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.902,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.17545875493627,\n y: 927.1137413655905,\n },\n {\n x: 1050.2528448174469,\n y: 927.1137413655905,\n },\n {\n x: 1050.2528448174469,\n y: 970.5487977795134,\n },\n {\n x: 224.17545875493627,\n y: 970.5487977795134,\n },\n ],\n boundingBox: {\n left: 224.17545875493627,\n top: 927.1137413655905,\n right: 1050.2528448174469,\n bottom: 970.5487977795134,\n },\n },\n {\n id: "block_11_48mMcn",\n type: "text",\n content:\n "[17] \\u0141ukasz Kaiser and Ilya Sutskever. Neural GPUs learn algorithms. In International Conference on Learning Representations (ICLR), 2016.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.903,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 224.42198286961465,\n y: 991.1752927392946,\n },\n {\n x: 1049.7810976348653,\n y: 991.1752927392946,\n },\n {\n x: 1049.7810976348653,\n y: 1034.8329123590227,\n },\n {\n x: 224.42198286961465,\n y: 1034.8329123590227,\n },\n ],\n boundingBox: {\n left: 224.42198286961465,\n top: 991.1752927392946,\n right: 1049.7810976348653,\n bottom: 1034.8329123590227,\n },\n },\n {\n id: "block_11_lBImir",\n type: "text",\n content:\n "[18] Nal Kalchbrenner, Lasse Espeholt, Karen Simonyan, Aaron van den Oord, Alex Graves, and Ko- ray Kavukcuoglu. Neural machine translation in linear time. arXiv preprint arXiv: 1610.10099v2, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.934,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.23202486803933,\n y: 1055.1385374714557,\n },\n {\n x: 1052.4190192675069,\n y: 1055.1385374714557,\n },\n {\n x: 1052.4190192675069,\n y: 1117.975328259002,\n },\n {\n x: 224.23202486803933,\n y: 1117.975328259002,\n },\n ],\n boundingBox: {\n left: 224.23202486803933,\n top: 1055.1385374714557,\n right: 1052.4190192675069,\n bottom: 1117.975328259002,\n },\n },\n {\n id: "block_11_Y0ddKF",\n type: "text",\n content:\n "[19] Yoon Kim, Carl Denton, Luong Hoang, and Alexander M. Rush. Structured attention networks. In International Conference on Learning Representations, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.974,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.29036606837366,\n y: 1142.1438929622334,\n },\n {\n x: 1052.7023705252766,\n y: 1142.1438929622334,\n },\n {\n x: 1052.7023705252766,\n y: 1185.793178300212,\n },\n {\n x: 224.29036606837366,\n y: 1185.793178300212,\n },\n ],\n boundingBox: {\n left: 224.29036606837366,\n top: 1142.1438929622334,\n right: 1052.7023705252766,\n bottom: 1185.793178300212,\n },\n },\n {\n id: "block_11_nehypx",\n type: "text",\n content:\n "[20] Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In ICLR, 2015.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 223.92950266817192,\n y: 1205.8213097134928,\n },\n {\n x: 1052.7550077786411,\n y: 1205.8213097134928,\n },\n {\n x: 1052.7550077786411,\n y: 1227.2851158658366,\n },\n {\n x: 223.92950266817192,\n y: 1227.2851158658366,\n },\n ],\n boundingBox: {\n left: 223.92950266817192,\n top: 1205.8213097134928,\n right: 1052.7550077786411,\n bottom: 1227.2851158658366,\n },\n },\n {\n id: "block_11_af7MVz",\n type: "text",\n content:\n "[21] Oleksii Kuchaiev and Boris Ginsburg. Factorization tricks for LSTM networks. arXiv preprint arXiv: 1703.10722, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.925,\n avgOcrConfidence: 0.989,\n },\n polygon: [\n {\n x: 223.78512890669552,\n y: 1247.11833873548,\n },\n {\n x: 1050.4177622551465,\n y: 1247.11833873548,\n },\n {\n x: 1050.4177622551465,\n y: 1289.109575544085,\n },\n {\n x: 223.78512890669552,\n y: 1289.109575544085,\n },\n ],\n boundingBox: {\n left: 223.78512890669552,\n top: 1247.11833873548,\n right: 1050.4177622551465,\n bottom: 1289.109575544085,\n },\n },\n {\n id: "block_11_vnPlfZ",\n type: "text",\n content:\n "[22] Zhouhan Lin, Minwei Feng, Cicero Nogueira dos Santos, Mo Yu, Bing Xiang, Bowen Zhou, and Yoshua Bengio. A structured self-attentive sentence embedding. arXiv preprint arXiv: 1703.03130, 2017.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.74063338676507,\n y: 1311.0246641116034,\n },\n {\n x: 1050.2205618976677,\n y: 1311.0246641116034,\n },\n {\n x: 1050.2205618976677,\n y: 1375.8748468958345,\n },\n {\n x: 223.74063338676507,\n y: 1375.8748468958345,\n },\n ],\n boundingBox: {\n left: 223.74063338676507,\n top: 1311.0246641116034,\n right: 1050.2205618976677,\n bottom: 1375.8748468958345,\n },\n },\n {\n id: "block_11_g0SHxO",\n type: "text",\n content:\n "[23] Minh-Thang Luong, Quoc V. Le, Ilya Sutskever, Oriol Vinyals, and Lukasz Kaiser. Multi-task sequence to sequence learning. arXiv preprint arXiv: 1511.06114, 2015.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.908,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.355428932357,\n y: 1397.7982697451025,\n },\n {\n x: 1050.4997476174015,\n y: 1397.7982697451025,\n },\n {\n x: 1050.4997476174015,\n y: 1441.9434448471643,\n },\n {\n x: 224.355428932357,\n y: 1441.9434448471643,\n },\n ],\n boundingBox: {\n left: 224.355428932357,\n top: 1397.7982697451025,\n right: 1050.4997476174015,\n bottom: 1441.9434448471643,\n },\n },\n {\n id: "block_11_gDtqYI",\n type: "text",\n content:\n "[24] Minh-Thang Luong, Hieu Pham, and Christopher D Manning. Effective approaches to attention- based neural machine translation. arXiv preprint arXiv: 1508.04025, 2015.",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.927,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 224.7064228475529,\n y: 1461.612349775501,\n },\n {\n x: 1052.9802308465444,\n y: 1461.612349775501,\n },\n {\n x: 1052.9802308465444,\n y: 1506.2439438669305,\n },\n {\n x: 224.7064228475529,\n y: 1506.2439438669305,\n },\n ],\n boundingBox: {\n left: 224.7064228475529,\n top: 1461.612349775501,\n right: 1052.9802308465444,\n bottom: 1506.2439438669305,\n },\n },\n {\n id: "block_11_JWTkzE",\n type: "page_number",\n content: "11",\n metadata: {\n page: {\n number: 11,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.995,\n avgOcrConfidence: 0.995,\n },\n polygon: [\n {\n x: 629.039650241824,\n y: 1547.854550239735,\n },\n {\n x: 645.38100862155,\n y: 1547.854550239735,\n },\n {\n x: 645.38100862155,\n y: 1563.4467601919532,\n },\n {\n x: 629.039650241824,\n y: 1563.4467601919532,\n },\n ],\n boundingBox: {\n left: 629.039650241824,\n top: 1547.854550239735,\n right: 645.38100862155,\n bottom: 1563.4467601919532,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_12_TQ4Lbe",\n type: "text",\n content:\n "[25] Mitchell P Marcus, Mary Ann Marcinkiewicz, and Beatrice Santorini. Building a large annotated corpus of english: The penn treebank. Computational linguistics, 19(2):313-330, 1993.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.913,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.94512343580706,\n y: 154.85743054411464,\n },\n {\n x: 1050.2930801280222,\n y: 154.85743054411464,\n },\n {\n x: 1050.2930801280222,\n y: 198.76930494953817,\n },\n {\n x: 223.94512343580706,\n y: 198.76930494953817,\n },\n ],\n boundingBox: {\n left: 223.94512343580706,\n top: 154.85743054411464,\n right: 1050.2930801280222,\n bottom: 198.76930494953817,\n },\n },\n {\n id: "block_12_LvCkff",\n type: "text",\n content:\n "[26] David McClosky, Eugene Charniak, and Mark Johnson. Effective self-training for parsing. In Proceedings of the Human Language Technology Conference of the NAACL, Main Conference, pages 152-159. ACL, June 2006.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.907,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.21323261121762,\n y: 226.782506971431,\n },\n {\n x: 1051.9384676522582,\n y: 226.782506971431,\n },\n {\n x: 1051.9384676522582,\n y: 292.8687442406676,\n },\n {\n x: 224.21323261121762,\n y: 292.8687442406676,\n },\n ],\n boundingBox: {\n left: 224.21323261121762,\n top: 226.782506971431,\n right: 1051.9384676522582,\n bottom: 292.8687442406676,\n },\n },\n {\n id: "block_12_Rm8AFL",\n type: "text",\n content:\n "[27] Ankur Parikh, Oscar T\\u00e4ckstr\\u00f6m, Dipanjan Das, and Jakob Uszkoreit. A decomposable attention model. In Empirical Methods in Natural Language Processing, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.916,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.08847948060418,\n y: 321.2656073462694,\n },\n {\n x: 1048.8436622341185,\n y: 321.2656073462694,\n },\n {\n x: 1048.8436622341185,\n y: 364.85913349811295,\n },\n {\n x: 224.08847948060418,\n y: 364.85913349811295,\n },\n ],\n boundingBox: {\n left: 224.08847948060418,\n top: 321.2656073462694,\n right: 1048.8436622341185,\n bottom: 364.85913349811295,\n },\n },\n {\n id: "block_12_cqas9e",\n type: "text",\n content:\n "[28] Romain Paulus, Caiming Xiong, and Richard Socher. A deep reinforced model for abstractive summarization. arXiv preprint arXiv: 1705.04304, 2017.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.67392691730583,\n y: 392.7383714116606,\n },\n {\n x: 1049.3349117084142,\n y: 392.7383714116606,\n },\n {\n x: 1049.3349117084142,\n y: 435.42904860991285,\n },\n {\n x: 224.67392691730583,\n y: 435.42904860991285,\n },\n ],\n boundingBox: {\n left: 224.67392691730583,\n top: 392.7383714116606,\n right: 1049.3349117084142,\n bottom: 435.42904860991285,\n },\n },\n {\n id: "block_12_hfa5dB",\n type: "text",\n content:\n "[29] Slav Petrov, Leon Barrett, Romain Thibaux, and Dan Klein. Learning accurate, compact, and interpretable tree annotation. In Proceedings of the 21st International Conference on Computational Linguistics and 44th Annual Meeting of the ACL, pages 433-440. ACL, July 2006.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.899,\n avgOcrConfidence: 0.99,\n },\n polygon: [\n {\n x: 223.91392923619625,\n y: 463.67279296530813,\n },\n {\n x: 1051.5214404920591,\n y: 463.67279296530813,\n },\n {\n x: 1051.5214404920591,\n y: 549.7230681799408,\n },\n {\n x: 223.91392923619625,\n y: 549.7230681799408,\n },\n ],\n boundingBox: {\n left: 223.91392923619625,\n top: 463.67279296530813,\n right: 1051.5214404920591,\n bottom: 549.7230681799408,\n },\n },\n {\n id: "block_12_H2k7w4",\n type: "text",\n content:\n "[30] Ofir Press and Lior Wolf. Using the output embedding to improve language models. arXiv preprint arXiv: 1608.05859, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.898,\n avgOcrConfidence: 0.987,\n },\n polygon: [\n {\n x: 224.29183347381814,\n y: 581.8894180068396,\n },\n {\n x: 1049.7876299558764,\n y: 581.8894180068396,\n },\n {\n x: 1049.7876299558764,\n y: 624.918793785841,\n },\n {\n x: 224.29183347381814,\n y: 624.918793785841,\n },\n ],\n boundingBox: {\n left: 224.29183347381814,\n top: 581.8894180068396,\n right: 1049.7876299558764,\n bottom: 624.918793785841,\n },\n },\n {\n id: "block_12_UrZIEK",\n type: "text",\n content:\n "[31] Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words with subword units. arXiv preprint arXiv: 1508.07909, 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.925,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.35140540129947,\n y: 653.3260510666926,\n },\n {\n x: 1049.4855337769445,\n y: 653.3260510666926,\n },\n {\n x: 1049.4855337769445,\n y: 696.2955715494944,\n },\n {\n x: 224.35140540129947,\n y: 696.2955715494944,\n },\n ],\n boundingBox: {\n left: 224.35140540129947,\n top: 653.3260510666926,\n right: 1049.4855337769445,\n bottom: 696.2955715494944,\n },\n },\n {\n id: "block_12_IIwlxZ",\n type: "text",\n content:\n "[32] Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz, Andy Davis, Quoc Le, Geoffrey Hinton, and Jeff Dean. Outrageously large neural networks: The sparsely-gated mixture-of-experts layer. arXiv preprint arXiv: 1701.06538, 2017.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.88,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.15238262092979,\n y: 724.7319041087216,\n },\n {\n x: 1051.274348349467,\n y: 724.7319041087216,\n },\n {\n x: 1051.274348349467,\n y: 791.0497254966793,\n },\n {\n x: 224.15238262092979,\n y: 791.0497254966793,\n },\n ],\n boundingBox: {\n left: 224.15238262092979,\n top: 724.7319041087216,\n right: 1051.274348349467,\n bottom: 791.0497254966793,\n },\n },\n {\n id: "block_12_pGLzhM",\n type: "text",\n content:\n "[33] Nitish Srivastava, Geoffrey E Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdi- nov. Dropout: a simple way to prevent neural networks from overfitting. Journal of Machine Learning Research, 15(1):1929-1958, 2014.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.938,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 224.4417928431156,\n y: 819.0001126052741,\n },\n {\n x: 1053.3042907714844,\n y: 819.0001126052741,\n },\n {\n x: 1053.3042907714844,\n y: 885.2761205228649,\n },\n {\n x: 224.4417928431156,\n y: 885.2761205228649,\n },\n ],\n boundingBox: {\n left: 224.4417928431156,\n top: 819.0001126052741,\n right: 1053.3042907714844,\n bottom: 885.2761205228649,\n },\n },\n {\n id: "block_12_Bz8MfK",\n type: "text",\n content:\n "[34] Sainbayar Sukhbaatar, Arthur Szlam, Jason Weston, and Rob Fergus. End-to-end memory networks. In C. Cortes, N. D. Lawrence, D. D. Lee, M. Sugiyama, and R. Garnett, editors, Advances in Neural Information Processing Systems 28, pages 2440-2448. Curran Associates, Inc., 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.897,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.0948934624665,\n y: 913.8373252467105,\n },\n {\n x: 1051.823347328353,\n y: 913.8373252467105,\n },\n {\n x: 1051.823347328353,\n y: 1000.8878563328793,\n },\n {\n x: 224.0948934624665,\n y: 1000.8878563328793,\n },\n ],\n boundingBox: {\n left: 224.0948934624665,\n top: 913.8373252467105,\n right: 1051.823347328353,\n bottom: 1000.8878563328793,\n },\n },\n {\n id: "block_12_m0nnSr",\n type: "text",\n content:\n "[35] Ilya Sutskever, Oriol Vinyals, and Quoc VV Le. Sequence to sequence learning with neural networks. In Advances in Neural Information Processing Systems, pages 3104-3112, 2014.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.899,\n avgOcrConfidence: 0.988,\n },\n polygon: [\n {\n x: 224.52872478178818,\n y: 1030.965426796361,\n },\n {\n x: 1050.1110271815835,\n y: 1030.965426796361,\n },\n {\n x: 1050.1110271815835,\n y: 1074.9609636579241,\n },\n {\n x: 224.52872478178818,\n y: 1074.9609636579241,\n },\n ],\n boundingBox: {\n left: 224.52872478178818,\n top: 1030.965426796361,\n right: 1050.1110271815835,\n bottom: 1074.9609636579241,\n },\n },\n {\n id: "block_12_C1nzdD",\n type: "text",\n content:\n "[36] Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, and Zbigniew Wojna. Rethinking the inception architecture for computer vision. CoRR, abs/1512.00567, 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.939,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.60145602261062,\n y: 1102.9526906981505,\n },\n {\n x: 1051.9790816481095,\n y: 1102.9526906981505,\n },\n {\n x: 1051.9790816481095,\n y: 1146.15116715969,\n },\n {\n x: 224.60145602261062,\n y: 1146.15116715969,\n },\n ],\n boundingBox: {\n left: 224.60145602261062,\n top: 1102.9526906981505,\n right: 1051.9790816481095,\n bottom: 1146.15116715969,\n },\n },\n {\n id: "block_12_smJ629",\n type: "text",\n content:\n "[37] Vinyals & Kaiser, Koo, Petrov, Sutskever, and Hinton. Grammar as a foreign language. In Advances in Neural Information Processing Systems, 2015.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.912,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.70363004364236,\n y: 1173.716330506748,\n },\n {\n x: 1049.93891472364,\n y: 1173.716330506748,\n },\n {\n x: 1049.93891472364,\n y: 1218.0808487512115,\n },\n {\n x: 224.70363004364236,\n y: 1218.0808487512115,\n },\n ],\n boundingBox: {\n left: 224.70363004364236,\n top: 1173.716330506748,\n right: 1049.93891472364,\n bottom: 1218.0808487512115,\n },\n },\n {\n id: "block_12_oKrqzS",\n type: "text",\n content:\n "[38] Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. Google\'s neural machine translation system: Bridging the gap between human and machine translation. arXiv preprint arXiv: 1609.08144, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.935,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.222865417926,\n y: 1246.0137622804568,\n },\n {\n x: 1050.4285547855127,\n y: 1246.0137622804568,\n },\n {\n x: 1050.4285547855127,\n y: 1332.3901636224045,\n },\n {\n x: 224.222865417926,\n y: 1332.3901636224045,\n },\n ],\n boundingBox: {\n left: 224.222865417926,\n top: 1246.0137622804568,\n right: 1050.4285547855127,\n bottom: 1332.3901636224045,\n },\n },\n {\n id: "block_12_5hQUgX",\n type: "text",\n content:\n "[39] Jie Zhou, Ying Cao, Xuguang Wang, Peng Li, and Wei Xu. Deep recurrent models with fast-forward connections for neural machine translation. CoRR, abs/1606.04199, 2016.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.977,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 224.40534438530025,\n y: 1362.7727877394598,\n },\n {\n x: 1049.6643678985372,\n y: 1362.7727877394598,\n },\n {\n x: 1049.6643678985372,\n y: 1404.796982844073,\n },\n {\n x: 224.40534438530025,\n y: 1404.796982844073,\n },\n ],\n boundingBox: {\n left: 224.40534438530025,\n top: 1362.7727877394598,\n right: 1049.6643678985372,\n bottom: 1404.796982844073,\n },\n },\n {\n id: "block_12_7qyMnf",\n type: "text",\n content:\n "[40] Muhua Zhu, Yue Zhang, Wenliang Chen, Min Zhang, and Jingbo Zhu. Fast and accurate shift-reduce constituent parsing. In Proceedings of the 51st Annual Meeting of the ACL (Volume 1: Long Papers), pages 434-443. ACL, August 2013.",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "List Item",\n minOcrConfidence: 0.905,\n avgOcrConfidence: 0.991,\n },\n polygon: [\n {\n x: 224.04902520841057,\n y: 1434.5126750056904,\n },\n {\n x: 1049.9945814592124,\n y: 1434.5126750056904,\n },\n {\n x: 1049.9945814592124,\n y: 1501.148572362455,\n },\n {\n x: 224.04902520841057,\n y: 1501.148572362455,\n },\n ],\n boundingBox: {\n left: 224.04902520841057,\n top: 1434.5126750056904,\n right: 1049.9945814592124,\n bottom: 1501.148572362455,\n },\n },\n {\n id: "block_12_6o6JUd",\n type: "page_number",\n content: "12",\n metadata: {\n page: {\n number: 12,\n width: 1275,\n height: 1651,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.998,\n avgOcrConfidence: 0.998,\n },\n polygon: [\n {\n x: 628.997000812614,\n y: 1547.789391309695,\n },\n {\n x: 647.0427269483133,\n y: 1547.789391309695,\n },\n {\n x: 647.0427269483133,\n y: 1563.398364533159,\n },\n {\n x: 628.997000812614,\n y: 1563.398364533159,\n },\n ],\n boundingBox: {\n left: 628.997000812614,\n top: 1547.789391309695,\n right: 647.0427269483133,\n bottom: 1563.398364533159,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_13_KlKk5h",\n type: "page_number",\n content: "13",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.999,\n avgOcrConfidence: 0.999,\n },\n polygon: [\n {\n x: 103.29433033878627,\n y: 628.7723457726248,\n },\n {\n x: 103.29433033878627,\n y: 646.9001519418981,\n },\n {\n x: 87.59273293860883,\n y: 646.9001519418981,\n },\n {\n x: 87.59273293860883,\n y: 628.7723457726248,\n },\n ],\n boundingBox: {\n left: 87.59273293860883,\n top: 628.7723457726248,\n right: 103.29433033878627,\n bottom: 646.9001519418981,\n },\n },\n {\n id: "block_13_PkaOm5",\n type: "text",\n content:\n "the word \'making\'. Different colors represent different heads. Best viewed in color. the verb \'making\', completing the phrase \'making ... more difficult\'. Attentions here shown only for encoder self-attention in layer 5 of 6. Many of the attention heads attend to a distant dependency of Figure 3: An example of the attention mechanism following long-distance dependencies in the",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.937,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 999.8870322148603,\n y: 224.33585563715354,\n },\n {\n x: 999.8870322148603,\n y: 1052.0067256732577,\n },\n {\n x: 911.037953656419,\n y: 1052.0067256732577,\n },\n {\n x: 911.037953656419,\n y: 224.33585563715354,\n },\n ],\n boundingBox: {\n left: 911.037953656419,\n top: 224.33585563715354,\n right: 999.8870322148603,\n bottom: 1052.0067256732577,\n },\n },\n {\n id: "block_13_xamkHQ",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nIt It is is in in this this spirit spirit that that a a majority majority of of American American governments governments have have passed passed new new laws laws since since 2009 2009 making making the the registration registration or or voting voting process process more more difficult difficult\\n\\n. . <EOS> <EOS> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad> <pad>\\n<caption>Diagram showing attention mechanism or word alignment between two identical sequences of text. The word \'making\' in the right column is highlighted in gray and acts as the target for connections from the left column. Connections originate from the words \'laws\', \'2009\', \'making\', \'more\', and \'difficult\' in the left column and point to \'making\' in the right column. The sequence of text is: \'It is in this spirit that a majority of American governments have passed new laws since 2009 making the registration or voting process more difficult. <EOS> <pad> <pad> <pad> <pad> <pad> <pad> <pad>\'</caption>\\n</figure>",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.717,\n avgOcrConfidence: 0.98,\n },\n polygon: [\n {\n x: 1444.0009233001479,\n y: 252.8656019781628,\n },\n {\n x: 1444.0009233001479,\n y: 1047.5539548553688,\n },\n {\n x: 1022.9538143416097,\n y: 1047.5539548553688,\n },\n {\n x: 1022.9538143416097,\n y: 252.8656019781628,\n },\n ],\n boundingBox: {\n left: 1022.9538143416097,\n top: 252.8656019781628,\n right: 1444.0009233001479,\n bottom: 1047.5539548553688,\n },\n },\n {\n id: "block_13_5eYqPZ",\n type: "heading",\n content: "# Attention Visualizations",\n metadata: {\n page: {\n number: 13,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Heading",\n minOcrConfidence: 0.992,\n avgOcrConfidence: 0.992,\n },\n polygon: [\n {\n x: 1498.6412794643775,\n y: 224.94428453654268,\n },\n {\n x: 1498.6412794643775,\n y: 480.8453803514912,\n },\n {\n x: 1479.199057528847,\n y: 480.8453803514912,\n },\n {\n x: 1479.199057528847,\n y: 224.94428453654268,\n },\n ],\n boundingBox: {\n left: 1479.199057528847,\n top: 224.94428453654268,\n right: 1498.6412794643775,\n bottom: 480.8453803514912,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_14_DaAuYi",\n type: "page_number",\n content: "14",\n metadata: {\n page: {\n number: 14,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.998,\n avgOcrConfidence: 0.998,\n },\n polygon: [\n {\n x: 103.12243577770732,\n y: 628.7327731612825,\n },\n {\n x: 103.12243577770732,\n y: 647.0026336447166,\n },\n {\n x: 87.74237117910752,\n y: 647.0026336447166,\n },\n {\n x: 87.74237117910752,\n y: 628.7327731612825,\n },\n ],\n boundingBox: {\n left: 87.74237117910752,\n top: 628.7327731612825,\n right: 103.12243577770732,\n bottom: 647.0026336447166,\n },\n },\n {\n id: "block_14_VDKMys",\n type: "text",\n content:\n "and 6. Note that the attentions are very sharp for this word. Full attentions for head 5. Bottom: Isolated attentions from just the word \'its\' for attention heads 5 Figure 4: Two attention heads, also in layer 5 of 6, apparently involved in anaphora resolution. Top:",\n metadata: {\n page: {\n number: 14,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.972,\n avgOcrConfidence: 0.993,\n },\n polygon: [\n {\n x: 370.4634644357782,\n y: 224.1528559775248,\n },\n {\n x: 370.4634644357782,\n y: 1051.3102287793681,\n },\n {\n x: 303.81733864232115,\n y: 1051.3102287793681,\n },\n {\n x: 303.81733864232115,\n y: 224.1528559775248,\n },\n ],\n boundingBox: {\n left: 303.81733864232115,\n top: 224.1528559775248,\n right: 370.4634644357782,\n bottom: 1051.3102287793681,\n },\n },\n {\n id: "block_14_QRz2LE",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nThe The The The Law Law Law Law will will will will never never never never be be be be perfect perfect perfect perfect , , , , but but but but its its its its application application application application should should should should be be be be just just just just - - - - this this this this is is is is what what what what we we we we are are are are missing missing missing missing , , , , in in in in my my my my opinion opinion opinion opinion . . . . <EOS> <EOS> <EOS> <EOS> <pad> <pad> <pad> <pad>\\n<caption>Attention weight visualization diagram showing alignment between two sequences of text tokens. The diagram consists of three columns of text, with lines connecting tokens between the columns to represent attention strength. Thicker, more opaque lines indicate higher attention weights. The text sequence is: \'The\', \'Law\', \'will\', \'never\', \'be\', \'perfect\', \',\', \'but\', \'its\', \'application\', \'should\', \'be\', \'just\', \'-\', \'this\', \'is\', \'what\', \'we\', \'are\', \'missing\', \',\', \'in\', \'my\', \'opinion\', \'.\', \'<EOS>\', \'<pad>\'. Specific highlights are present: the word \'Law\' in the first column and \'its\' in the second column are highlighted with a purple/grey background, and lines connect these highlighted tokens to corresponding tokens in the third column.</caption>\\n</figure>",\n metadata: {\n page: {\n number: 14,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.379,\n avgOcrConfidence: 0.963,\n },\n polygon: [\n {\n x: 1294.7974623916741,\n y: 255.12043611846704,\n },\n {\n x: 1294.7974623916741,\n y: 1044.444475382784,\n },\n {\n x: 388.9633916410289,\n y: 1044.444475382784,\n },\n {\n x: 388.9633916410289,\n y: 255.12043611846704,\n },\n ],\n boundingBox: {\n left: 388.9633916410289,\n top: 255.12043611846704,\n right: 1294.7974623916741,\n bottom: 1044.444475382784,\n },\n },\n ],\n },\n {\n blocks: [\n {\n id: "block_15_pV91a2",\n type: "page_number",\n content: "15",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Page Number",\n minOcrConfidence: 0.998,\n avgOcrConfidence: 0.998,\n },\n polygon: [\n {\n x: 103.26014084206486,\n y: 628.7008215911197,\n },\n {\n x: 103.26014084206486,\n y: 647.1549124613296,\n },\n {\n x: 87.58487219559515,\n y: 647.1549124613296,\n },\n {\n x: 87.58487219559515,\n y: 628.7008215911197,\n },\n ],\n boundingBox: {\n left: 87.58487219559515,\n top: 628.7008215911197,\n right: 103.26014084206486,\n bottom: 647.1549124613296,\n },\n },\n {\n id: "block_15_2igWoi",\n type: "text",\n content:\n "at layer 5 of 6. The heads clearly learned to perform different tasks. sentence. We give two such examples above, from two different heads from the encoder self-attention Figure 5: Many of the attention heads exhibit behaviour that seems related to the structure of the",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Caption",\n minOcrConfidence: 0.976,\n avgOcrConfidence: 0.994,\n },\n polygon: [\n {\n x: 394.6980404387739,\n y: 223.74716570777616,\n },\n {\n x: 394.6980404387739,\n y: 1049.736980800211,\n },\n {\n x: 328.87227315113955,\n y: 1049.736980800211,\n },\n {\n x: 328.87227315113955,\n y: 223.74716570777616,\n },\n ],\n boundingBox: {\n left: 328.87227315113955,\n top: 223.74716570777616,\n right: 394.6980404387739,\n bottom: 1049.736980800211,\n },\n },\n {\n id: "block_15_OqCqJD",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nThe The Law Law will will never never be be perfect perfect , , but but its its application application should should be be just just - - this this is is what what we we are are missing missing , , in in my my opinion opinion\\n\\n. . <EOS> <EOS> <pad> <pad>\\n<caption>Attention weight visualization showing connections between two identical sequences of text: \'The Law will never be perfect , but its application should be just - this is what we are missing , in my opinion . <EOS> <pad>\'. The diagram uses lines of varying thickness and red color intensity to indicate the strength of attention between words in the left sequence and words in the right sequence. Stronger connections are represented by thicker, more opaque red lines, while weaker connections are represented by thinner, more transparent red lines.</caption>\\n</figure>",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.651,\n avgOcrConfidence: 0.969,\n },\n polygon: [\n {\n x: 810.314180990807,\n y: 253.4944325467966,\n },\n {\n x: 810.314180990807,\n y: 1035.3522419059364,\n },\n {\n x: 421.96601087527165,\n y: 1035.3522419059364,\n },\n {\n x: 421.96601087527165,\n y: 253.4944325467966,\n },\n ],\n boundingBox: {\n left: 421.96601087527165,\n top: 253.4944325467966,\n right: 810.314180990807,\n bottom: 1035.3522419059364,\n },\n },\n {\n id: "block_15_sK8Nre",\n type: "figure",\n content:\n "<figure type=\\"diagram\\">\\nThe The Law Law will will never never be be perfect perfect , , but but its its application application should should be be just just - - this this is is what what we we are are missing missing , , in in my my opinion opinion\\n\\n. . <EOS> <EOS> <pad> <pad>\\n<caption>Attention weight visualization diagram showing connections between two identical sequences of text: \'The\', \'Law\', \'will\', \'never\', \'be\', \'perfect\', \',\', \'but\', \'its\', \'application\', \'should\', \'be\', \'just\', \'-\', \'this\', \'is\', \'what\', \'we\', \'are\', \'missing\', \',\', \'in\', \'my\', \'opinion\', \'.\', \'<EOS>\', \'<pad>\'. The diagram displays lines connecting tokens from the left sequence to the right sequence, where line thickness and opacity represent the strength of the attention weight. Notable high-attention connections include: \'Law\' to \'Law\', \'application\' to \'application\', \'missing\' to \'missing\', \'opinion\' to \'opinion\', and \'<pad>\' to \'<pad>\'.</caption>\\n</figure>",\n metadata: {\n page: {\n number: 15,\n width: 1651,\n height: 1275,\n },\n layoutClass: "Picture/Figure/Image/Chart",\n minOcrConfidence: 0.6,\n avgOcrConfidence: 0.968,\n },\n polygon: [\n {\n x: 1255.9501913113702,\n y: 254.50874105857238,\n },\n {\n x: 1255.9501913113702,\n y: 1034.3072598868043,\n },\n {\n x: 882.2701913360366,\n y: 1034.3072598868043,\n },\n {\n x: 882.2701913360366,\n y: 254.50874105857238,\n },\n ],\n boundingBox: {\n left: 882.2701913360366,\n top: 254.50874105857238,\n right: 1255.9501913113702,\n bottom: 1034.3072598868043,\n },\n },\n ],\n },\n ],\n} satisfies ParsedOcrOutput\n\nfunction getBlockType(block: ParsedOcrBlock): OcrBlockType | undefined {\n if (block.type === "heading" || block.type === "section_heading") {\n return "heading"\n }\n\n if (block.type === "header") {\n return "header"\n }\n\n if (block.type === "footer") {\n return "footer"\n }\n\n if (block.type === "page_number") {\n return "page_number"\n }\n\n if (block.type === "figure" || block.type === "image") {\n return "figure"\n }\n\n if (block.type === "table") {\n return "table"\n }\n\n if (block.metadata.layoutClass === "List Item") {\n return "list"\n }\n\n if (block.type === "text") {\n return "paragraph"\n }\n}\n\nexport function getOcrBlocks(output: ParsedOcrOutput): OcrBlock[] {\n return output.chunks.flatMap((chunk) =>\n chunk.blocks.flatMap((block) => {\n const type = getBlockType(block)\n const { page } = block.metadata\n\n if (!type || page.width <= 0 || page.height <= 0) {\n return []\n }\n\n return {\n id: block.id,\n type,\n text: block.content,\n page: page.number,\n pageWidth: page.width,\n pageHeight: page.height,\n confidence:\n block.metadata.avgOcrConfidence ??\n block.metadata.minOcrConfidence ??\n 1,\n polygon: block.polygon,\n boundingBox: block.boundingBox,\n }\n })\n )\n}\n\nfunction getBoundingBox(block: OcrBlock): BoundingBox {\n if (block.boundingBox) {\n return block.boundingBox\n }\n\n const polygon = block.polygon ?? []\n const xValues = polygon.map((point) => point.x)\n const yValues = polygon.map((point) => point.y)\n const left = Math.min(...xValues)\n const right = Math.max(...xValues)\n const top = Math.min(...yValues)\n const bottom = Math.max(...yValues)\n\n return { left, top, right, bottom }\n}\n\nfunction getBlockCoordinateRotation(\n block: OcrBlock,\n pageSize?: { width: number; height: number }\n) {\n const blockIsLandscape = block.pageWidth > block.pageHeight\n\n if (!pageSize) return blockIsLandscape ? 1 : 0\n\n const pageIsLandscape = pageSize.width > pageSize.height\n\n if (blockIsLandscape && !pageIsLandscape) return 1\n if (!blockIsLandscape && pageIsLandscape) return 3\n\n return 0\n}\n\nfunction normalizeHighlightAreaForRotation(\n area: HighlightArea,\n rotation: number\n): HighlightArea {\n if (rotation === 1) {\n return {\n left: area.top,\n top: 100 - area.left - area.width,\n width: area.height,\n height: area.width,\n }\n }\n\n if (rotation === 3) {\n return {\n left: 100 - area.top - area.height,\n top: area.left,\n width: area.height,\n height: area.width,\n }\n }\n\n return area\n}\n\nexport function blockToHighlightArea(\n block: OcrBlock,\n pageSize?: { width: number; height: number }\n): HighlightArea {\n const { left, top, right, bottom } = getBoundingBox(block)\n\n const area = {\n left: (left / block.pageWidth) * 100,\n top: (top / block.pageHeight) * 100,\n width: ((right - left) / block.pageWidth) * 100,\n height: ((bottom - top) / block.pageHeight) * 100,\n }\n\n return normalizeHighlightAreaForRotation(\n area,\n getBlockCoordinateRotation(block, pageSize)\n )\n}\n\nexport function blockToArea(\n block: OcrBlock,\n pageSize?: { width: number; height: number }\n): React.CSSProperties {\n const area = blockToHighlightArea(block, pageSize)\n\n return {\n left: `${area.left}%`,\n top: `${area.top}%`,\n width: `${area.width}%`,\n height: `${area.height}%`,\n }\n}\n\nconst OcrBlockMarkdown = React.memo(function OcrBlockMarkdown({\n text,\n}: {\n text: string\n}) {\n const markdown = text.replace(OCR_MARKDOWN_FIGURE_CAPTION_PATTERN, (tag) =>\n tag.startsWith("</") ? "</figcaption>" : "<figcaption>"\n )\n\n return (\n <div className="space-y-1 text-sm leading-5 text-foreground/90">\n <ReactMarkdown\n rehypePlugins={OCR_MARKDOWN_REHYPE_PLUGINS}\n remarkPlugins={OCR_MARKDOWN_REMARK_PLUGINS}\n components={{\n h1: ({ node: _node, ...props }) => (\n <h1\n className="my-0 text-base leading-5 font-semibold text-foreground"\n {...props}\n />\n ),\n h2: ({ node: _node, ...props }) => (\n <h2\n className="my-0 text-[15px] leading-5 font-semibold text-foreground"\n {...props}\n />\n ),\n h3: ({ node: _node, ...props }) => (\n <h3\n className="my-0 text-sm leading-5 font-semibold text-foreground"\n {...props}\n />\n ),\n p: ({ node: _node, ...props }) => (\n <p className="my-0 text-[13px] leading-5" {...props} />\n ),\n strong: ({ node: _node, ...props }) => (\n <strong className="font-semibold text-foreground" {...props} />\n ),\n em: ({ node: _node, ...props }) => (\n <em className="text-foreground" {...props} />\n ),\n ul: ({ node: _node, ...props }) => (\n <ul className="my-0 list-disc space-y-0.5 pl-4" {...props} />\n ),\n ol: ({ node: _node, ...props }) => (\n <ol className="my-0 list-decimal space-y-0.5 pl-4" {...props} />\n ),\n li: ({ node: _node, ...props }) => (\n <li className="pl-0.5 text-[13px] leading-5" {...props} />\n ),\n table: ({ node: _node, ...props }) => (\n <div className="overflow-hidden rounded-md border bg-background">\n <table className="w-full border-collapse text-xs" {...props} />\n </div>\n ),\n figure: ({ node: _node, ...props }) => (\n <figure\n className="my-0 space-y-2 rounded-md border bg-muted/20 p-2 text-[13px]"\n {...props}\n />\n ),\n figcaption: ({ node: _node, ...props }) => (\n <figcaption\n className="border-t pt-2 text-xs leading-5 text-muted-foreground"\n {...props}\n />\n ),\n caption: ({ node: _node, ...props }) => (\n <figcaption\n className="block border-t pt-2 text-xs leading-5 text-muted-foreground"\n {...props}\n />\n ),\n th: ({ node: _node, ...props }) => (\n <th\n className="border-b bg-muted px-2 py-1 text-left font-medium"\n {...props}\n />\n ),\n td: ({ node: _node, ...props }) => (\n <td className="border-t px-2 py-1" {...props} />\n ),\n }}\n >\n {markdown}\n </ReactMarkdown>\n </div>\n )\n})\n\nexport function renderOcrBlockText(text: string) {\n return <OcrBlockMarkdown text={text} />\n}\n\nexport const OcrBlockOverlay = React.memo(function OcrBlockOverlay({\n block,\n isActive,\n pageHeight,\n pageWidth,\n}: {\n block: OcrBlock\n isActive?: boolean\n pageHeight?: number\n pageWidth?: number\n}) {\n const style = layoutBlockStyles[block.type]\n\n return (\n <div\n className={cn(\n "pointer-events-none absolute z-10 border transition-[opacity,box-shadow]",\n isActive ? style.overlay : cn("opacity-55", style.mutedOverlay)\n )}\n style={blockToArea(\n block,\n pageWidth && pageHeight\n ? { width: pageWidth, height: pageHeight }\n : undefined\n )}\n />\n )\n})\n\nexport function OcrBlocksPanel(props: {\n activeBlockId?: string\n blocks: OcrBlock[]\n className?: string\n onBlockFocus?: (block: OcrBlock) => void\n}) {\n return <LayoutBlocksPanel {...props} renderText={renderOcrBlockText} />\n}\n\nexport function OcrBlocks() {\n return (\n <OcrBlocksPanel blocks={getOcrBlocks(ATTENTION_OCR_OUTPUT).slice(0, 12)} />\n )\n}\n'++export function OcrBlocksSource() {+ return (+ <DocsSourceCodeBlock+ code={ocrBlocksSourceCode}+ fileName="components/extend/layout-blocks.tsx"+ />+ )+}diff --git a/apps/v4/components/lazy-docs-demos.tsx b/apps/v4/components/lazy-docs-demos.tsxindex 259fe02..49cd90a 100644--- a/apps/v4/components/lazy-docs-demos.tsx+++ b/apps/v4/components/lazy-docs-demos.tsx@@ -121,7 +121,7 @@ export const OcrBlocksDemo = dynamic(() =>)export const OcrBlocksSource = dynamic(() =>- import("@/components/layout-blocks-docs").then(+ import("@/components/layout-blocks-source-code").then((module) => module.OcrBlocksSource))diff --git a/apps/v4/components/pdf-viewer-block-fullscreen.tsx b/apps/v4/components/pdf-viewer-block-fullscreen.tsxindex 2a55b2a..7c9bc16 100644--- a/apps/v4/components/pdf-viewer-block-fullscreen.tsx+++ b/apps/v4/components/pdf-viewer-block-fullscreen.tsx@@ -1,113 +1,14 @@"use client"-import * as React from "react"-import dynamic from "next/dynamic"--import {- getPdfViewerBlock,- type PdfViewerBlockId,-} from "@/lib/pdf-viewer-blocks"--type PdfViewerBlockFullscreenPreviewProps = {- defaultViewerZoom?: number- heightClassName?: string-}--// Every preview is a dynamic chunk so each fullscreen page only loads the-// block it renders instead of bundling all of them.-const HumanReviewBlock = dynamic<- PdfViewerBlockFullscreenPreviewProps & { showExpected?: boolean }->(- () =>- import("@/components/bounding-box-citations-docs").then(- (mod) => mod.HumanReviewBlock- ),- { loading: () => <BlockViewPlaceholder /> }-)--const PdfDropzoneBlock = dynamic<PdfViewerBlockFullscreenPreviewProps>(- () =>- import("@/components/pdf-dropzone-block").then(- (mod) => mod.PdfDropzoneBlock- ),- { loading: () => <BlockViewPlaceholder /> }-)--const OcrBlocksBlock = dynamic<PdfViewerBlockFullscreenPreviewProps>(- () =>- import("@/components/layout-blocks-docs").then((mod) => mod.OcrBlocksBlock),- { loading: () => <BlockViewPlaceholder /> }-)--const ESignatureBlock = dynamic<PdfViewerBlockFullscreenPreviewProps>(- () =>- import("@/components/e-signature-docs").then((mod) => mod.ESignatureBlock),- { loading: () => <BlockViewPlaceholder /> }-)--const DocumentSplitsBlock = dynamic<PdfViewerBlockFullscreenPreviewProps>(- () =>- import("@/components/document-splitter-docs").then(- (mod) => mod.DocumentSplitsBlock- ),- { loading: () => <BlockViewPlaceholder /> }-)--const XlsxEditorBlock = dynamic<PdfViewerBlockFullscreenPreviewProps>(- () =>- import("@/components/document-splitter-docs").then(- (mod) => mod.XlsxEditorBlock- ),- { loading: () => <BlockViewPlaceholder /> }-)--const PdfEditorBlock = dynamic<PdfViewerBlockFullscreenPreviewProps>(- () =>- import("@/components/pdf-editor-docs").then((mod) => mod.PdfEditorBlock),- { loading: () => <BlockViewPlaceholder /> }-)--const DocxEditorBlock = dynamic<PdfViewerBlockFullscreenPreviewProps>(- () =>- import("@/components/docx-editor-docs").then((mod) => mod.DocxEditorBlock),- { loading: () => <BlockViewPlaceholder /> }-)--const FileSystemFinderBlock = dynamic<PdfViewerBlockFullscreenPreviewProps>(- () =>- import("@/components/file-system-docs").then(- (mod) => mod.FileSystemFinderBlock- ),- { loading: () => <BlockViewPlaceholder /> }-)--const blockComponents = {- "bounding-box-citations": (props: PdfViewerBlockFullscreenPreviewProps) => (- <HumanReviewBlock {...props} showExpected={false} />- ),- "pdf-dropzone": PdfDropzoneBlock,- "layout-blocks": OcrBlocksBlock,- "e-signature": ESignatureBlock,- "document-splits": DocumentSplitsBlock,- "excel-editor": XlsxEditorBlock,- "docx-editor-block": DocxEditorBlock,- "pdf-editor-block": PdfEditorBlock,- "file-system": FileSystemFinderBlock,-} satisfies Record<- PdfViewerBlockId,- React.ComponentType<PdfViewerBlockFullscreenPreviewProps>->--function BlockViewPlaceholder() {- return <div className="h-dvh bg-muted/20" />-}+import { getPdfViewerBlock } from "@/lib/pdf-viewer-blocks"+import { blockPreviews } from "@/components/block-previews"export function PdfViewerBlockFullscreen({ blockId }: { blockId: string }) {const block = getPdfViewerBlock(blockId)if (!block) return null- const Preview = blockComponents[block.id]+ const Preview = blockPreviews[block.id]return (<main className="h-dvh min-h-0 overflow-hidden bg-background [&>*]:h-full [&>*]:min-h-0">diff --git a/apps/v4/components/pdf-viewer-blocks.tsx b/apps/v4/components/pdf-viewer-blocks.tsxindex 61faad8..ad7f359 100644--- a/apps/v4/components/pdf-viewer-blocks.tsx+++ b/apps/v4/components/pdf-viewer-blocks.tsx@@ -4,7 +4,6 @@ import * as React from "react"import dynamic from "next/dynamic"import Link from "next/link"import {- CodeIcon,FullScreenIcon,LaptopIcon,Refresh01Icon,@@ -13,13 +12,14 @@ import {TerminalIcon,} from "@hugeicons/core-free-icons"import { HugeiconsIcon } from "@hugeicons/react"-import { prepareFileTreeInput } from "@pierre/trees"-import { FileTree as PierreFileTree, useFileTree } from "@pierre/trees/react"import type { PanelImperativeHandle } from "react-resizable-panels"+import type {+ BlockCodeFile,+ LoadedBlockCodeFile,+} from "@/lib/block-code-samples"import {PDF_VIEWER_BLOCKS,- type PdfViewerBlockId,type PdfViewerBlockMetadata,} from "@/lib/pdf-viewer-blocks"import { cn } from "@/lib/utils"@@ -32,26 +32,15 @@ import {ResizablePanel,ResizablePanelGroup,} from "@/components/ui/resizable"+import type { BlockCodeLoadState } from "@/components/block-code-panel"+import {+ BlockPreviewPlaceholder,+ blockPreviews,+} from "@/components/block-previews"import {- CodeHeaderCopyButton,CopyButtonIcon,copyToClipboardWithMeta,} from "@/components/copy-button"-import { HighlightedCodeBlock } from "@/components/highlighted-code-block"--type BlockCodeFile = {- sourcePath: string- targetPath: string- language: string-}--type LoadedBlockCodeFile = BlockCodeFile & {- content: string-}--type PdfViewerBlock = PdfViewerBlockMetadata & {- component: React.ComponentType-}type BlockViewportSize = "desktop" | "tablet" | "mobile"type BlockView = "preview" | "code"@@ -68,106 +57,15 @@ const blockViewportSizes: Array<{]const BLOCK_VIEWPORT_HEIGHT_CLASS = "h-[680px]"-const BLOCK_PREVIEW_LAZY_ROOT_MARGIN = "900px 0px"--// Every preview is a dynamic chunk so the page bundle stays free of the-// heavy viewer engines; chunks load when the lazy preview mounts near the-// viewport. Previews render with no props here — the explicit prop type-// only pins next/dynamic's inference so optional-prop components stay-// assignable to React.ComponentType.-type BlockPreviewProps = {- defaultViewerZoom?: number- heightClassName?: string-}--const HumanReviewBlock = dynamic<- BlockPreviewProps & { showExpected?: boolean }->(- () =>- import("@/components/bounding-box-citations-docs").then(- (mod) => mod.HumanReviewBlock- ),- { loading: () => <BlockPreviewPlaceholder /> }-)--const PdfDropzoneBlock = dynamic<BlockPreviewProps>(- () =>- import("@/components/pdf-dropzone-block").then(- (mod) => mod.PdfDropzoneBlock- ),- { loading: () => <BlockPreviewPlaceholder /> }-)--const OcrBlocksBlock = dynamic<BlockPreviewProps>(- () =>- import("@/components/layout-blocks-docs").then((mod) => mod.OcrBlocksBlock),- { loading: () => <BlockPreviewPlaceholder /> }-)+const SCROLL_SETTLE_MS = 150+const MIN_VISIBLE_RATIO = 0.1-const ESignatureBlock = dynamic<BlockPreviewProps>(+const BlockCodePanel = dynamic(() =>- import("@/components/e-signature-docs").then((mod) => mod.ESignatureBlock),- { loading: () => <BlockPreviewPlaceholder /> }+ import("@/components/block-code-panel").then((mod) => mod.BlockCodePanel),+ { loading: () => <div className="h-full bg-code" /> })-const DocumentSplitsBlock = dynamic<BlockPreviewProps>(- () =>- import("@/components/document-splitter-docs").then(- (mod) => mod.DocumentSplitsBlock- ),- { loading: () => <BlockPreviewPlaceholder /> }-)--const XlsxEditorBlock = dynamic<BlockPreviewProps>(- () =>- import("@/components/document-splitter-docs").then(- (mod) => mod.XlsxEditorBlock- ),- { loading: () => <BlockPreviewPlaceholder /> }-)--const PdfEditorBlock = dynamic<BlockPreviewProps>(- () =>- import("@/components/pdf-editor-docs").then((mod) => mod.PdfEditorBlock),- { loading: () => <BlockPreviewPlaceholder /> }-)--const DocxEditorBlock = dynamic<BlockPreviewProps>(- () =>- import("@/components/docx-editor-docs").then((mod) => mod.DocxEditorBlock),- { loading: () => <BlockPreviewPlaceholder /> }-)--const FileSystemFinderBlock = dynamic<BlockPreviewProps>(- () =>- import("@/components/file-system-docs").then(- (mod) => mod.FileSystemFinderBlock- ),- { loading: () => <BlockPreviewPlaceholder /> }-)--const blockComponents = {- "bounding-box-citations": () => <HumanReviewBlock showExpected={false} />,- "pdf-dropzone": PdfDropzoneBlock,- "layout-blocks": OcrBlocksBlock,- "e-signature": ESignatureBlock,- "document-splits": DocumentSplitsBlock,- "excel-editor": XlsxEditorBlock,- "docx-editor-block": DocxEditorBlock,- "pdf-editor-block": PdfEditorBlock,- "file-system": FileSystemFinderBlock,-} satisfies Record<PdfViewerBlockId, React.ComponentType>--const pdfViewerBlocks: PdfViewerBlock[] = PDF_VIEWER_BLOCKS.map((block) => ({- ...block,- component: blockComponents[block.id],-}))--type BlockCodeLoadState =- | { status: "loading" }- | { status: "error" }- | { status: "loaded"; files: LoadedBlockCodeFile[] }-// File contents stay out of the page payload; they are fetched once per// block from the static /blocks/[block]/code route when the Code tab opens.const blockCodeContentCache = new Map<string, Promise<LoadedBlockCodeFile[]>>()@@ -226,12 +124,18 @@ export function PdfViewerBlocks({}: {codeSamples: Record<string, BlockCodeFile[]>}) {+ const [sectionRef, visibleBlocks] = useVisibleBlocks()+ const isDesktopViewport = useMediaQuery("(min-width: 768px)")+ const mounted = useMounted()+ const showAll = mounted && !("IntersectionObserver" in window)return (- <section className="space-y-12">- {pdfViewerBlocks.map((block) => (+ <section ref={sectionRef} className="space-y-12">+ {PDF_VIEWER_BLOCKS.map((block) => (<PdfViewerBlockPreviewkey={block.id}block={block}+ isDesktopViewport={isDesktopViewport}+ inView={showAll || visibleBlocks.has(block.id)}codeSamples={codeSamples[block.id] ?? []}/>))}@@ -241,45 +145,46 @@ export function PdfViewerBlocks({function PdfViewerBlockPreview({block,+ inView,+ isDesktopViewport,codeSamples,}: {- block: (typeof pdfViewerBlocks)[number]+ inView: boolean+ isDesktopViewport: boolean+ block: PdfViewerBlockMetadatacodeSamples: BlockCodeFile[]}) {const [previewKey, setPreviewKey] = React.useState(0)const [view, setView] = React.useState<BlockView>("preview")- const [hasOpenedCode, setHasOpenedCode] = React.useState(false)- const [codeScrollResetKey, setCodeScrollResetKey] = React.useState(0)- const [activeViewport, setActiveViewport] =- React.useState<BlockViewportSize>("desktop")+ const [keepPreview, setKeepPreview] = React.useState(false)+ const lastScrollGesture = React.useRef(-Infinity)+ const [activeViewport, setActiveViewport] = React.useState(+ blockViewportSizes[0]+ )const [isCommandCopied, setIsCommandCopied] = React.useState(false)const [activeFile, setActiveFile] = React.useState<string | null>(codeSamples[0]?.targetPath ?? null)- const [articleRef, shouldMountPreview] = useLazyBlockPreview()const codeLoadState = useLoadedBlockCode(block.id,- hasOpenedCode && codeSamples.length > 0+ view === "code" && codeSamples.length > 0)- const isMounted = useMounted()const previewPanelRef = React.useRef<PanelImperativeHandle>(null)- const Preview = block.component- const isDesktopViewport = useMediaQuery("(min-width: 768px)")+ const Preview = blockPreviews[block.id]const previewHeightClassName =block.previewHeightClassName ?? BLOCK_VIEWPORT_HEIGHT_CLASS- function setBlockView(nextView: BlockView) {- if (nextView === "code") {- setHasOpenedCode(true)- setCodeScrollResetKey((key) => key + 1)- }+ function retainPreview() {+ if (!keepPreview) setKeepPreview(true)+ }- setView(nextView)+ function noteScrollGesture() {+ lastScrollGesture.current = performance.now()}function resizeViewport(viewport: (typeof blockViewportSizes)[number]) {setView("preview")- setActiveViewport(viewport.id)+ setActiveViewport(viewport)previewPanelRef.current?.resize(`${viewport.panelSize}%`)}@@ -312,13 +217,13 @@ function PdfViewerBlockPreview({}return (- <article ref={articleRef} id={block.id} className="scroll-mt-24 space-y-2">+ <article id={block.id} className="scroll-mt-24 space-y-2"><divdata-view={view}className="group/block-preview overflow-hidden rounded-xl"><div className="flex min-h-11 flex-wrap items-center gap-2 px-2 pb-2">- <BlockViewToggle view={view} onViewChange={setBlockView} />+ <BlockViewToggle view={view} onViewChange={setView} /><div className="flex min-w-0 flex-1 items-center gap-2"><ahref={`#${block.id}`}@@ -339,7 +244,7 @@ function PdfViewerBlockPreview({key={viewport.id}type="button"variant={- activeViewport === viewport.id ? "secondary" : "ghost"+ activeViewport.id === viewport.id ? "secondary" : "ghost"}size="icon-sm"className="size-7"@@ -357,7 +262,13 @@ function PdfViewerBlockPreview({className="size-7"title="Open Fullscreen Preview"aria-label={`Open ${block.title} fullscreen preview`}- render={<Link href={block.viewHref} target="_blank" />}+ render={+ <Link+ href={block.viewHref}+ prefetch={false}+ target="_blank"+ />+ }><HugeiconsIcon icon={FullScreenIcon} className="size-4" /></Button>@@ -368,7 +279,10 @@ function PdfViewerBlockPreview({className="size-7"title="Refresh Preview"aria-label={`Refresh ${block.title} preview`}- onClick={() => setPreviewKey((value) => value + 1)}+ onClick={() => {+ setKeepPreview(false)+ setPreviewKey((value) => value + 1)+ }}><HugeiconsIcon icon={Refresh01Icon} className="size-4" /></Button>@@ -396,90 +310,129 @@ function PdfViewerBlockPreview({</Button></div></div>- <div className={view === "preview" ? "block" : "hidden"}>- <div- className={`relative hidden ${previewHeightClassName} box-content overflow-hidden rounded-xl border bg-muted/30 md:block`}- >- <div className="absolute inset-0 right-4 bg-[radial-gradient(var(--border)_1px,transparent_1px)] bg-[size:20px_20px]" />+ <div+ hidden={view !== "preview"}+ className={cn(+ "relative box-content overflow-hidden rounded-xl border bg-background",+ previewHeightClassName+ )}+ onClickCapture={retainPreview}+ onPointerDownCapture={(event) => {+ if (event.pointerType !== "touch") retainPreview()+ }}+ onFocusCapture={retainPreview}+ onWheelCapture={keepPreview ? undefined : noteScrollGesture}+ onTouchMoveCapture={keepPreview ? undefined : noteScrollGesture}+ onScrollCapture={() => {+ if (+ performance.now() - lastScrollGesture.current <+ SCROLL_SETTLE_MS+ )+ retainPreview()+ }}+ onKeyDownCapture={retainPreview}+ onChangeCapture={retainPreview}+ onDropCapture={retainPreview}+ >+ {keepPreview || (inView && view === "preview") ? (<ResizablePanelGrouporientation="horizontal"- className="relative z-10 h-full"+ className="h-full bg-[radial-gradient(var(--border)_1px,transparent_1px)] bg-[size:20px_20px]"><ResizablePanelref={previewPanelRef}- defaultSize="100%"+ defaultSize={`${activeViewport.panelSize}%`}minSize="30%"className="min-w-0 overflow-hidden rounded-xl bg-background">- <BlockPreviewSurface- Preview={Preview}- isMounted={isMounted}- previewKey={previewKey}- shouldRenderPreview={isDesktopViewport && shouldMountPreview}- />+ <Preview key={previewKey} /></ResizablePanel>- <ResizableHandle className="relative w-3 bg-transparent p-0 after:absolute after:top-1/2 after:right-0 after:h-8 after:w-1.5 after:-translate-y-1/2 after:rounded-full after:bg-background after:shadow-sm after:ring-1 after:ring-border after:transition-all after:hover:h-10" />- <ResizablePanel defaultSize="0%" minSize="0%" />+ {isDesktopViewport && (+ <>+ <ResizableHandle className="relative w-3 bg-transparent p-0 after:absolute after:top-1/2 after:right-0 after:h-8 after:w-1.5 after:-translate-y-1/2 after:rounded-full after:bg-background after:shadow-sm after:ring-1 after:ring-border after:transition-all after:hover:h-10" />+ <ResizablePanel defaultSize="0%" minSize="0%" />+ </>+ )}</ResizablePanelGroup>- </div>- <div className="overflow-hidden rounded-xl border bg-background md:hidden">- <BlockPreviewSurface- Preview={Preview}- isMounted={isMounted}- previewKey={previewKey}- shouldRenderPreview={!isDesktopViewport && shouldMountPreview}- />- </div>+ ) : (+ <BlockPreviewPlaceholder />+ )}</div>- {hasOpenedCode ? (- <div className={view === "code" ? "block" : "hidden"}>- <BlockCodePanel- codeSamples={codeSamples}- loadState={codeLoadState}- activeFile={activeFile}- onActiveFileChange={setActiveFile}- scrollResetKey={codeScrollResetKey}- />+ {view === "code" && (+ <div className={BLOCK_VIEWPORT_HEIGHT_CLASS}>+ {inView && (+ <BlockCodePanel+ codeSamples={codeSamples}+ loadState={codeLoadState}+ activeFile={activeFile}+ onActiveFileChange={setActiveFile}+ />+ )}</div>- ) : null}+ )}</div></article>)}-function useLazyBlockPreview() {- const [node, setNode] = React.useState<HTMLElement | null>(null)- const [hasIntersected, setShouldMountPreview] = React.useState(false)- const isMounted = useMounted()- const shouldMountPreview =- hasIntersected || (isMounted && !("IntersectionObserver" in window))+function useVisibleBlocks() {+ const sectionRef = React.useRef<HTMLElement>(null)+ const [visibleBlocks, setVisibleBlocks] = React.useState<Set<string>>(+ () => new Set()+ )React.useEffect(() => {- if (shouldMountPreview) return- if (!node) return+ const section = sectionRef.current+ if (!section || !("IntersectionObserver" in window)) return++ const visible = new Set<string>()+ let dirty = false+ let settleTimer: number | undefined++ function publish() {+ settleTimer = undefined+ if (!dirty) return+ dirty = false+ const next = new Set(visible)+ React.startTransition(() => setVisibleBlocks(next))+ }- if (!("IntersectionObserver" in window)) return+ function onScroll() {+ window.clearTimeout(settleTimer)+ settleTimer = window.setTimeout(publish, SCROLL_SETTLE_MS)+ }const observer = new IntersectionObserver(- ([entry]) => {- if (!entry?.isIntersecting) return-- setShouldMountPreview(true)- observer.disconnect()+ (entries) => {+ for (const entry of entries) {+ const id = entry.target.id+ const inView =+ entry.isIntersecting &&+ (entry.intersectionRatio >= MIN_VISIBLE_RATIO ||+ (entry.rootBounds?.height ?? window.innerHeight) <+ entry.boundingClientRect.height * MIN_VISIBLE_RATIO)+ if (visible.has(id) === inView) continue+ if (inView) visible.add(id)+ else visible.delete(id)+ dirty = true+ }+ if (settleTimer === undefined) publish()},- { rootMargin: BLOCK_PREVIEW_LAZY_ROOT_MARGIN }+ { threshold: [0, MIN_VISIBLE_RATIO] })- observer.observe(node)-- return () => observer.disconnect()- }, [node, shouldMountPreview])-- return [setNode, shouldMountPreview] as const-}+ section+ .querySelectorAll(":scope > article[id]")+ .forEach((node) => observer.observe(node))+ window.addEventListener("scroll", onScroll, { passive: true })+ return () => {+ observer.disconnect()+ window.removeEventListener("scroll", onScroll)+ window.clearTimeout(settleTimer)+ }+ }, [])-function BlockPreviewPlaceholder() {- return <div className="h-full min-h-[560px] bg-muted/20" />+ return [sectionRef, visibleBlocks] as const}function BlockViewToggle({@@ -518,231 +471,3 @@ function BlockViewToggle({</div>)}--const BlockPreviewSurface = React.memo(function BlockPreviewSurface({- Preview,- isMounted,- previewKey,- shouldRenderPreview,-}: {- Preview: React.ComponentType- isMounted: boolean- previewKey: number- shouldRenderPreview: boolean-}) {- if (!isMounted || !shouldRenderPreview) {- return <BlockPreviewPlaceholder />- }-- return <Preview key={previewKey} />-})--function BlockCodePanel({- codeSamples,- loadState,- activeFile,- onActiveFileChange,- scrollResetKey,-}: {- codeSamples: BlockCodeFile[]- loadState: BlockCodeLoadState- activeFile: string | null- onActiveFileChange: (file: string) => void- scrollResetKey: React.Key-}) {- const activeCodeSample =- codeSamples.find((sample) => sample.targetPath === activeFile) ??- codeSamples[0]-- if (!activeCodeSample) {- return (- <div- className={`grid ${BLOCK_VIEWPORT_HEIGHT_CLASS} place-items-center rounded-xl border bg-code text-sm text-code-foreground`}- >- No source sample available.- </div>- )- }-- const activeLoadedSample =- loadState.status === "loaded"- ? loadState.files.find(- (file) => file.targetPath === activeCodeSample.targetPath- )- : undefined-- return (- <div- className={`flex ${BLOCK_VIEWPORT_HEIGHT_CLASS} overflow-hidden rounded-xl border bg-code text-code-foreground`}- >- <div className="hidden w-72 shrink-0 border-r bg-code md:block">- <div className="flex h-12 items-center border-b px-4 text-sm font-medium">- Files- </div>- <BlockFileTree- codeSamples={codeSamples}- activeFile={activeCodeSample.targetPath}- onActiveFileChange={onActiveFileChange}- />- </div>- <div className="flex min-w-0 flex-1 flex-col">- <div className="flex h-12 items-center gap-2 border-b px-4 text-sm">- <HugeiconsIcon icon={CodeIcon} className="size-4 opacity-70" />- <span className="truncate">{activeCodeSample.targetPath}</span>- {activeLoadedSample ? (- <CodeHeaderCopyButton- value={activeLoadedSample.content}- className="ml-auto"- event="copy_block_code"- />- ) : null}- </div>- {activeLoadedSample ? (- <BlockCodeContent- code={activeLoadedSample}- scrollResetKey={scrollResetKey}- />- ) : loadState.status === "error" ? (- <div className="grid min-h-0 flex-1 place-items-center text-sm text-code-foreground/70">- Failed to load source.- </div>- ) : (- <BlockCodeContentSkeleton />- )}- </div>- </div>- )-}--function BlockCodeContent({- code,- scrollResetKey,-}: {- code: LoadedBlockCodeFile- scrollResetKey: React.Key-}) {- return (- <HighlightedCodeBlock- code={code.content}- fileName={code.targetPath}- language={code.language}- lazy={false}- renderFallbackCode- scrollResetKey={scrollResetKey}- showCopy={false}- className="min-h-0 flex-1 rounded-none border-0"- maxHeightClassName="h-full max-h-none"- />- )-}--function BlockCodeContentSkeleton() {- return (- <div- aria-hidden="true"- className="min-h-0 flex-1 animate-pulse space-y-3 overflow-hidden p-4"- >- {Array.from({ length: 14 }, (_, index) => (- <div- key={index}- className="h-3 rounded bg-code-foreground/10"- style={{ width: `${30 + ((index * 37) % 55)}%` }}- />- ))}- </div>- )-}--function BlockFileTree({- codeSamples,- activeFile,- onActiveFileChange,-}: {- codeSamples: BlockCodeFile[]- activeFile: string- onActiveFileChange: (file: string) => void-}) {- const paths = React.useMemo(- () => codeSamples.map((sample) => sample.targetPath),- [codeSamples]- )-- return (- <PierreBlockFileTree- key={paths.join("\0")}- activeFile={activeFile}- paths={paths}- onActiveFileChange={onActiveFileChange}- />- )-}--function PierreBlockFileTree({- activeFile,- paths,- onActiveFileChange,-}: {- activeFile: string- paths: string[]- onActiveFileChange: (file: string) => void-}) {- const filePathSet = React.useMemo(() => new Set(paths), [paths])- const preparedInput = React.useMemo(- () =>- prepareFileTreeInput(paths, {- flattenEmptyDirectories: true,- sort: "default",- }),- [paths]- )- const { model } = useFileTree({- flattenEmptyDirectories: true,- initialExpansion: "open",- initialSelectedPaths: activeFile ? [activeFile] : [],- itemHeight: 28,- overscan: 12,- preparedInput,- unsafeCSS: `- button[data-type='item'][data-item-selected] {- background: var(--color-primary);- color: var(--color-primary-foreground);- }- button[data-type='item'][data-item-selected] *,- button[data-type='item'][data-item-selected] svg {- color: var(--color-primary-foreground) !important;- }- `,- onSelectionChange: (selectedPaths) => {- const nextPath = selectedPaths.find((path) => filePathSet.has(path))- if (nextPath) {- onActiveFileChange(nextPath)- }- },- })-- React.useEffect(() => {- if (!activeFile) return-- const item = model.getItem(activeFile)- if (!item) return-- item.select()- model.scrollToPath(activeFile, { focus: false, offset: "nearest" })- }, [activeFile, model])-- return (- <PierreFileTree- model={model}- className="block h-[calc(680px-3rem)]"- style={- {- "--trees-bg-override": "var(--color-code)",- "--trees-border-color-override": "var(--color-border)",- "--trees-fg-override":- "color-mix(in oklab, var(--color-code-foreground) 78%, transparent)",- "--trees-selected-bg-override": "var(--color-primary)",- } as React.CSSProperties- }- />- )-}diff --git a/apps/v4/content/docs/components/docx-editor.mdx b/apps/v4/content/docs/components/docx-editor.mdxindex 218c40e..3f2383d 100644--- a/apps/v4/content/docs/components/docx-editor.mdx+++ b/apps/v4/content/docs/components/docx-editor.mdx@@ -35,7 +35,7 @@ npx shadcn@latest add @extend/docx-editor<Step>Install the following dependencies:</Step>```bash-npm install @base-ui/react@^1.4.1 @extend-ai/[email protected]+npm install @base-ui/react@^1.4.1 @extend-ai/[email protected]```<Step>Install the icon library configured in your `components.json`:</Step>diff --git a/apps/v4/content/docs/components/docx-viewer.mdx b/apps/v4/content/docs/components/docx-viewer.mdxindex 69a210d..e80ead9 100644--- a/apps/v4/content/docs/components/docx-viewer.mdx+++ b/apps/v4/content/docs/components/docx-viewer.mdx@@ -35,7 +35,7 @@ npx shadcn@latest add @extend/docx-viewer<Step>Install the following dependencies:</Step>```bash-npm install @extend-ai/[email protected] @tanstack/[email protected]+npm install @extend-ai/[email protected] @tanstack/[email protected]```<Step>Install the icon library configured in your `components.json`:</Step>@@ -93,9 +93,18 @@ The DocxViewerPreview component renders a DOCX file with upload, theme, and zoom| `defaultZoom` | `number \| "fit-page" \| "fit-width" \| "automatic"` | `50` | No || `fileName` | `string` | `-` | No || `isDark` | `boolean` | `-` | Yes |+| `layout` | `React.ComponentType<DocxViewerLayoutProps>` | `-` | No || `onIsDarkChange` | `(isDark: boolean) => void` | `-` | Yes || `showDownload` | `boolean` | `true` | No || `showToolbar` | `boolean` | `true` | No || `showUpload` | `boolean` | `true` | No || `src` | `string` | `-` | No || `toolbarActions` | `React.ReactNode` | `-` | No |++## Layout blocks++[Open the DOCX Layout Blocks preview](/view/blocks/docx-layout-blocks) to inspect the parser output alongside the read-only viewer. Select a block to reveal its source in the document. The list includes nested blocks.++```bash+pnpm dlx shadcn@latest add @extend/docx-layout-blocks+```diff --git a/apps/v4/content/docs/components/layout-blocks.mdx b/apps/v4/content/docs/components/layout-blocks.mdxindex 61bf4d1..b0a3c8c 100644--- a/apps/v4/content/docs/components/layout-blocks.mdx+++ b/apps/v4/content/docs/components/layout-blocks.mdx@@ -6,7 +6,7 @@ component: trueLayout Blocks help users debug and review the text layer behind scanned or image-heavy PDFs. They should show document structure without replacing the original page image.-See it composed with the PDF Viewer in the [Layout Blocks block](/blocks#layout-blocks).+The [PDF Layout Blocks](/blocks#layout-blocks) and [DOCX Layout Blocks](/blocks#docx-layout-blocks) previews share the same panel, cards, and type badges.<OcrBlocksDemo />@@ -46,7 +46,11 @@ so make sure that library's package is installed. When copying the sourcemanually, replace each `IconPlaceholder` element with the icon named by theprop for your library.-<Step>Copy and paste the following code into your project.</Step>+<Step>Install the shared panel, then copy the PDF layout component.</Step>++```bash+npx shadcn@latest add @extend/layout-blocks-panel+```<OcrBlocksSource />diff --git a/apps/v4/lib/block-code-samples.ts b/apps/v4/lib/block-code-samples.tsindex 6901df5..1eea985 100644--- a/apps/v4/lib/block-code-samples.ts+++ b/apps/v4/lib/block-code-samples.ts@@ -31,6 +31,7 @@ export const blockIds = ["document-splits","excel-editor","docx-editor-block",+ "docx-layout-blocks","pdf-editor-block","file-system",]@@ -38,6 +39,8 @@ export const blockIds = [const blockCodeDependencies: Record<string, string[]> = {"pdf-dropzone": ["file-upload", "pdf-viewer", "file-thumbnail"],"layout-blocks": [+ "layout-blocks-panel",+ "layout-blocks","pdf-block-resizable-shell","pdf-viewer","file-thumbnail",@@ -54,6 +57,12 @@ const blockCodeDependencies: Record<string, string[]> = {"pdf-viewer",],"excel-editor": ["xlsx-editor"],+ "docx-layout-blocks": [+ "docx-viewer",+ "layout-blocks-panel",+ "pdf-block-resizable-shell",+ "file-thumbnail",+ ],"docx-editor-block": ["docx-editor", "file-thumbnail"],"pdf-editor-block": ["pdf-editor", "document-viewer-sidebar", "color-picker"],"file-system": [diff --git a/apps/v4/lib/events.ts b/apps/v4/lib/events.tsindex a297549..1e27ef3 100644--- a/apps/v4/lib/events.ts+++ b/apps/v4/lib/events.ts@@ -22,7 +22,10 @@ const eventSchema = z.object({]),// declare type AllowedPropertyValues = string | number | boolean | nullproperties: z- .record(z.union([z.string(), z.number(), z.boolean(), z.null()]))+ .record(+ z.string(),+ z.union([z.string(), z.number(), z.boolean(), z.null()])+ ).optional(),})diff --git a/apps/v4/lib/pdf-viewer-blocks.ts b/apps/v4/lib/pdf-viewer-blocks.tsindex 3b0e7ac..b062db2 100644--- a/apps/v4/lib/pdf-viewer-blocks.ts+++ b/apps/v4/lib/pdf-viewer-blocks.ts@@ -101,6 +101,16 @@ export const PDF_VIEWER_BLOCKS = [viewHref: "/view/blocks/docx-editor-block",previewHeightClassName: "h-[720px]",},+ {+ id: "docx-layout-blocks",+ title: "DOCX Layout Blocks",+ description:+ "Inspect parsed layout blocks in the read-only DOCX viewer and select a block to reveal its source.",+ command: getRegistryAddCommand("docx-layout-blocks"),+ docsHref: "/docs/components/docx-viewer#layout-blocks",+ viewHref: "/view/blocks/docx-layout-blocks",+ previewHeightClassName: "h-[720px]",+ },] as const satisfies readonly PdfViewerBlockConfig[]export type PdfViewerBlockId = (typeof PDF_VIEWER_BLOCKS)[number]["id"]diff --git a/apps/v4/package.json b/apps/v4/package.jsonindex 19a4706..425b724 100644--- a/apps/v4/package.json+++ b/apps/v4/package.json@@ -55,7 +55,7 @@"@embedpdf/plugin-viewport": "^2.15.0","@embedpdf/plugin-zoom": "^2.15.0","@embedpdf/utils": "2.15.0",- "@extend-ai/react-docx": "0.12.0",+ "@extend-ai/react-docx": "0.13.4","@extend-ai/react-pptx": "0.2.1","@extend-ai/react-xlsx": "0.19.0","@glideapps/glide-data-grid": "6.0.4-alpha24",diff --git a/apps/v4/registry.json b/apps/v4/registry.jsonindex b5ecfbf..eb01dbb 100644--- a/apps/v4/registry.json+++ b/apps/v4/registry.json@@ -747,7 +747,7 @@"title": "DOCX Viewer","description": "A DOCX viewer with upload, zoom, theme controls, and read-only rendering.","dependencies": [- "@extend-ai/[email protected]",+ "@extend-ai/[email protected]","@tanstack/react-virtual@^3.13.12"],"registryDependencies": [@@ -774,7 +774,7 @@"type": "registry:ui","title": "DOCX Editor","description": "A DOCX editor with a Word-style toolbar, page thumbnails, import, export, and live document mutation.",- "dependencies": ["@extend-ai/[email protected]"],+ "dependencies": ["@extend-ai/[email protected]"],"registryDependencies": ["@extend/document-viewer-sidebar","@extend/file-thumbnail",@@ -884,19 +884,34 @@}]},+ {+ "name": "layout-blocks-panel",+ "type": "registry:ui",+ "title": "Layout Blocks Panel",+ "description": "A virtualized list of layout blocks with typed badges and source navigation.",+ "dependencies": ["@tanstack/react-virtual@^3.13.26"],+ "registryDependencies": ["utils"],+ "categories": ["documents"],+ "files": [+ {+ "path": "components/extend/layout-blocks-panel.tsx",+ "type": "registry:ui",+ "target": "@components/extend/layout-blocks-panel.tsx"+ }+ ]+ },{"name": "layout-blocks","type": "registry:ui","title": "Layout Blocks","description": "A structured layout review panel with typed blocks and confidence cards.","dependencies": [- "@tanstack/react-virtual@^3.13.26","react-markdown@^10.1.0","rehype-raw@^7.0.0","rehype-sanitize@^6.0.0","remark-gfm@^4.0.1"],- "registryDependencies": ["utils"],+ "registryDependencies": ["@extend/layout-blocks-panel", "utils"],"categories": ["documents"],"files": [{@@ -1059,6 +1074,25 @@}]},+ {+ "name": "docx-layout-blocks",+ "type": "registry:block",+ "title": "DOCX Layout Blocks",+ "description": "A read-only DOCX viewer with typed layout blocks and source highlights.",+ "registryDependencies": [+ "@extend/docx-viewer",+ "@extend/layout-blocks-panel",+ "@extend/pdf-block-resizable-shell"+ ],+ "categories": ["documents", "blocks"],+ "files": [+ {+ "path": "registry/new-york-v4/blocks/docx-layout-blocks.tsx",+ "type": "registry:component",+ "target": "@components/blocks/docx-layout-blocks.tsx"+ }+ ]+ },{"name": "docx-editor-block","type": "registry:block",diff --git a/apps/v4/registry/new-york-v4/blocks/docx-layout-blocks.tsx b/apps/v4/registry/new-york-v4/blocks/docx-layout-blocks.tsxnew file mode 100644index 0000000..8e0ecfc--- /dev/null+++ b/apps/v4/registry/new-york-v4/blocks/docx-layout-blocks.tsx@@ -0,0 +1,171 @@+"use client"++import * as React from "react"+import {+ DocxBlockHighlights,+ extractDocumentBlocks,+ flattenDocumentBlocks,+ revealDocxSource,+ type DocumentBlock,+} from "@extend-ai/react-docx"++import {+ DocxViewerPreview,+ type DocxViewerLayoutProps,+} from "@/components/extend/docx-viewer"+import {+ LayoutBlocksPanel,+ layoutBlockStyles,+ type LayoutBlockItem,+} from "@/components/extend/layout-blocks-panel"+import { PdfBlockResizableShell } from "@/components/extend/pdf-block-resizable-shell"++const blockTypes = {+ text: { type: "paragraph" },+ heading: { type: "heading" },+ section_heading: { type: "heading", label: "Section heading" },+ figure: { type: "figure" },+ table: { type: "table" },+ table_head: { type: "table", label: "Table header" },+ table_cell: { type: "table", label: "Table cell" },+ key_value: { type: "paragraph", label: "Key-value pair" },+ page_number: { type: "page_number" },+ barcode: { type: "figure", label: "Barcode" },+ formula: { type: "paragraph", label: "Formula" },+ header: { type: "header" },+ footer: { type: "footer" },+ watermark: { type: "figure", label: "Watermark" },+ legend: { type: "paragraph", label: "Legend" },+} satisfies Record<+ DocumentBlock["type"],+ Pick<LayoutBlockItem, "type" | "label">+>++function presentation(+ block: DocumentBlock+): Pick<LayoutBlockItem, "type" | "label"> {+ return block.type === "text" && block.details.numbering+ ? { type: "list" }+ : blockTypes[block.type]+}++function blockColor(block: DocumentBlock) {+ return layoutBlockStyles[presentation(block).type].color+}++function BlockLayout({+ children,+ model,+ viewportRef,+ isLoading,+ loadError,+}: DocxViewerLayoutProps) {+ const [result, setResult] = React.useState<{+ model: NonNullable<typeof model>+ blocks: DocumentBlock[]+ error?: string+ }>()+ const [selectedId, setSelectedId] = React.useState<string>()+ const [previewId, setPreviewId] = React.useState<string>()++ React.useEffect(() => {+ if (!model) return+ let current = true+ void extractDocumentBlocks(model).then(+ (output) => {+ if (current)+ setResult({ model, blocks: flattenDocumentBlocks(output.blocks) })+ },+ (error: unknown) => {+ if (current)+ setResult({+ model,+ blocks: [],+ error:+ error instanceof Error+ ? error.message+ : "Unable to read layout blocks.",+ })+ }+ )+ return () => {+ current = false+ }+ }, [model])++ const parsed = result?.model === model ? result : undefined+ const blocks = parsed?.blocks+ const rows = React.useMemo(+ () =>+ blocks?.map((block) => ({+ ...presentation(block),+ id: block.id,+ text: block.content,+ block,+ })) ?? [],+ [blocks]+ )+ const active =+ blocks?.find((block) => block.id === (previewId ?? selectedId)) ??+ blocks?.[0]+ const message =+ loadError ||+ parsed?.error ||+ (isLoading || (model && !parsed)+ ? "Reading layout blocks…"+ : !model+ ? "Open a DOCX to inspect its layout blocks."+ : "No layout blocks found.")++ return (+ <PdfBlockResizableShell+ autoSaveId="docx-layout-blocks-panels"+ heightClassName="h-[720px]"+ left={+ <>+ {children}+ {blocks?.length ? (+ <DocxBlockHighlights+ rootRef={viewportRef}+ blocks={blocks}+ block={active}+ colorForBlock={blockColor}+ />+ ) : null}+ </>+ }+ right={+ <LayoutBlocksPanel+ heading="Layout blocks"+ ariaLabel="DOCX layout blocks"+ className="h-full"+ blocks={rows}+ activeBlockId={active?.id}+ emptyMessage={message}+ onBlockFocus={(row) => setPreviewId(row.id)}+ onBlockBlur={() => setPreviewId(undefined)}+ onBlockSelect={({ block }) => {+ setSelectedId(block.id)+ const source = block.sourceRefs[0]+ if (viewportRef.current && source)+ revealDocxSource(viewportRef.current, source)+ }}+ />+ }+ />+ )+}++export function DocxLayoutBlocks({ file }: { file?: string }) {+ const [isDark, setIsDark] = React.useState(false)+ return (+ <DocxViewerPreview+ src={file}+ className="h-full"+ defaultZoom="fit-width"+ layout={BlockLayout}+ isDark={isDark}+ onIsDarkChange={setIsDark}+ />+ )+}diff --git a/apps/v4/registry/new-york-v4/blocks/layout-blocks-block.tsx b/apps/v4/registry/new-york-v4/blocks/layout-blocks-block.tsxindex 64f452c..6e1b3ea 100644--- a/apps/v4/registry/new-york-v4/blocks/layout-blocks-block.tsx+++ b/apps/v4/registry/new-york-v4/blocks/layout-blocks-block.tsx@@ -16,9 +16,13 @@ import { PdfBlockResizableShell } from "@/components/extend/pdf-block-resizable-import { PDFViewer, type PDFViewerHandle } from "@/components/extend/pdf-viewer"export function OcrBlocksBlock({+ autoSaveId = "pdf-block-ocr",+ defaultViewerZoom = 1,file = PDF_URL,output = ATTENTION_OCR_OUTPUT,}: {+ autoSaveId?: string+ defaultViewerZoom?: numberfile?: stringoutput?: ParsedOcrOutput}) {@@ -82,12 +86,12 @@ export function OcrBlocksBlock({return (<PdfBlockResizableShell- autoSaveId="pdf-block-ocr"+ autoSaveId={autoSaveId}left={<PDFViewerref={viewerRef}src={file}- defaultZoom={1}+ defaultZoom={defaultViewerZoom}renderPageOverlay={renderPageOverlay}/>}diff --git a/apps/v4/scripts/build-registry.mts b/apps/v4/scripts/build-registry.mtsindex e90e2e0..3405268 100644--- a/apps/v4/scripts/build-registry.mts+++ b/apps/v4/scripts/build-registry.mts@@ -43,7 +43,7 @@ const registry = JSON.parse(const manifest = JSON.parse(await readFile(path.join(appRoot, "package.json"), "utf8")) as { dependencies: Record<string, string> }-const owners = new Map<string, string>()+const owners = new Map<string, string[]>()for (const item of registry.items)for (const file of item.files ?? []) {const target = file.target@@ -51,7 +51,7 @@ for (const item of registry.items).replace(/^@lib\//, "@/lib/").replace(/\.(tsx?|jsx?)$/, "")if (target && !target.startsWith("@/components/ui/"))- owners.set(target, item.name)+ owners.set(target, [...(owners.get(target) ?? []), item.name])}for (const family of ["base", "radix"] as const) {@@ -120,11 +120,12 @@ for (const family of ["base", "radix"] as const) {)continueconst modulePath = statement.moduleSpecifier.text+ const moduleOwners = owners.get(modulePath)if (modulePath.startsWith("@/components/ui/"))registryDependencies.add(modulePath.slice("@/components/ui/".length))else if (modulePath === "@/lib/utils") registryDependencies.add("utils")- else if (owners.has(modulePath) && owners.get(modulePath) !== item.name)- registryDependencies.add(`@extend/${owners.get(modulePath)}`)+ else if (moduleOwners && !moduleOwners.includes(item.name))+ registryDependencies.add(`@extend/${moduleOwners.at(-1)}`)else if (!modulePath.startsWith("@/") && !modulePath.startsWith(".")) {const packageName = modulePath.startsWith("@")? modulePath.split("/").slice(0, 2).join("/")diff --git a/package.json b/package.jsonindex 2ecb6f7..0835df6 100644--- a/package.json+++ b/package.json@@ -35,7 +35,7 @@"@types/react-dom": "19.2.2"},"patchedDependencies": {- "@extend-ai/[email protected]": "patches/@[email protected]"+ "@extend-ai/[email protected]": "patches/@[email protected]"}}}diff --git a/patches/@[email protected] b/patches/@[email protected]similarity index 76%rename from patches/@[email protected]rename to patches/@[email protected]index 6e06863..513824f 100644--- a/patches/@[email protected]+++ b/patches/@[email protected]@@ -1,8 +1,7 @@diff --git a/dist/index.cjs b/dist/index.cjs-index 6e5b4facab5b3ee7bbe9faf21e51f6571a92c020..2215135e1e6e28f36421d96548ce1aac66e2d88a 100644--- a/dist/index.cjs+++ b/dist/index.cjs-@@ -13506,7 +13506,7 @@ function fontMetricProfileKey() {+@@ -15899,7 +15899,7 @@const ratio = typeof window !== "undefined" ? window.devicePixelRatio : 1;const viewportScale = typeof window !== "undefined" ? window.visualViewport?.scale ?? 1 : 1;const hasDom = typeof document !== "undefined" && Boolean(document.body);@@ -12,10 +11,9 @@ index 6e5b4facab5b3ee7bbe9faf21e51f6571a92c020..2215135e1e6e28f36421d96548ce1aacfunction bodyZoomScale() {let scale = 1;diff --git a/dist/index.js b/dist/index.js-index f1c26fc1a7005acc436ce4d4395c6c1a8c72a169..51f2bd857558321ab5d55ca7c6dd83b1a1a7a4d7 100644--- a/dist/index.js+++ b/dist/index.js-@@ -12420,7 +12420,7 @@ function fontMetricProfileKey() {+@@ -14582,7 +14582,7 @@const ratio = typeof window !== "undefined" ? window.devicePixelRatio : 1;const viewportScale = typeof window !== "undefined" ? window.visualViewport?.scale ?? 1 : 1;const hasDom = typeof document !== "undefined" && Boolean(document.body);diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 293d77b..39dbce8 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -9,9 +9,9 @@ overrides:'@types/react-dom': 19.2.2patchedDependencies:- '@extend-ai/[email protected]':- hash: 6jpfdezkpalcaczkxwnedel2hi- path: patches/@[email protected]+ '@extend-ai/[email protected]':+ hash: 4ln4m3ssclybpuz52ehchmyjo4+ path: patches/@[email protected]importers:@@ -129,8 +129,8 @@ importers:specifier: 2.15.0version: 2.15.0([email protected])([email protected]([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]))([email protected]([email protected]))'@extend-ai/react-docx':- specifier: 0.12.0- version: 0.12.0(patch_hash=6jpfdezkpalcaczkxwnedel2hi)([email protected]([email protected]))([email protected])+ specifier: 0.13.4+ version: 0.13.4(patch_hash=4ln4m3ssclybpuz52ehchmyjo4)([email protected]([email protected]))([email protected])'@extend-ai/react-pptx':specifier: 0.2.1@@ -1484,8 +1484,8 @@ packages:resolution: {integrity: sha512-ZAoA40rNMPwSm+AeHpCq8STiNAwzWLJuP8Xv4CHIc9wv/PSuExjMrmjfYNj682vW0OOiZ1HKxzvjQr9XZIisQA==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}- '@extend-ai/[email protected]':- resolution: {integrity: sha512-PbapIQrN2naad7D6yHJV7v7UDcvfupfisHJMU5Mo/ZSQpTPGr4kIWuK09nRmaSDl7fdfbz+z1mj/SBdC6GlBMA==}+ '@extend-ai/[email protected]':+ resolution: {integrity: sha512-TbTeAZ7oowxwoc/WC27SJgRCs7VSw3PefcHnC+V1e5WOp8iRzE1C0aDl2vyZfBBDIH6ggjKCD9QbbNrFiqDyKA==}peerDependencies:react: '>=18'react-dom: '>=18'@@ -7648,7 +7648,7 @@ snapshots:'@eslint/core': 0.13.0levn: 0.4.1- '@extend-ai/[email protected](patch_hash=6jpfdezkpalcaczkxwnedel2hi)([email protected]([email protected]))([email protected])':+ '@extend-ai/[email protected](patch_hash=4ln4m3ssclybpuz52ehchmyjo4)([email protected]([email protected]))([email protected])':dependencies:'@chenglou/pretext': 0.0.8csstype: 3.2.3