Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: keep Word equations when a .docx is added to a knowledge base or chat documents (#12490)
Nilay7d21673ac363
diff --git a/studio/backend/core/rag/parsers.py b/studio/backend/core/rag/parsers.pyindex 4b141b55dd0..a8f2ce6ff00 100644--- a/studio/backend/core/rag/parsers.py+++ b/studio/backend/core/rag/parsers.py@@ -465,10 +465,19 @@ def render_pdf_pages(_W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"_MC_FALLBACK = "{http://schemas.openxmlformats.org/markup-compatibility/2006}Fallback"+_M = "{http://schemas.openxmlformats.org/officeDocument/2006/math}"+_DOCX_MATH = frozenset((_M + "oMathPara", _M + "oMath"))# Runs not shown as body text; text boxes are read as blocks of their own._DOCX_SKIP_RUNS_UNDER = frozenset((_W + "del", _W + "moveFrom", _W + "rt", _W + "txbxContent", _MC_FALLBACK))+_DOCX_SKIP_RUNS_OR_MATH = _DOCX_SKIP_RUNS_UNDER | _DOCX_MATH+_DOCX_MATH_ROWS = {+ "oMathPara": ("oMath", "\n"),+ "eqArr": ("e", "\n"),+ "m": ("mr", " \\\\ "),+ "mr": ("e", " & "),+}def _docx_placeholder(element) -> bool:@@ -528,11 +537,80 @@ def _docx_blocks(element, parent):yield from _docx_blocks(child if content is None else content, parent)+def _docx_math_text(element) -> str:+ # Mirrored by docxMathText in the frontend's attachment-content.ts.+ tag = element.tag+ if tag in _DOCX_SKIP_RUNS_UNDER or _docx_placeholder(element):+ return ""+ if tag == _W + "r":+ return element.text+ if tag == _M + "t":+ return element.text or ""+ name = tag[len(_M) :] if tag.startswith(_M) else ""++ def arg(key):+ child = element.find(_M + key)+ if child is None or prop(f"{key}Hide", "off") not in ("0", "false", "off"):+ return ""+ return _docx_math_text(child)++ def prop(key, default):+ node = element.find(f"{_M}{name}Pr/{_M}{key}")+ return default if node is None else node.get(_M + "val", "")++ def scripts(sub, sup):+ return (f"_{{{sub}}}" if sub else "") + (f"^{{{sup}}}" if sup else "")++ if name == "f":+ if prop("type", "bar") == "noBar":+ return f"{{{arg('num')} \\atop {arg('den')}}}"+ return f"\\frac{{{arg('num')}}}{{{arg('den')}}}"+ if name == "phant" and prop("show", "on") in ("0", "false", "off"):+ return ""+ if name in ("sSub", "sSup", "sSubSup"):+ return arg("e") + scripts(arg("sub"), arg("sup"))+ if name == "sPre":+ return "{}" + scripts(arg("sub"), arg("sup")) + arg("e")+ if name == "limLow":+ return arg("e") + scripts(arg("lim"), "")+ if name == "limUpp":+ return arg("e") + scripts("", arg("lim"))+ if name == "nary":+ return prop("chr", "\u222b") + scripts(arg("sub"), arg("sup")) + arg("e")+ if name == "rad":+ deg = arg("deg")+ return f"\\sqrt[{deg}]{{{arg('e')}}}" if deg else f"\\sqrt{{{arg('e')}}}"+ if name == "acc":+ return arg("e") + prop("chr", "\u0302")+ if name in ("bar", "groupChr"):+ side = "over" if prop("pos", "bot") == "top" else "under"+ if name == "bar":+ return f"\\{side}line{{{arg('e')}}}"+ mark = prop("chr", "\u23df")+ if mark in ("\u23de", "\u23df"):+ return f"\\{side}brace{{{arg('e')}}}"+ return f"\\{side}set{{{mark}}}{{{arg('e')}}}"+ if name == "func":+ return f"{arg('fName')} {arg('e')}"+ if name == "d":+ return (+ prop("begChr", "(")+ + prop("sepChr", "|").join(_docx_math_text(e) for e in element.iterchildren(_M + "e"))+ + prop("endChr", ")")+ )+ if name in _DOCX_MATH_ROWS:+ child, sep = _DOCX_MATH_ROWS[name]+ return sep.join(_docx_math_text(c) for c in element.iterchildren(_M + child))+ return "".join(_docx_math_text(child) for child in element.iterchildren("*"))++def _docx_paragraph_text(paragraph) -> str:- """Paragraph.text skips runs wrapped in w:ins, w:sdt, w:fldSimple, w:smartTag."""+ """Paragraph.text skips runs wrapped in w:ins, w:sdt, w:fldSimple, w:smartTag, and equations."""p = paragraph._preturn "".join(- run.text for run in p.iter(_W + "r") if not _docx_inside(run, p, _DOCX_SKIP_RUNS_UNDER)+ _docx_math_text(node) if node.tag in _DOCX_MATH else node.text+ for node in p.iter(_W + "r", *_DOCX_MATH)+ if not _docx_inside(node, p, _DOCX_SKIP_RUNS_OR_MATH))diff --git a/studio/backend/tests/test_rag_parsing.py b/studio/backend/tests/test_rag_parsing.pyindex 18218f82cf9..06b3fef0f40 100644--- a/studio/backend/tests/test_rag_parsing.py+++ b/studio/backend/tests/test_rag_parsing.py@@ -5,6 +5,8 @@from __future__ import annotations+import re+import pytest@@ -337,7 +339,8 @@ _DOCX_XMLNS = ('xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ''xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" ''xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" '- 'xmlns:v="urn:schemas-microsoft-com:vml"'+ 'xmlns:v="urn:schemas-microsoft-com:vml" '+ 'xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"')@@ -445,6 +448,113 @@ def test_docx_reads_one_branch_of_alternate_content(tmp_path):assert text == "Preferred"+def _m(text):+ return f'<m:r><w:rPr><w:rFonts w:ascii="Cambria Math"/></w:rPr><m:t>{text}</m:t></m:r>'+++def test_docx_keeps_equations_where_they_appear(tmp_path):+ half = f"<m:f><m:fPr><m:ctrlPr><w:rPr><w:i/></w:rPr></m:ctrlPr></m:fPr><m:num>{_m('1')}</m:num><m:den>{_m('2')}</m:den></m:f>"+ squared = f"<m:sSup><m:e>{_m('v')}</m:e><m:sup>{_m('2')}</m:sup></m:sSup>"+ text = _docx_from_xml(+ tmp_path,+ f"<w:p>{_r('The kinetic energy is ')}<m:oMath>{_m('E=')}{half}{_m('m')}{squared}</m:oMath>{_r(' joules.')}</w:p>",+ f"<w:p><m:oMathPara><m:oMathParaPr/><m:oMath>{_m('F=ma')}</m:oMath><m:oMath>{_m('p=mv')}</m:oMath></m:oMathPara></w:p>",+ )+ assert text == "The kinetic energy is E=\\frac{1}{2}mv^{2} joules.\nF=ma\np=mv"+++def test_docx_table_cells_keep_equations_without_deleted_parts(tmp_path):+ root = f"<m:rad><m:radPr><m:degHide m:val=\"1\"/></m:radPr><m:deg/><m:e>{_m('x')}</m:e></m:rad>"+ text = _docx_from_xml(+ tmp_path,+ "<w:tbl><w:tr>"+ f"<w:tc><w:p>{_r('Work')}</w:p></w:tc>"+ f"<w:tc><w:p><m:oMath>{_m('W=F')}<m:d><m:e>{_m('a+b')}</m:e></m:d>"+ f'<w:del w:id="1" w:author="a">{_m("+c")}</w:del>{root}</m:oMath></w:p></w:tc>'+ "</w:tr></w:tbl>",+ )+ assert text == "Work | W=F(a+b)\\sqrt{x}"+++def test_docx_equations_keep_binomials_and_skip_hidden_phantoms(tmp_path):+ binom = f'<m:d><m:e><m:f><m:fPr><m:type m:val="noBar"/></m:fPr><m:num>{_m("n")}</m:num><m:den>{_m("k")}</m:den></m:f></m:e></m:d>'+ phantom = (+ f'<m:phant><m:phantPr><m:show m:val="off"/></m:phantPr><m:e>{_m("xyz")}</m:e></m:phant>'+ )+ text = _docx_from_xml(+ tmp_path, f"<w:p><m:oMath>{binom}{_m('a')}{phantom}{_m('b')}</m:oMath></w:p>"+ )+ assert text == "({n \\atop k})ab"+++def test_docx_equations_keep_bars_and_group_characters(tmp_path):+ mean = f'<m:bar><m:barPr><m:pos m:val="top"/></m:barPr><m:e>{_m("x")}</m:e></m:bar>'+ brace = f"<m:limLow><m:e><m:groupChr><m:e>{_m('a+b')}</m:e></m:groupChr></m:e><m:lim>{_m('n')}</m:lim></m:limLow>"+ arrow = f'<m:groupChr><m:groupChrPr><m:chr m:val="→"/><m:pos m:val="top"/></m:groupChrPr><m:e>{_m("Δ")}</m:e></m:groupChr>'+ text = _docx_from_xml(+ tmp_path, f"<w:p><m:oMath>{mean}{_m('=')}{brace}{_m(',')}{arrow}</m:oMath></w:p>"+ )+ assert text == "\\overline{x}=\\underbrace{a+b}_{n},\\overset{→}{Δ}"+++# Same cases and expected text as the chat attachment reader's test (attachment-preview-text.test.ts).+_OMML_CASES = [+ (+ '<m:nary><m:naryPr><m:chr m:val="∑"/></m:naryPr><m:sub>{i=1}</m:sub><m:sup>{n}</m:sup><m:e>{i}</m:e></m:nary>',+ "∑_{i=1}^{n}i",+ ),+ ("<m:nary><m:sub>{0}</m:sub><m:sup>{1}</m:sup><m:e>{x}</m:e></m:nary>", "∫_{0}^{1}x"),+ (+ "<m:sSubSup><m:e>{x}</m:e><m:sub>{i}</m:sub><m:sup>{2}</m:sup></m:sSubSup><m:sSub><m:e>{a}</m:e><m:sub>{0}</m:sub></m:sSub>",+ "x_{i}^{2}a_{0}",+ ),+ ("<m:sPre><m:sub>{6}</m:sub><m:sup>{14}</m:sup><m:e>{C}</m:e></m:sPre>", "{}_{6}^{14}C"),+ ("<m:limUpp><m:e>{x}</m:e><m:lim>{def}</m:lim></m:limUpp>", "x^{def}"),+ ("<m:limLow><m:e>{lim}</m:e><m:lim>{n→∞}</m:lim></m:limLow>", "lim_{n→∞}"),+ (+ '<m:f><m:fPr><m:type m:val="noBar"/></m:fPr><m:num>{n}</m:num><m:den>{k}</m:den></m:f>'+ '<m:phant><m:phantPr><m:show m:val="off"/></m:phantPr><m:e>{xyz}</m:e></m:phant>',+ "{n \\atop k}",+ ),+ (+ "<m:acc><m:e>{θ}</m:e></m:acc><m:rad><m:deg>{3}</m:deg><m:e>{y}</m:e></m:rad>",+ "θ̂\\sqrt[3]{y}",+ ),+ (+ '<m:rad><m:radPr><m:degHide m:val="1"/></m:radPr><m:deg>{3}</m:deg><m:e>{x}</m:e></m:rad>'+ '<m:nary><m:naryPr><m:chr m:val="∑"/><m:subHide m:val="0"/><m:supHide/></m:naryPr><m:sub>{k}</m:sub><m:sup>{n}</m:sup><m:e>{a}</m:e></m:nary>',+ "\\sqrt{x}∑_{k}a",+ ),+ ("<m:func><m:fName>{sin}</m:fName><m:e>{x}</m:e></m:func>", "sin x"),+ (+ "<m:m><m:mr><m:e>{a}</m:e><m:e>{b}</m:e></m:mr><m:mr><m:e>{c}</m:e><m:e>{d}</m:e></m:mr></m:m>",+ "a & b \\\\ c & d",+ ),+ ("<m:eqArr><m:e>{x=1}</m:e><m:e>{y=2}</m:e></m:eqArr>", "x=1\ny=2"),+ (+ '<m:d><m:e>{a}</m:e><m:e>{b}</m:e></m:d><m:d><m:dPr><m:begChr m:val="["/><m:endChr m:val=""/></m:dPr><m:e>{c}</m:e></m:d>',+ "(a|b)[c",+ ),+ (+ '<m:bar><m:e>{x}</m:e></m:bar><m:groupChr><m:groupChrPr><m:chr m:val="⏞"/><m:pos m:val="top"/></m:groupChrPr><m:e>{y}</m:e></m:groupChr>'+ '<m:groupChr><m:groupChrPr><m:chr m:val="←"/></m:groupChrPr><m:e>{z}</m:e></m:groupChr>',+ "\\underline{x}\\overbrace{y}\\underset{←}{z}",+ ),+ (+ '{a}<w:r><w:t xml:space="preserve"> if </w:t></w:r>'+ "<w:sdt><w:sdtPr><w:showingPlcHdr/></w:sdtPr><w:sdtContent>{prompt}</w:sdtContent></w:sdt>{b}",+ "a if b",+ ),+]++[email protected](("omml", "expected"), _OMML_CASES)+def test_docx_equation_structures(tmp_path, omml, expected):+ filled = re.sub(r"\{([^{}]*)\}", lambda match: _m(match.group(1)), omml)+ text = _docx_from_xml(tmp_path, f"<w:p><m:oMath>{filled}</m:oMath></w:p>")+ assert text == expected++def test_docx_keeps_rows_and_cells_wrapped_in_content_controls(tmp_path):document, docx, parsers = _shared_setup_1()from docx.oxml import parse_xmldiff --git a/studio/frontend/src/features/chat/attachment-content.ts b/studio/frontend/src/features/chat/attachment-content.tsindex 2b622a18c91..ed41688c54d 100644--- a/studio/frontend/src/features/chat/attachment-content.ts+++ b/studio/frontend/src/features/chat/attachment-content.ts@@ -804,6 +804,118 @@ function docxNoteText(node: Node, ns: string): string {return text;}+const OMML_NAMESPACES = new Set([+ "http://schemas.openxmlformats.org/officeDocument/2006/math",+ "http://purl.oclc.org/ooxml/officeDocument/math",+]);+const OMML_ROWS: Record<string, [string, string]> = {+ oMathPara: ["oMath", "\n"],+ eqArr: ["e", "\n"],+ m: ["mr", " \\\\ "],+ mr: ["e", " & "],+};++/** Linear LaTeX-style text for an equation; mirrors the backend's _docx_math_text. */+function docxMathText(element: Element, w: string): string {+ const name = element.localName;+ const ns = element.namespaceURI ?? "";+ if (DOCX_NOTE_SKIP.has(name) || (name === "sdt" && isDocxPlaceholder(element, w))) return "";+ if (ns === w && name === "r") return docxNoteText(element, w);+ if (OMML_NAMESPACES.has(ns) && name === "t") return element.textContent ?? "";+ const children = (key: string) => childElements(element, ns, key);+ const join = (nodes: Element[], sep = "") => nodes.map((node) => docxMathText(node, w)).join(sep);+ const arg = (key: string) =>+ ["0", "false", "off"].includes(prop(`${key}Hide`, "off")) ? join(children(key).slice(0, 1)) : "";+ const prop = (key: string, fallback: string) => {+ const node = children(`${name}Pr`).flatMap((pr) => childElements(pr, ns, key))[0];+ return node ? (node.getAttributeNS(ns, "val") ?? "") : fallback;+ };+ const scripts = (sub: string, sup: string) => (sub ? `_{${sub}}` : "") + (sup ? `^{${sup}}` : "");+ const all = Array.from(element.childNodes).filter((node): node is Element => node.nodeType === 1);+ if (!OMML_NAMESPACES.has(ns)) return join(all);+ switch (name) {+ case "f":+ return prop("type", "bar") === "noBar"+ ? `{${arg("num")} \\atop ${arg("den")}}`+ : `\\frac{${arg("num")}}{${arg("den")}}`;+ case "phant":+ return ["0", "false", "off"].includes(prop("show", "on")) ? "" : join(all);+ case "sSub":+ case "sSup":+ case "sSubSup":+ return arg("e") + scripts(arg("sub"), arg("sup"));+ case "sPre":+ return `{}${scripts(arg("sub"), arg("sup"))}${arg("e")}`;+ case "limLow":+ return arg("e") + scripts(arg("lim"), "");+ case "limUpp":+ return arg("e") + scripts("", arg("lim"));+ case "nary":+ return prop("chr", "∫") + scripts(arg("sub"), arg("sup")) + arg("e");+ case "rad": {+ const deg = arg("deg");+ return deg ? `\\sqrt[${deg}]{${arg("e")}}` : `\\sqrt{${arg("e")}}`;+ }+ case "acc":+ return arg("e") + prop("chr", "̂");+ case "bar":+ case "groupChr": {+ const side = prop("pos", "bot") === "top" ? "over" : "under";+ if (name === "bar") return `\\${side}line{${arg("e")}}`;+ const mark = prop("chr", "⏟");+ if (mark === "⏞" || mark === "⏟") return `\\${side}brace{${arg("e")}}`;+ return `\\${side}set{${mark}}{${arg("e")}}`;+ }+ case "func":+ return `${arg("fName")} ${arg("e")}`;+ case "d":+ return prop("begChr", "(") + join(children("e"), prop("sepChr", "|")) + prop("endChr", ")");+ }+ const row = OMML_ROWS[name];+ return row ? join(children(row[0]), row[1]) : join(all);+}++/** Each equation becomes a plain run where it sits; extractRawText drops OMML. */+export function linearizeDocxMath(archive: Uint8Array): Uint8Array {+ const rewritten: Record<string, Uint8Array> = {};+ const parts = unzipSync(archive, { filter: (entry) => entry.name.endsWith(".xml") });+ for (const [name, bytes] of Object.entries(parts)) {+ const xml = strFromU8(bytes);+ if (!xml.includes("oMath")) continue;+ const doc = new DOMParser().parseFromString(xml, "application/xml");+ const root = doc.documentElement;+ const w = root?.namespaceURI ?? "";+ // Chromium keeps the root of malformed XML and drops everything after the error.+ if (!WORDPROCESSINGML_NAMESPACES.has(w) || doc.getElementsByTagName("parsererror").length) continue;+ const tag = (local: string) => (root.prefix ? `${root.prefix}:${local}` : local);+ let found = false;+ const visit = (node: Node) => {+ for (const child of Array.from(node.childNodes)) {+ if (child.nodeType !== 1) continue;+ const element = child as Element;+ if (+ !OMML_NAMESPACES.has(element.namespaceURI ?? "") ||+ (element.localName !== "oMath" && element.localName !== "oMathPara")+ ) {+ visit(element);+ continue;+ }+ const run = doc.createElementNS(w, tag("r"));+ const text = doc.createElementNS(w, tag("t"));+ text.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space", "preserve");+ text.appendChild(doc.createTextNode(docxMathText(element, w)));+ run.appendChild(text);+ node.replaceChild(run, element);+ found = true;+ }+ };+ visit(doc);+ if (found) rewritten[name] = strToU8(new XMLSerializer().serializeToString(doc));+ }+ if (!Object.keys(rewritten).length) return archive;+ return zipSync({ ...unzipSync(archive), ...rewritten }, { level: 0 });+}+const DOCX_NOTE_REFERENCE_RE =/<(?:([\w.-]+):)?(footnote|endnote)Reference\b([^>]*?)(\/?)>(\s*<\/(?:[\w.-]+:)?\2Reference\s*>)?/g;const DOCX_NOTE_ID_RE = /(?:^|\s)(?:[\w.-]+:)?id\s*=\s*["']([^"']*)["']/;@@ -1329,7 +1441,7 @@ export async function extractDocxAttachmentText(file: File): Promise<string> {file.name,new Uint8Array(buffer),);- const marked = markDocxNotes(repacked);+ const marked = markDocxNotes(linearizeDocxMath(repacked));const { value } = await mammoth.extractRawText({arrayBuffer: toArrayBuffer(marked.archive),});diff --git a/studio/frontend/tests/attachment-preview-text.test.ts b/studio/frontend/tests/attachment-preview-text.test.tsindex 2ba2b28c91f..998a1f03b39 100644--- a/studio/frontend/tests/attachment-preview-text.test.ts+++ b/studio/frontend/tests/attachment-preview-text.test.ts@@ -4,7 +4,7 @@import assert from "node:assert/strict";import test from "node:test";-import { DOMParser as XmlDomParser } from "@xmldom/xmldom";+import { DOMParser as XmlDomParser, XMLSerializer as XmlSerializer } from "@xmldom/xmldom";import {Unzip,UnzipInflate,@@ -29,6 +29,7 @@ const {getPdfAttachmentTextError,isAudioAttachment,isTextAttachment,+ linearizeDocxMath,markDocxNotes,parseAttachmentText,readAttachmentText,@@ -1231,6 +1232,139 @@ test("markDocxNotes numbers the references extractRawText keeps and marks the bo}});+test("linearizeDocxMath keeps equations in the body, tables and notes", async () => {+ const ns =+ 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ' ++ 'xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"';+ const run = (text: string) => `<w:r><w:t xml:space="preserve">${text}</w:t></w:r>`;+ const m = (text: string) => `<m:r><m:t>${text}</m:t></m:r>`;+ const half = `<m:f><m:num>${m("1")}</m:num><m:den>${m("2")}</m:den></m:f>`;+ const squared = `<m:sSup><m:e>${m("v")}</m:e><m:sup>${m("2")}</m:sup></m:sSup>`;+ const mean = `<m:bar><m:barPr><m:pos m:val="top"/></m:barPr><m:e>${m("x")}</m:e></m:bar>`;+ const root = `<m:rad><m:radPr><m:degHide m:val="1"/></m:radPr><m:deg/><m:e>${m("n")}</m:e></m:rad>`;+ const archive = repackDocxAttachmentArchive(+ "physics.docx",+ zipSync({+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": relationships([["officeDocument", "word/document.xml"]]),+ "word/document.xml": strToU8(+ `<w:document ${ns}><w:body>` ++ `<w:p>${run("The kinetic energy is ")}<m:oMath>${m("E=")}${half}${m("m")}${squared}</m:oMath>${run(" joules.")}` ++ `<w:r><w:footnoteReference w:id="1"/></w:r></w:p>` ++ `<w:p><m:oMathPara><m:oMath>${m("F=ma")}</m:oMath><m:oMath>${m("p=mv")}</m:oMath></m:oMathPara></w:p>` ++ `<w:tbl><w:tr><w:tc><w:p>${run("Error")}</w:p></w:tc><w:tc><w:p><m:oMath>` ++ `<m:d><m:e>${m("a+b")}</m:e></m:d><w:del w:id="2" w:author="a">${m("+c")}</w:del>${root}` ++ `</m:oMath></w:p></w:tc></w:tr></w:tbl>` ++ `<w:p><w:del w:id="3" w:author="a"><m:oMath>${m("gone")}</m:oMath></w:del></w:p>` ++ `</w:body></w:document>`,+ ),+ "word/_rels/document.xml.rels": relationships([["footnotes", "footnotes.xml"]]),+ "word/footnotes.xml": strToU8(+ `<w:footnotes ${ns}><w:footnote w:id="1"><w:p>${run("Where ")}<m:oMath>${mean}</m:oMath>${run(" is the mean.")}</w:p></w:footnote></w:footnotes>`,+ ),+ }),+ );+ const globals = globalThis as { DOMParser?: unknown; XMLSerializer?: unknown };+ const original = { DOMParser: globals.DOMParser, XMLSerializer: globals.XMLSerializer };+ globals.DOMParser = XmlDomParser;+ globals.XMLSerializer = XmlSerializer;+ try {+ const marked = markDocxNotes(linearizeDocxMath(archive));+ const { default: mammoth } = await import("mammoth");+ const { value } = await mammoth.extractRawText({ buffer: Buffer.from(marked.archive) });+ assert.equal(+ marked.label(value),+ "The kinetic energy is E=\\frac{1}{2}mv^{2} joules.[1]\n\nF=ma\np=mv\n\nError\n\n(a+b)\\sqrt{n}\n\n\n\n" ++ "Footnotes\n[1] Where \\overline{x} is the mean.",+ );+ } finally {+ Object.assign(globals, original);+ }+});++// Same cases and expected text as the backend reader's test_docx_equation_structures.+const OMML_CASES: [string, string][] = [+ [+ '<m:nary><m:naryPr><m:chr m:val="∑"/></m:naryPr><m:sub>{i=1}</m:sub><m:sup>{n}</m:sup><m:e>{i}</m:e></m:nary>',+ "∑_{i=1}^{n}i",+ ],+ ["<m:nary><m:sub>{0}</m:sub><m:sup>{1}</m:sup><m:e>{x}</m:e></m:nary>", "∫_{0}^{1}x"],+ [+ "<m:sSubSup><m:e>{x}</m:e><m:sub>{i}</m:sub><m:sup>{2}</m:sup></m:sSubSup><m:sSub><m:e>{a}</m:e><m:sub>{0}</m:sub></m:sSub>",+ "x_{i}^{2}a_{0}",+ ],+ ["<m:sPre><m:sub>{6}</m:sub><m:sup>{14}</m:sup><m:e>{C}</m:e></m:sPre>", "{}_{6}^{14}C"],+ ["<m:limUpp><m:e>{x}</m:e><m:lim>{def}</m:lim></m:limUpp>", "x^{def}"],+ ["<m:limLow><m:e>{lim}</m:e><m:lim>{n→∞}</m:lim></m:limLow>", "lim_{n→∞}"],+ [+ '<m:f><m:fPr><m:type m:val="noBar"/></m:fPr><m:num>{n}</m:num><m:den>{k}</m:den></m:f>' ++ '<m:phant><m:phantPr><m:show m:val="off"/></m:phantPr><m:e>{xyz}</m:e></m:phant>',+ "{n \\atop k}",+ ],+ ["<m:acc><m:e>{θ}</m:e></m:acc><m:rad><m:deg>{3}</m:deg><m:e>{y}</m:e></m:rad>", "θ̂\\sqrt[3]{y}"],+ [+ '<m:rad><m:radPr><m:degHide m:val="1"/></m:radPr><m:deg>{3}</m:deg><m:e>{x}</m:e></m:rad>' ++ '<m:nary><m:naryPr><m:chr m:val="∑"/><m:subHide m:val="0"/><m:supHide/></m:naryPr><m:sub>{k}</m:sub><m:sup>{n}</m:sup><m:e>{a}</m:e></m:nary>',+ "\\sqrt{x}∑_{k}a",+ ],+ ["<m:func><m:fName>{sin}</m:fName><m:e>{x}</m:e></m:func>", "sin x"],+ [+ "<m:m><m:mr><m:e>{a}</m:e><m:e>{b}</m:e></m:mr><m:mr><m:e>{c}</m:e><m:e>{d}</m:e></m:mr></m:m>",+ "a & b \\\\ c & d",+ ],+ ["<m:eqArr><m:e>{x=1}</m:e><m:e>{y=2}</m:e></m:eqArr>", "x=1\ny=2"],+ [+ '<m:d><m:e>{a}</m:e><m:e>{b}</m:e></m:d><m:d><m:dPr><m:begChr m:val="["/><m:endChr m:val=""/></m:dPr><m:e>{c}</m:e></m:d>',+ "(a|b)[c",+ ],+ [+ '<m:bar><m:e>{x}</m:e></m:bar><m:groupChr><m:groupChrPr><m:chr m:val="⏞"/><m:pos m:val="top"/></m:groupChrPr><m:e>{y}</m:e></m:groupChr>' ++ '<m:groupChr><m:groupChrPr><m:chr m:val="←"/></m:groupChrPr><m:e>{z}</m:e></m:groupChr>',+ "\\underline{x}\\overbrace{y}\\underset{←}{z}",+ ],+ [+ '{a}<w:r><w:t xml:space="preserve"> if </w:t></w:r>' ++ "<w:sdt><w:sdtPr><w:showingPlcHdr/></w:sdtPr><w:sdtContent>{prompt}</w:sdtContent></w:sdt>{b}",+ "a if b",+ ],+];++test("linearizeDocxMath writes equations as the backend does and leaves other parts untouched", () => {+ const ns =+ 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ' ++ 'xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"';+ const archive = (body: string) =>+ zipSync({ "word/document.xml": strToU8(`<w:document ${ns}><w:body>${body}</w:body></w:document>`) });+ const globals = globalThis as { DOMParser?: unknown; XMLSerializer?: unknown };+ const original = { DOMParser: globals.DOMParser, XMLSerializer: globals.XMLSerializer };+ globals.DOMParser = XmlDomParser;+ globals.XMLSerializer = XmlSerializer;+ try {+ const plain = archive('<w:p><w:r><w:t>oMath is only a word here</w:t></w:r></w:p>');+ assert.equal(linearizeDocxMath(plain), plain);+ // How Chromium's DOMParser returns a part cut short at an XML error.+ const truncated = archive(+ '<parsererror xmlns="http://www.w3.org/1999/xhtml"/><w:p><m:oMath><m:r><m:t>x</m:t></m:r></m:oMath></w:p>',+ );+ assert.equal(linearizeDocxMath(truncated), truncated);+ const strict = zipSync({+ "word/document.xml": strToU8(+ '<w:document xmlns:w="http://purl.oclc.org/ooxml/wordprocessingml/main" xmlns:m="http://purl.oclc.org/ooxml/officeDocument/math">' ++ "<w:body><w:p><m:oMath><m:sSup><m:e><m:r><m:t>x</m:t></m:r></m:e><m:sup><m:r><m:t>2</m:t></m:r></m:sup></m:sSup></m:oMath></w:p></w:body></w:document>",+ ),+ });+ assert.ok(strFromU8(unzipSync(linearizeDocxMath(strict))["word/document.xml"]).includes(">x^{2}<"));+ for (const [omml, expected] of OMML_CASES) {+ const filled = omml.replace(/\{([^{}]*)\}/g, (_, text: string) => `<m:r><m:t>${text}</m:t></m:r>`);+ const xml = strFromU8(unzipSync(linearizeDocxMath(archive(`<w:p><m:oMath>${filled}</m:oMath></w:p>`)))["word/document.xml"]);+ const doc = new XmlDomParser().parseFromString(xml, "application/xml");+ assert.equal(doc.getElementsByTagNameNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "t")[0]?.textContent, expected);+ }+ } finally {+ Object.assign(globals, original);+ }+});+test("markDocxNotes reads Strict OOXML notes and skips unfilled content controls", () => {const w = 'xmlns:w="http://purl.oclc.org/ooxml/wordprocessingml/main"';const run = (text: string) => `<w:r><w:t xml:space="preserve">${text}</w:t></w:r>`;