From 08346a0857d5bc96b6ca4ef56807f0b7c9550580 Mon Sep 17 00:00:00 2001
From: Mikei386 <44135113+Mikei386@users.noreply.github.com>
Date: Wed, 7 Oct 2026 00:36:09 +0200
Subject: [PATCH] Document and vendor reviewed OpenWebUI community plugins
---
docs/CURRENT_SYSTEM.md | 10 +
.../LICENSE-Classic298 | 28 +
.../LICENSE-Fu-Jie | 22 +
.../LICENSE-SmetDenis | 21 +
.../openwebui-community-plugins/README.md | 79 +
.../openwebui-community-plugins/activate.py | 23 +
.../download_code_blocks.py | 918 ++++
.../export_to_excel.py | 1552 ++++++
.../export_to_word.py | 3436 ++++++++++++++
.../inline_visualizer.py | 4171 +++++++++++++++++
.../openwebui-community-plugins/install.py | 32 +
.../openwebui-community-plugins/manifest.json | 50 +
.../markdown_normalizer.py | 1182 +++++
.../token_usage_display.py | 2327 +++++++++
.../openwebui-community-plugins/verify.py | 26 +
.../visualize.SKILL.md | 727 +++
16 files changed, 14604 insertions(+)
create mode 100644 integrations/openwebui-community-plugins/LICENSE-Classic298
create mode 100644 integrations/openwebui-community-plugins/LICENSE-Fu-Jie
create mode 100644 integrations/openwebui-community-plugins/LICENSE-SmetDenis
create mode 100644 integrations/openwebui-community-plugins/README.md
create mode 100644 integrations/openwebui-community-plugins/activate.py
create mode 100644 integrations/openwebui-community-plugins/download_code_blocks.py
create mode 100644 integrations/openwebui-community-plugins/export_to_excel.py
create mode 100644 integrations/openwebui-community-plugins/export_to_word.py
create mode 100644 integrations/openwebui-community-plugins/inline_visualizer.py
create mode 100644 integrations/openwebui-community-plugins/install.py
create mode 100644 integrations/openwebui-community-plugins/manifest.json
create mode 100644 integrations/openwebui-community-plugins/markdown_normalizer.py
create mode 100644 integrations/openwebui-community-plugins/token_usage_display.py
create mode 100644 integrations/openwebui-community-plugins/verify.py
create mode 100644 integrations/openwebui-community-plugins/visualize.SKILL.md
diff --git a/docs/CURRENT_SYSTEM.md b/docs/CURRENT_SYSTEM.md
index ba4d297..c0622a6 100644
--- a/docs/CURRENT_SYSTEM.md
+++ b/docs/CURRENT_SYSTEM.md
@@ -128,3 +128,13 @@ Original-JavaScript read-only über Unraids persistente Container-Vorlage eingeb
OpenWebUI mit gleichem Image neu erstellt. Athena/SoulX nicht neu gestartet.
Installation, Sicherung, Prüfgrenzen und Rückbau:
[Reasoning Effort Selector](../integrations/openwebui-reasoning-selector/README.md).
+
+### Weitere OpenWebUI-Community-Plugins (7. Oktober 2026)
+
+Inline Visualizer samt `visualize`-Skill, Token Usage Display, Markdown
+Normalizer, Word-/Excel-Export und Download Code Blocks importiert und
+serverseitig synthetisch geprüft. Sub Agent nicht installiert. Nach ausdrücklicher
+Zustimmung sind die fünf Funktionen global aktiviert und Same-Origin für
+den Visualizer im Benutzerprofil freigegeben. Browserprüfung noch offen.
+Quellen, Versionen, Backup und Einschränkungen:
+[integrations/openwebui-community-plugins](../integrations/openwebui-community-plugins/README.md).
diff --git a/integrations/openwebui-community-plugins/LICENSE-Classic298 b/integrations/openwebui-community-plugins/LICENSE-Classic298
new file mode 100644
index 0000000..e55cbe3
--- /dev/null
+++ b/integrations/openwebui-community-plugins/LICENSE-Classic298
@@ -0,0 +1,28 @@
+BSD 3-Clause License
+
+Copyright (c) 2026, Classic298
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/integrations/openwebui-community-plugins/LICENSE-Fu-Jie b/integrations/openwebui-community-plugins/LICENSE-Fu-Jie
new file mode 100644
index 0000000..3a5ba00
--- /dev/null
+++ b/integrations/openwebui-community-plugins/LICENSE-Fu-Jie
@@ -0,0 +1,22 @@
+MIT License
+
+Copyright (c) 2024 Awesome OpenWebUI Contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
diff --git a/integrations/openwebui-community-plugins/LICENSE-SmetDenis b/integrations/openwebui-community-plugins/LICENSE-SmetDenis
new file mode 100644
index 0000000..17063bd
--- /dev/null
+++ b/integrations/openwebui-community-plugins/LICENSE-SmetDenis
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Denis
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/integrations/openwebui-community-plugins/README.md b/integrations/openwebui-community-plugins/README.md
new file mode 100644
index 0000000..61e44b0
--- /dev/null
+++ b/integrations/openwebui-community-plugins/README.md
@@ -0,0 +1,79 @@
+# OpenWebUI Community-Erweiterungen
+
+Stand: 7. Oktober 2026. Sechs unveränderte Original-Erweiterungen importiert;
+Sub Agent ausdrücklich ausgeschlossen. Quellen, feste Git-Revisionen und
+SHA-256 stehen in `manifest.json`. Download Code Blocks stammt aus dem
+öffentlichen Community-Post; dessen heruntergeladener Python-Inhalt ist per
+Prüfsumme festgehalten. Lizenzen der Repositories liegen daneben; Download
+Code Blocks erklärt MIT im eigenen Header.
+
+| ID | Version | Typ |
+| --- | --- | --- |
+| inline_visualizer | 2.2.3 | Werkzeug |
+| token_usage_display | 2.6.0 | Filter |
+| markdown_normalizer | 1.2.9 | Filter |
+| export_to_word | 0.5.3 | Aktion |
+| export_to_excel | 0.3.11 | Aktion |
+| download_code_blocks | 1.1.0 | Aktion |
+
+## Installation und Zustand
+
+Installation erfolgte über die OpenWebUI-API im bestehenden Unraid-Dienst.
+Keine Containerneustarts und keine Frontend-Patches. Nach ausdrücklicher
+Zustimmung des Nutzers wurden alle fünf Funktionen global aktiviert und
+`iframeSandboxAllowSameOrigin` im bestehenden Admin-Benutzerprofil gesetzt.
+Der Zustand wird per API zurückgelesen. Das Visualizer-Werkzeug ist in
+Workspace → Tools verfügbar; der zugehörige Original-Skill `visualize`
+liegt in der nativen OpenWebUI-Skillverwaltung. Für die beiden Freigaben
+wurde `activate.py` getrennt von der Installation ausgeführt. Die erste
+automatische Freigabeprüfung hatte diese Schritte bis zur ausdrücklichen
+Zustimmung blockiert. Browserdarstellung noch nicht Ende zu Ende geprüft.
+
+Tokenfilter: Kostenanzeige und externe models.dev-Abfragen ausgeschaltet.
+Kontext-Prozentanzeige ebenfalls ausgeschaltet, bis die realen Athena-
+Profilgrößen verlässlich zugeordnet werden; keine geratenen Modellgrößen.
+Tokenzahlen und Dauer bleiben verfügbar. API-Zahlen werden bevorzugt,
+Schätzungen können verwendet werden, wenn keine Zahlen vorliegen.
+
+## Reproduktion, Abhängigkeiten, Sicherung
+
+`install.py` ist der dokumentierte Importweg für einen vorhandenen
+OpenWebUI-Dienst (nicht der native Athena-Installer). Im OpenWebUI-Python
+mit dessen Backend im PYTHONPATH starten. Der Helfer verwendet einen
+kurzlebigen, nicht ausgegebenen Admin-Token, sichert zuerst die SQLite-DB,
+importiert über die API und überschreibt keine vorhandenen IDs.
+Die Pfade beziehen sich ausdrücklich auf den aktuellen OpenWebUI-Container.
+Für OpenWebUI an anderer Stelle müssen DB-Pfad und API-Adresse angepasst
+werden; für einen nativen Athena-Deck-Dienst wird kein Plugin benötigt.
+
+OpenWebUI-Datenpartition inklusive webui.db, Plugins, Skills und
+Plugin-Backups sichern. Private DB-Sicherungen gehören nicht in Git.
+Vorimport-Sicherung: `/app/backend/data/plugin-backups/20261006T223416Z/webui.db`.
+
+Word benötigt python-docx, Pygments, latex2mathml, mathml2omml; letztere
+fehlten vorher und wurden beim API-Import durch OpenWebUIs vorgesehenen
+Requirements-Mechanismus installiert. Excel braucht pandas und xlsxwriter;
+beides war im vorhandenen Image verfügbar. Bei Neuaufbau importiert
+OpenWebUI die Word-Abhängigkeiten; Excel-Abhängigkeiten im Zielimage prüfen.
+Visualizer/Word verwenden für bestimmte Browserfunktionen öffentliche
+CDN-Bibliotheken. Kein eigener Source-Patch und kein zusätzlicher Container.
+
+## Prüfung und Bedienung
+
+`verify.py`: alle sechs Module geladen und Prüfsummen geprüft. Synthetische
+Token-Statistik, Markdown-Ausgangsfilter, echte DOCX- und XLSX-Erzeugung,
+Codeblock-Dateinamen und Visualizer-Werkzeugaufruf bestanden. Keine echten
+Chats gelesen, keine LLM-Inferenz. Browserdownload und interaktive
+Darstellung sind damit noch nicht Ende zu Ende geprüft.
+
+Funktionen: Administration → Funktionen. Aktionsknöpfe werden nach
+Zuordnung unter Antworten angeboten. Filter wirken nach Zuordnung an
+Modelle oder global. Visualizer pro Chat unter Werkzeuge wählen; mit dem
+bestehenden Tool-Search kann das Modell das lokale Werkzeug entdecken.
+Vor einer Visualisierung den Skill `visualize` laden.
+
+Rückfall: betroffene Funktionen deaktivieren oder Zuordnung entfernen,
+Werkzeug/Skill bei Bedarf deaktivieren. Ganze DB nur bei gestopptem Dienst
+und bewusstem Rücksetzen wiederherstellen, da sonst neuere Chats verloren
+gehen würden. Bestehende Thinking-, Audio- und Tool-Search-Erweiterungen
+wurden nicht geändert.
diff --git a/integrations/openwebui-community-plugins/activate.py b/integrations/openwebui-community-plugins/activate.py
new file mode 100644
index 0000000..8ef6691
--- /dev/null
+++ b/integrations/openwebui-community-plugins/activate.py
@@ -0,0 +1,23 @@
+"""Explicitly authorized global activation and visualizer browser preference."""
+import json,sqlite3,urllib.request
+from datetime import timedelta
+from open_webui.utils.auth import create_token
+c=sqlite3.connect("/app/backend/data/webui.db")
+uid=c.execute("select id from user where role='admin' limit 1").fetchone()[0]
+token=create_token({"id":uid},timedelta(minutes=5))
+def api(path,data=None):
+ req=urllib.request.Request("http://127.0.0.1:8080/api/v1/"+path,data=None if data is None else json.dumps(data).encode(),headers={"Authorization":"Bearer "+token,"Content-Type":"application/json"})
+ with urllib.request.urlopen(req,timeout=60) as r:return json.load(r)
+ids=('token_usage_display','markdown_normalizer','export_to_word','export_to_excel','download_code_blocks')
+for ident in ids:
+ row=next(x for x in api('functions/') if x['id']==ident)
+ if not row.get('is_active'):api('functions/id/'+ident+'/toggle',{})
+ if not row.get('is_global'):api('functions/id/'+ident+'/toggle/global',{})
+settings=api('users/user/settings') or {}
+settings.setdefault('ui',{})['iframeSandboxAllowSameOrigin']=True
+api('users/user/settings/update',settings)
+assert api('users/user/settings')['ui']['iframeSandboxAllowSameOrigin'] is True
+for row in api('functions/'):
+ if row['id'] in ids:
+ assert row['is_active'] and row['is_global'];print(row['id'],'active/global')
+print('Visualizer same-origin preference verified')
diff --git a/integrations/openwebui-community-plugins/download_code_blocks.py b/integrations/openwebui-community-plugins/download_code_blocks.py
new file mode 100644
index 0000000..a1b1312
--- /dev/null
+++ b/integrations/openwebui-community-plugins/download_code_blocks.py
@@ -0,0 +1,918 @@
+"""
+title: Download Code Blocks
+author: silentoplayz
+author_url: https://github.com/silentoplayz
+funding_url: https://github.com/sponsors/silentoplayz
+version: 1.1.0
+license: MIT
+description: Extracts fenced code blocks from any assistant response and downloads them as properly named files. Features a confirmation modal with syntax-highlighted previews, line numbers, and editable filenames. Supports 170+ languages.
+required_open_webui_version: 0.4.0
+"""
+
+import html as html_lib
+import re
+from pydantic import BaseModel, Field
+
+try:
+ from pygments import highlight as _pygments_highlight
+ from pygments.lexers import get_lexer_by_name, ClassNotFound as _LexerNotFound
+ from pygments.formatters import HtmlFormatter as _HtmlFormatter
+
+ _HAS_PYGMENTS = True
+except ImportError:
+ _HAS_PYGMENTS = False
+
+
+class Action:
+ # SVG download icon (Lucide arrow-down-to-line)
+ icon_url = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 17V3'/%3E%3Cpath d='m6 11 6 6 6-6'/%3E%3Cpath d='M19 21H5'/%3E%3C/svg%3E"
+
+ class Valves(BaseModel):
+ priority: int = Field(
+ default=0, description="Priority level for the action button ordering."
+ )
+ default_filename: str = Field(
+ default="code",
+ description="Base filename used when a code block has no language specified.",
+ )
+ auto_download: bool = Field(
+ default=False,
+ description="When enabled, downloads all code blocks immediately without confirmation prompts.",
+ )
+
+ class UserValves(BaseModel):
+ default_filename: str = Field(
+ default="code",
+ description="Base filename used when a code block has no language specified.",
+ )
+ auto_download: bool = Field(
+ default=False,
+ description="When enabled, downloads all code blocks immediately without confirmation prompts.",
+ )
+
+ def __init__(self):
+ self.valves = self.Valves()
+
+ # Mapping of language identifiers to file extensions
+ LANG_EXTENSION_MAP = {
+ # Web
+ "html": "html",
+ "htm": "html",
+ "css": "css",
+ "scss": "scss",
+ "sass": "sass",
+ "less": "less",
+ "javascript": "js",
+ "js": "js",
+ "jsx": "jsx",
+ "typescript": "ts",
+ "ts": "ts",
+ "tsx": "tsx",
+ "svelte": "svelte",
+ "vue": "vue",
+ "astro": "astro",
+ # Python
+ "python": "py",
+ "py": "py",
+ "python3": "py",
+ "pyw": "pyw",
+ # Systems
+ "c": "c",
+ "cpp": "cpp",
+ "c++": "cpp",
+ "cxx": "cpp",
+ "h": "h",
+ "hpp": "hpp",
+ "rust": "rs",
+ "rs": "rs",
+ "go": "go",
+ "golang": "go",
+ "zig": "zig",
+ # JVM
+ "java": "java",
+ "kotlin": "kt",
+ "kt": "kt",
+ "scala": "scala",
+ "groovy": "groovy",
+ # .NET
+ "csharp": "cs",
+ "cs": "cs",
+ "c#": "cs",
+ "fsharp": "fs",
+ "fs": "fs",
+ "f#": "fs",
+ "vb": "vb",
+ "vbnet": "vb",
+ # Shell
+ "bash": "sh",
+ "sh": "sh",
+ "shell": "sh",
+ "zsh": "zsh",
+ "fish": "fish",
+ "powershell": "ps1",
+ "ps1": "ps1",
+ "pwsh": "ps1",
+ "bat": "bat",
+ "batch": "bat",
+ "cmd": "cmd",
+ # Data / Config
+ "json": "json",
+ "jsonc": "jsonc",
+ "json5": "json5",
+ "yaml": "yaml",
+ "yml": "yaml",
+ "toml": "toml",
+ "ini": "ini",
+ "cfg": "cfg",
+ "xml": "xml",
+ "csv": "csv",
+ "tsv": "tsv",
+ "env": "env",
+ "dotenv": "env",
+ "properties": "properties",
+ # Markup / Docs
+ "markdown": "md",
+ "md": "md",
+ "rst": "rst",
+ "restructuredtext": "rst",
+ "tex": "tex",
+ "latex": "tex",
+ "txt": "txt",
+ "text": "txt",
+ "plaintext": "txt",
+ # Ruby
+ "ruby": "rb",
+ "rb": "rb",
+ # PHP
+ "php": "php",
+ # Swift / Objective-C
+ "swift": "swift",
+ "objectivec": "m",
+ "objc": "m",
+ # Functional
+ "haskell": "hs",
+ "hs": "hs",
+ "elixir": "ex",
+ "ex": "ex",
+ "erlang": "erl",
+ "erl": "erl",
+ "clojure": "clj",
+ "clj": "clj",
+ "ocaml": "ml",
+ "ml": "ml",
+ "lisp": "lisp",
+ "scheme": "scm",
+ "racket": "rkt",
+ # Scripting
+ "lua": "lua",
+ "perl": "pl",
+ "pl": "pl",
+ "r": "r",
+ "julia": "jl",
+ "jl": "jl",
+ "dart": "dart",
+ "nim": "nim",
+ "v": "v",
+ "vlang": "v",
+ # Database
+ "sql": "sql",
+ "mysql": "sql",
+ "postgresql": "sql",
+ "postgres": "sql",
+ "sqlite": "sql",
+ "plsql": "sql",
+ "graphql": "graphql",
+ "gql": "graphql",
+ # DevOps / IaC
+ "dockerfile": "Dockerfile",
+ "docker": "Dockerfile",
+ "terraform": "tf",
+ "tf": "tf",
+ "hcl": "tf",
+ "nginx": "conf",
+ "apache": "conf",
+ # Build tools
+ "makefile": "Makefile",
+ "make": "Makefile",
+ "cmake": "cmake",
+ "gradle": "gradle",
+ # Other
+ "diff": "diff",
+ "patch": "patch",
+ "asm": "asm",
+ "assembly": "asm",
+ "nasm": "asm",
+ "wasm": "wasm",
+ "proto": "proto",
+ "protobuf": "proto",
+ "solidity": "sol",
+ "sol": "sol",
+ "cuda": "cu",
+ "glsl": "glsl",
+ "hlsl": "hlsl",
+ "wgsl": "wgsl",
+ "regex": "txt",
+ "mermaid": "mmd",
+ }
+
+ # MIME type mapping for common extensions
+ MIME_TYPE_MAP = {
+ "html": "text/html",
+ "css": "text/css",
+ "js": "text/javascript",
+ "jsx": "text/javascript",
+ "ts": "text/typescript",
+ "tsx": "text/typescript",
+ "json": "application/json",
+ "xml": "application/xml",
+ "svg": "image/svg+xml",
+ "md": "text/markdown",
+ "py": "text/x-python",
+ "sh": "text/x-shellscript",
+ "sql": "application/sql",
+ "yaml": "text/yaml",
+ "csv": "text/csv",
+ }
+
+ # Maximum number of lines to show in the code preview
+ MAX_PREVIEW_LINES = 200
+
+ def _get_extension(self, lang: str) -> str:
+ """Resolve a language identifier to a file extension."""
+ if not lang:
+ return "txt"
+ return self.LANG_EXTENSION_MAP.get(lang.lower().strip(), lang.lower().strip())
+
+ def _get_mime_type(self, ext: str) -> str:
+ """Get the MIME type for a file extension."""
+ return self.MIME_TYPE_MAP.get(ext, "text/plain")
+
+ def _extract_code_blocks(self, content: str) -> list[dict]:
+ """
+ Extract all fenced code blocks from markdown content.
+ Returns a list of dicts with 'lang', 'code', and 'filename' keys.
+ """
+ # Match ```lang ... ``` blocks, including optional filename hints
+ pattern = r"```(\w*)\s*\n(.*?)```"
+ matches = re.findall(pattern, content, re.DOTALL)
+
+ blocks = []
+ lang_counters: dict[str, int] = {}
+
+ for lang, code in matches:
+ lang = lang.strip() if lang else ""
+ code = code.rstrip("\n")
+
+ if not code.strip():
+ continue
+
+ ext = self._get_extension(lang)
+ base = self.valves.default_filename
+
+ # Use the language as a more descriptive base if available
+ if lang:
+ base = lang.lower()
+
+ # Always number files: python_1.py, python_2.py, etc.
+ lang_counters[ext] = lang_counters.get(ext, 0) + 1
+ count = lang_counters[ext]
+
+ filename = f"{base}_{count}.{ext}"
+
+ # Handle special filenames (Dockerfile, Makefile, etc.)
+ if ext in ("Dockerfile", "Makefile"):
+ filename = f"{ext}_{count}"
+
+ blocks.append(
+ {
+ "lang": lang or "text",
+ "code": code,
+ "filename": filename,
+ "extension": ext,
+ }
+ )
+
+ return blocks
+
+ def _build_code_preview(self, block: dict, index: int, total: int) -> str:
+ """
+ Build an HTML-formatted code preview for the confirmation modal.
+
+ Uses raw HTML that visually matches Open WebUI's native CodeBlock
+ component: OLED black background, language header bar, and CSS-
+ powered line numbers. html.escape() prevents code content from
+ being rendered by the marked parser. A scrollable container
+ handles long code.
+ """
+ lang = block["lang"]
+ code = block["code"]
+ lines = code.split("\n")
+ total_lines = len(lines)
+
+ # Truncate extremely long blocks to limit WebSocket payload size
+ if total_lines > self.MAX_PREVIEW_LINES:
+ preview_lines = lines[: self.MAX_PREVIEW_LINES]
+ remaining = total_lines - self.MAX_PREVIEW_LINES
+ truncation_html = (
+ f'
'
+ f"\u2026 {remaining} more line{'s' if remaining != 1 else ''} "
+ f"(truncated for preview)
"
+ )
+ else:
+ preview_lines = lines
+ truncation_html = ""
+
+ escaped_lang = html_lib.escape(lang)
+ line_label = f"{total_lines} line{'s' if total_lines != 1 else ''}"
+
+ return (
+ f''
+ f"Code block {index} of {total} · "
+ f"{line_label}
"
+ #
+ # Code block container
+ f''
+ #
+ # ── Header bar (matches CodeBlock.svelte sticky header) ──
+ f'
'
+ f'{escaped_lang} '
+ f"
"
+ #
+ # ── Scrollable code area ──
+ f'
'
+ f'
'
+ f"{self._build_numbered_code(preview_lines, lang)}"
+ f" "
+ #
+ # Truncation notice (if applicable)
+ f"{truncation_html}"
+ f"
"
+ )
+
+ def _highlight_code(self, code: str, lang: str) -> str | None:
+ """
+ Syntax-highlight code using Pygments with github-dark inline styles.
+
+ Returns the highlighted HTML string, or None if Pygments is
+ unavailable or the language is not recognized. Uses
+ ``noclasses=True`` so all colors are inlined as ``style``
+ attributes, which survive DOMPurify sanitization.
+ """
+ if not _HAS_PYGMENTS:
+ return None
+
+ try:
+ lexer = get_lexer_by_name(lang)
+ except _LexerNotFound:
+ return None
+
+ # github-dark matches Open WebUI's highlight.js theme
+ for style in ("github-dark", "monokai"):
+ try:
+ formatter = _HtmlFormatter(
+ noclasses=True,
+ style=style,
+ nowrap=True,
+ )
+ return _pygments_highlight(code, lexer, formatter)
+ except Exception:
+ continue
+
+ return None
+
+ def _build_numbered_code(self, lines: list[str], lang: str = "") -> str:
+ """
+ Build HTML for code lines with inline line numbers and optional
+ syntax highlighting.
+
+ If Pygments is available the code is highlighted first, then
+ split by newlines so each line can be prefixed with a dimmed,
+ right-aligned line number ````.
+ """
+ # Attempt syntax highlighting
+ preview_code = "\n".join(lines)
+ highlighted = self._highlight_code(preview_code, lang)
+
+ if highlighted is not None:
+ h_lines = highlighted.rstrip("\n").split("\n")
+ else:
+ h_lines = None
+
+ gutter_width = len(str(len(lines)))
+ parts = []
+ for i in range(len(lines)):
+ # Use highlighted line if available, otherwise escape
+ if h_lines is not None and i < len(h_lines):
+ content = h_lines[i] if h_lines[i] else " "
+ else:
+ content = html_lib.escape(lines[i]) if lines[i] else " "
+
+ num_str = str(i + 1).rjust(gutter_width)
+ parts.append(
+ f'{num_str} {content}'
+ )
+ return "\n".join(parts)
+
+ def _build_single_download_js(self, code: str, filename: str, ext: str) -> str:
+ """Build JavaScript to download a single file."""
+ mime = self._get_mime_type(ext)
+ escaped_code = (
+ code.replace("\\", "\\\\").replace("`", "\\`").replace("${", "\\${")
+ )
+ return f"""
+ (function() {{
+ const content = `{escaped_code}`;
+ const blob = new Blob([content], {{ type: '{mime}' }});
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = '{filename}';
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+ }})();
+ """
+
+ def _build_batch_download_js(self, blocks: list[dict]) -> str:
+ """
+ Build JavaScript that downloads multiple files via the browser.
+ Uses a staggered approach to avoid popup blockers.
+ """
+ file_defs = []
+ for block in blocks:
+ mime = self._get_mime_type(block["extension"])
+ escaped_code = (
+ block["code"]
+ .replace("\\", "\\\\")
+ .replace("`", "\\`")
+ .replace("${", "\\${")
+ )
+ file_defs.append(
+ f'{{ filename: "{block["filename"]}", content: `{escaped_code}`, mime: "{mime}" }}'
+ )
+
+ files_array = ",\n ".join(file_defs)
+
+ return f"""
+ (function() {{
+ const files = [
+ {files_array}
+ ];
+
+ function downloadFile(file) {{
+ const blob = new Blob([file.content], {{ type: file.mime }});
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = file.filename;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+ }}
+
+ // Stagger downloads to avoid browser throttling
+ files.forEach(function(file, index) {{
+ setTimeout(function() {{
+ downloadFile(file);
+ }}, index * 350);
+ }});
+ }})();
+ """
+
+ async def _confirm_and_download(
+ self,
+ blocks: list[dict],
+ __event_emitter__,
+ __event_call__,
+ ) -> None:
+ """
+ Interactive download flow with navigation between code blocks.
+
+ For **multiple blocks**, shows a custom modal (via ``execute``
+ event) with ◀ Prev / Skip ▶ / ✓ Save buttons so the user can
+ freely navigate between code blocks, review the syntax-
+ highlighted preview, rename each file, and choose which to save.
+
+ For a **single block**, uses the simpler built-in ``input``
+ modal since there is nothing to navigate.
+ """
+ total = len(blocks)
+ saved_count = 0
+ saved_files = []
+
+ if total == 1:
+ # ── Single block — use the simpler built-in input modal ──
+ block = blocks[0]
+ preview = self._build_code_preview(block, 1, 1)
+
+ response = await __event_call__(
+ {
+ "type": "input",
+ "data": {
+ "title": "Save Code Block",
+ "message": preview,
+ "placeholder": "Enter filename...",
+ "value": block["filename"],
+ },
+ }
+ )
+
+ if response is not False and response is not None:
+ filename = str(response).strip() or block["filename"]
+ if not filename:
+ filename = block["filename"]
+ if "." in filename:
+ ext = filename.rsplit(".", 1)[-1]
+ else:
+ ext = block["extension"]
+ filename = f"{filename}.{ext}"
+
+ js_code = self._build_single_download_js(block["code"], filename, ext)
+ await __event_emitter__({"type": "execute", "data": {"code": js_code}})
+ saved_count = 1
+ saved_files.append(filename)
+ else:
+ # ── Multiple blocks — custom navigator modal ─────────────
+ # Pre-render all code previews for instant navigation
+ previews = [
+ self._build_code_preview(block, i + 1, total)
+ for i, block in enumerate(blocks)
+ ]
+
+ current = 0
+ while 0 <= current < total:
+ block = blocks[current]
+
+ js_code = self._build_navigator_js(
+ preview_html=previews[current],
+ filename=block["filename"],
+ current=current + 1,
+ total=total,
+ )
+
+ result = await __event_call__(
+ {"type": "execute", "data": {"code": js_code}}
+ )
+
+ # Determine the user's action
+ if isinstance(result, dict):
+ user_action = result.get("action", "done")
+ else:
+ user_action = "done"
+
+ if user_action == "save":
+ filename = (
+ str(result.get("filename", "")).strip() or block["filename"]
+ )
+ if "." in filename:
+ ext = filename.rsplit(".", 1)[-1]
+ else:
+ ext = block["extension"]
+ filename = f"{filename}.{ext}"
+
+ dl_js = self._build_single_download_js(block["code"], filename, ext)
+ await __event_emitter__(
+ {"type": "execute", "data": {"code": dl_js}}
+ )
+
+ saved_count += 1
+ saved_files.append(filename)
+
+ await __event_emitter__(
+ {
+ "type": "status",
+ "data": {
+ "description": f"Saved {filename}",
+ "done": False,
+ },
+ }
+ )
+ current += 1
+
+ elif user_action == "skip":
+ current += 1
+
+ elif user_action == "prev":
+ current = max(0, current - 1)
+
+ else: # "done" or unknown
+ break
+
+ # ── Final status ─────────────────────────────────────────────
+ if saved_count == 0:
+ description = "No code blocks were saved."
+ else:
+ noun = "file" if saved_count == 1 else "files"
+ file_list = ", ".join(saved_files)
+ description = f"Saved {saved_count} {noun}: {file_list}"
+
+ await __event_emitter__(
+ {
+ "type": "status",
+ "data": {"description": description, "done": True},
+ }
+ )
+
+ def _build_navigator_js(
+ self,
+ preview_html: str,
+ filename: str,
+ current: int,
+ total: int,
+ ) -> str:
+ """
+ Build JavaScript that creates a custom modal with navigation
+ buttons (◀ Prev / Skip ▶ / ✓ Save).
+
+ The JS returns a Promise that resolves when the user clicks a
+ button. The resolved value is an object like
+ ``{ action: 'save', filename: '...' }``. The ``execute`` event
+ awaits this Promise and passes the result back to Python via
+ the socket.io acknowledgment callback.
+ """
+ import json
+
+ preview_json = json.dumps(preview_html)
+ filename_json = json.dumps(filename)
+
+ return f"""
+return new Promise(function(resolve) {{
+ var previewHtml = {preview_json};
+ var defaultFilename = {filename_json};
+ var current = {current};
+ var total = {total};
+
+ /* ── Overlay ─────────────────────────────────────────────── */
+ var overlay = document.createElement('div');
+ overlay.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.6);z-index:99999999;display:flex;justify-content:center;align-items:center;opacity:0;transition:opacity 0.1s ease;';
+
+ /* ── Modal ───────────────────────────────────────────────── */
+ var modal = document.createElement('div');
+ modal.style.cssText = 'background:rgba(3,7,18,0.95);border-radius:2rem;max-width:32rem;width:calc(100% - 2rem);max-height:90dvh;display:flex;flex-direction:column;box-shadow:0 25px 50px rgba(0,0,0,0.5);border:1px solid rgb(17,24,39);transform:scale(0.985);opacity:0;transition:transform 0.1s ease,opacity 0.1s ease;';
+ modal.addEventListener('mousedown', function(e) {{ e.stopPropagation(); }});
+ overlay.addEventListener('mousedown', function() {{ finish('done'); }});
+
+ /* ── Title ───────────────────────────────────────────────── */
+ var titleEl = document.createElement('div');
+ titleEl.style.cssText = 'padding:1.5rem 1.75rem 0;font-size:1.125rem;font-weight:500;color:#e5e7eb;';
+ titleEl.textContent = 'Save Code Block (' + current + '/' + total + ')';
+
+ /* ── Code preview ────────────────────────────────────────── */
+ var content = document.createElement('div');
+ content.style.cssText = 'padding:0.75rem 1.75rem 0;overflow-y:auto;flex:1 1 auto;min-height:0;font-size:0.875rem;color:#9ca3af;';
+ content.innerHTML = previewHtml;
+
+ /* ── Filename input ──────────────────────────────────────── */
+ var inputWrap = document.createElement('div');
+ inputWrap.style.cssText = 'padding:0 1.75rem;';
+ var input = document.createElement('input');
+ input.type = 'text';
+ input.value = defaultFilename;
+ input.placeholder = 'Enter filename...';
+ input.style.cssText = 'width:100%;box-sizing:border-box;margin-top:0.75rem;border-radius:0.75rem;padding:0.625rem 1rem;font-size:0.875rem;color:#d1d5db;background:rgb(17,24,39);border:none;outline:none;';
+ inputWrap.appendChild(input);
+
+ /* ── Buttons ─────────────────────────────────────────────── */
+ var btnRow = document.createElement('div');
+ btnRow.style.cssText = 'display:flex;gap:0.375rem;padding:1.5rem 1.75rem;';
+
+ function makeBtn(text, bg, fg) {{
+ var b = document.createElement('button');
+ b.textContent = text;
+ b.style.cssText = 'padding:0.5rem 0;border-radius:1.5rem;border:none;cursor:pointer;font-size:0.875rem;font-weight:500;transition:opacity 0.15s;flex:1;background:' + bg + ';color:' + fg + ';';
+ b.addEventListener('mouseenter', function() {{ b.style.opacity = '0.85'; }});
+ b.addEventListener('mouseleave', function() {{ b.style.opacity = '1'; }});
+ return b;
+ }}
+
+ var prevBtn = makeBtn('\\u25C0 Prev', 'rgb(31,41,55)', '#9ca3af');
+ if (current <= 1) {{
+ prevBtn.disabled = true;
+ prevBtn.style.opacity = '0.3';
+ prevBtn.style.cursor = 'default';
+ }}
+ prevBtn.addEventListener('click', function() {{ if (current > 1) finish('prev'); }});
+
+ var skipBtn = makeBtn('Skip \\u25B6', 'rgb(31,41,55)', '#9ca3af');
+ skipBtn.addEventListener('click', function() {{ finish('skip'); }});
+
+ var saveBtn = makeBtn('\\u2713 Save', 'rgb(243,244,246)', 'rgb(31,41,55)');
+ saveBtn.style.fontWeight = '600';
+ saveBtn.addEventListener('click', function() {{ finish('save'); }});
+
+ btnRow.append(prevBtn, skipBtn, saveBtn);
+ modal.append(titleEl, content, inputWrap, btnRow);
+ overlay.appendChild(modal);
+
+ /* ── Lock body scroll ────────────────────────────────────── */
+ var prevOverflow = document.body.style.overflow;
+ document.body.style.overflow = 'hidden';
+ document.body.appendChild(overlay);
+
+ /* ── Animate in ──────────────────────────────────────────── */
+ requestAnimationFrame(function() {{
+ overlay.style.opacity = '1';
+ modal.style.transform = 'scale(1)';
+ modal.style.opacity = '1';
+ input.focus();
+ input.select();
+ }});
+
+ /* ── Keyboard shortcuts ──────────────────────────────────── */
+ function handleKey(e) {{
+ if (e.key === 'Escape') {{ finish('done'); }}
+ else if (e.key === 'Enter') {{ e.preventDefault(); finish('save'); }}
+ }}
+ document.addEventListener('keydown', handleKey, true);
+
+ /* ── Cleanup and resolve ─────────────────────────────────── */
+ var resolved = false;
+ function finish(action) {{
+ if (resolved) return;
+ resolved = true;
+ document.removeEventListener('keydown', handleKey, true);
+ document.body.style.overflow = prevOverflow || '';
+ overlay.style.opacity = '0';
+ modal.style.transform = 'scale(0.985)';
+ modal.style.opacity = '0';
+ setTimeout(function() {{
+ try {{ document.body.removeChild(overlay); }} catch(e) {{}}
+ resolve({{ action: action, filename: input.value.trim() || defaultFilename }});
+ }}, 120);
+ }}
+}});
+"""
+
+ return indices
+
+ async def _auto_download(
+ self,
+ blocks: list[dict],
+ __event_emitter__,
+ ) -> None:
+ """Download all code blocks immediately without confirmation."""
+ count = len(blocks)
+ file_list = ", ".join(b["filename"] for b in blocks)
+ noun = "file" if count == 1 else "files"
+
+ await __event_emitter__(
+ {
+ "type": "status",
+ "data": {
+ "description": f"Found {count} code {noun}. Downloading: {file_list}",
+ "done": False,
+ },
+ }
+ )
+
+ js_code = self._build_batch_download_js(blocks)
+
+ await __event_emitter__(
+ {
+ "type": "execute",
+ "data": {"code": js_code},
+ }
+ )
+
+ await __event_emitter__(
+ {
+ "type": "status",
+ "data": {
+ "description": f"Downloaded {count} {noun}: {file_list}",
+ "done": True,
+ },
+ }
+ )
+
+ async def action(
+ self,
+ body: dict,
+ __user__=None,
+ __event_emitter__=None,
+ __event_call__=None,
+ ) -> None:
+ """Extract code blocks from the assistant's response and download them."""
+
+ # Resolve effective settings: user valves override admin valves
+ user_valves = (
+ __user__.get("valves") if __user__ and isinstance(__user__, dict) else None
+ )
+
+ auto_download = (
+ user_valves.auto_download if user_valves else self.valves.auto_download
+ )
+ default_filename = (
+ user_valves.default_filename
+ if user_valves
+ else self.valves.default_filename
+ )
+
+ # Temporarily apply the resolved filename for extraction
+ original_filename = self.valves.default_filename
+ self.valves.default_filename = default_filename
+
+ if __event_emitter__:
+ await __event_emitter__(
+ {
+ "type": "status",
+ "data": {
+ "description": "Scanning for code blocks...",
+ "done": False,
+ },
+ }
+ )
+
+ # Get the messages from the body
+ messages = body.get("messages", [])
+
+ if not messages:
+ self.valves.default_filename = original_filename
+ if __event_emitter__:
+ await __event_emitter__(
+ {
+ "type": "status",
+ "data": {
+ "description": "No messages found.",
+ "done": True,
+ },
+ }
+ )
+ return
+
+ # Find the target assistant message.
+ # The action button is attached to a specific message — `body["id"]`
+ # corresponds to the message_id. Walk backwards to find the matching
+ # assistant message.
+ target_message_id = body.get("id")
+ target_content = None
+
+ for msg in reversed(messages):
+ if msg.get("role") == "assistant":
+ # If we can match by id, do so; otherwise take the last assistant msg
+ if target_message_id and msg.get("id") == target_message_id:
+ target_content = msg.get("content", "")
+ break
+ elif not target_content:
+ target_content = msg.get("content", "")
+
+ if not target_content:
+ self.valves.default_filename = original_filename
+ if __event_emitter__:
+ await __event_emitter__(
+ {
+ "type": "status",
+ "data": {
+ "description": "No assistant response found.",
+ "done": True,
+ },
+ }
+ )
+ return
+
+ # Extract code blocks
+ blocks = self._extract_code_blocks(target_content)
+
+ # Restore the original valve value
+ self.valves.default_filename = original_filename
+
+ if not blocks:
+ if __event_emitter__:
+ await __event_emitter__(
+ {
+ "type": "status",
+ "data": {
+ "description": "No code blocks found in the response.",
+ "done": True,
+ },
+ }
+ )
+ return
+
+ # Dispatch to the appropriate mode
+ if auto_download:
+ await self._auto_download(blocks, __event_emitter__)
+ else:
+ if not __event_call__:
+ # Fallback: if __event_call__ isn't available, use auto download
+ await self._auto_download(blocks, __event_emitter__)
+ else:
+ await self._confirm_and_download(
+ blocks, __event_emitter__, __event_call__
+ )
diff --git a/integrations/openwebui-community-plugins/export_to_excel.py b/integrations/openwebui-community-plugins/export_to_excel.py
new file mode 100644
index 0000000..d2e59a1
--- /dev/null
+++ b/integrations/openwebui-community-plugins/export_to_excel.py
@@ -0,0 +1,1552 @@
+"""
+title: Export to Excel
+author: Fu-Jie
+author_url: https://github.com/Fu-Jie/openwebui-extensions
+funding_url: https://github.com/open-webui
+version: 0.3.11
+required_open_webui_version: 0.10.2
+openwebui_id: 244b8f9d-7459-47d6-84d3-c7ae8e3ec710
+icon_url: data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjxwYXRoIGQ9Ik0xNSAySDZhMiAyIDAgMCAwLTIgMnYxNmEyIDIgMCAwIDAgMiAyaDEyYTIgMiAwIDAgMCAyLTJWN1oiLz48cGF0aCBkPSJNMTQgMnY0YTIgMiAwIDAgMCAyIDJoNCIvPjxwYXRoIGQ9Ik04IDEzaDIiLz48cGF0aCBkPSJNMTQgMTNoMiIvPjxwYXRoIGQ9Ik04IDE3aDIiLz48cGF0aCBkPSJNMTQgMTdoMiIvPjwvc3ZnPg==
+description: Extracts tables from chat messages and exports them to Excel (.xlsx) files with smart formatting.
+"""
+
+import os
+import pandas as pd
+import re
+import base64
+from fastapi import FastAPI, HTTPException
+from typing import Optional, Callable, Awaitable, Any, List, Dict
+import datetime
+import asyncio
+from inspect import iscoroutinefunction
+from open_webui.models.chats import Chats
+from open_webui.models.chat_messages import ChatMessages
+from open_webui.models.users import Users
+from open_webui.utils.chat import generate_chat_completion
+from open_webui.utils.misc import convert_output_to_messages
+from pydantic import BaseModel, Field
+from typing import Literal
+
+# ── OpenWebUI version detection for async DB compatibility ──────────
+try:
+ from open_webui.env import VERSION as _owui_version
+except ImportError:
+ _owui_version = "0.0.0"
+
+
+def _owui_version_ge(threshold: str) -> bool:
+ try:
+ v = [int(x) for x in _owui_version.split(".")[:3]]
+ t = [int(x) for x in threshold.split(".")[:3]]
+ return v >= t
+ except (ValueError, TypeError):
+ return False
+
+
+async def _call_db(method, *args, **kwargs):
+ if iscoroutinefunction(method):
+ return await method(*args, **kwargs)
+ res = method(*args, **kwargs)
+ if asyncio.iscoroutine(res):
+ return await res
+ return res
+
+
+app = FastAPI()
+
+
+class Action:
+ class Valves(BaseModel):
+ TITLE_SOURCE: Literal["chat_title", "ai_generated", "markdown_title"] = Field(
+ default="chat_title",
+ description="Title Source: 'chat_title' (Chat Title), 'ai_generated' (AI Generated), 'markdown_title' (Markdown Title)",
+ )
+ SHOW_STATUS: bool = Field(
+ default=True,
+ description="Whether to show operation status updates.",
+ )
+ EXPORT_SCOPE: Literal["last_message", "all_messages"] = Field(
+ default="last_message",
+ description="Export Scope: 'last_message' (Last Message Only), 'all_messages' (All Messages)",
+ )
+ MODEL_ID: str = Field(
+ default="",
+ description="Model ID for AI title generation. Leave empty to use the current chat model.",
+ )
+ SHOW_DEBUG_LOG: bool = Field(
+ default=False,
+ description="Whether to print debug logs in the browser console.",
+ )
+ ROW_HEIGHT: int = Field(
+ default=0,
+ description="Fixed row height in points for data rows. 0 = auto-adjust based on content. Set e.g. 20 for compact single-line rows.",
+ )
+ COLUMN_WIDTH: int = Field(
+ default=0,
+ description="Fixed column width in characters for all data columns. 0 = auto-adjust based on content. Set e.g. 15 for uniform compact columns.",
+ )
+
+ def __init__(self):
+ self.valves = self.Valves()
+
+ async def _emit_status(
+ self,
+ emitter: Optional[Callable[[Any], Awaitable[None]]],
+ description: str,
+ done: bool = False,
+ ):
+ """Emits a status update event."""
+ if self.valves.SHOW_STATUS and emitter:
+ await emitter(
+ {"type": "status", "data": {"description": description, "done": done}}
+ )
+
+ async def _emit_notification(
+ self,
+ emitter: Optional[Callable[[Any], Awaitable[None]]],
+ content: str,
+ ntype: str = "info",
+ ):
+ """Emits a notification event (info, success, warning, error)."""
+ if emitter:
+ await emitter(
+ {"type": "notification", "data": {"type": ntype, "content": content}}
+ )
+
+ async def _emit_debug_log(self, emitter, title: str, data: dict):
+ """Print structured debug logs in the browser console"""
+ if not self.valves.SHOW_DEBUG_LOG or not emitter:
+ return
+
+ try:
+ import json
+
+ js_code = f"""
+ (async function() {{
+ console.group("🛠️ {title}");
+ console.log({json.dumps(data, ensure_ascii=False)});
+ console.groupEnd();
+ }})();
+ """
+
+ await emitter({"type": "execute", "data": {"code": js_code}})
+ except Exception as e:
+ print(f"Error emitting debug log: {e}")
+
+ async def action(
+ self,
+ body: dict,
+ __user__=None,
+ __event_emitter__=None,
+ __event_call__: Optional[Callable[[Any], Awaitable[None]]] = None,
+ __request__: Optional[Any] = None,
+ ):
+ print(f"action:{__name__}")
+ if isinstance(__user__, (list, tuple)):
+ user_language = (
+ __user__[0].get("language", "en-US") if __user__ else "en-US"
+ )
+ user_name = __user__[0].get("name", "User") if __user__[0] else "User"
+ user_id = (
+ __user__[0]["id"]
+ if __user__ and "id" in __user__[0]
+ else "unknown_user"
+ )
+ elif isinstance(__user__, dict):
+ user_language = __user__.get("language", "en-US")
+ user_name = __user__.get("name", "User")
+ user_id = __user__.get("id", "unknown_user")
+
+ if __event_emitter__:
+ await __event_emitter__(
+ {
+ "type": "status",
+ "data": {"description": "Saving to file...", "done": False},
+ }
+ )
+
+ try:
+ messages = body.get("messages", [])
+ if not messages:
+ raise HTTPException(status_code=400, detail="No messages found.")
+
+ # Determine messages to process based on scope
+ target_messages = []
+ if self.valves.EXPORT_SCOPE == "all_messages":
+ target_messages = messages
+ else:
+ target_messages = [messages[-1]]
+
+ chat_ctx = self._get_chat_context(body, None)
+ chat_id = chat_ctx["chat_id"]
+
+ # OWUI 0.10+ stores replies as structured `output` and leaves the flat
+ # `content` empty; recover each target message's text so table
+ # extraction and title generation see it.
+ if chat_id:
+ for msg in target_messages:
+ existing = msg.get("content")
+ if not (isinstance(existing, str) and existing.strip()):
+ recovered = await self._fetch_message_output_text(
+ chat_id, str(msg.get("id") or "")
+ )
+ if recovered:
+ msg["content"] = recovered
+
+ all_tables = []
+ all_sheet_names = []
+
+ # Process messages
+ for msg_index, msg in enumerate(target_messages):
+ content = msg.get("content", "")
+ tables = self.extract_tables_from_message(content)
+
+ if not tables:
+ continue
+
+ # Generate sheet names for this message's tables
+ # If multiple messages, we need to ensure uniqueness across the whole workbook
+ # We'll generate base names here and deduplicate later if needed,
+ # or better: generate unique names on the fly.
+
+ # Extract headers for this message
+ headers = []
+ lines = content.split("\n")
+ for i, line in enumerate(lines):
+ if re.match(r"^#{1,6}\s+", line):
+ headers.append(
+ {
+ "text": re.sub(r"^#{1,6}\s+", "", line).strip(),
+ "line_num": i,
+ }
+ )
+
+ for table_index, table in enumerate(tables):
+ sheet_name = ""
+
+ # 1. Try Markdown Header (closest above)
+ table_start_line = table["start_line"] - 1
+ closest_header_text = None
+ candidate_headers = [
+ h for h in headers if h["line_num"] < table_start_line
+ ]
+ if candidate_headers:
+ closest_header = max(
+ candidate_headers, key=lambda x: x["line_num"]
+ )
+ closest_header_text = closest_header["text"]
+
+ if closest_header_text:
+ sheet_name = self.clean_sheet_name(closest_header_text)
+
+ # 2. AI Generated (Only if explicitly enabled and we have a request object)
+ # Note: Generating titles for EVERY table in all messages might be too slow/expensive.
+ # We'll skip this for 'all_messages' scope to avoid timeout, unless it's just one message.
+ if (
+ not sheet_name
+ and self.valves.TITLE_SOURCE == "ai_generated"
+ and len(target_messages) == 1
+ ):
+ # Logic for AI generation (simplified for now, reusing existing flow if possible)
+ pass
+
+ # 3. Fallback: Message Index
+ if not sheet_name:
+ if len(target_messages) > 1:
+ # Use global message index (from original list if possible, but here we iterate target_messages)
+ # Let's use the loop index.
+ # If multiple tables in one message: "Msg 1 - Table 1"
+ if len(tables) > 1:
+ sheet_name = f"Msg{msg_index+1}-Tab{table_index+1}"
+ else:
+ sheet_name = f"Msg{msg_index+1}"
+ else:
+ # Single message (last_message scope)
+ if len(tables) > 1:
+ sheet_name = f"Table {table_index+1}"
+ else:
+ sheet_name = "Sheet1"
+
+ all_tables.append(table)
+ all_sheet_names.append(sheet_name)
+
+ if not all_tables:
+ raise HTTPException(
+ status_code=400, detail="No tables found in the selected scope."
+ )
+
+ # Deduplicate sheet names
+ final_sheet_names = []
+ seen_names = {}
+ for name in all_sheet_names:
+ base_name = name
+ counter = 1
+ while name in seen_names:
+ name = f"{base_name} ({counter})"
+ counter += 1
+ seen_names[name] = True
+ final_sheet_names.append(name)
+
+ # Notify user about the number of tables found
+ table_count = len(all_tables)
+ if self.valves.EXPORT_SCOPE == "all_messages":
+ await self._emit_notification(
+ __event_emitter__,
+ f"Found {table_count} table(s) in all messages.",
+ "info",
+ )
+ # Wait a moment for user to see the notification before download dialog
+ await asyncio.sleep(1.5)
+ # Generate Workbook Title (Filename)
+ # Use the title of the chat, or the first header of the first message with tables
+ title = ""
+ chat_title = ""
+ if chat_id:
+ chat_title = await self.fetch_chat_title(chat_id, user_id)
+
+ if (
+ self.valves.TITLE_SOURCE == "chat_title"
+ or not self.valves.TITLE_SOURCE
+ ):
+ title = chat_title
+ elif self.valves.TITLE_SOURCE == "ai_generated":
+ # Use AI to generate a title based on message content
+ if target_messages and __request__:
+ # Get content from the first message with tables
+ content_for_title = ""
+ for msg in target_messages:
+ msg_content = msg.get("content", "")
+ if msg_content:
+ content_for_title = msg_content
+ break
+ if content_for_title:
+ title = await self.generate_title_using_ai(
+ body,
+ content_for_title,
+ user_id,
+ __request__,
+ __event_emitter__,
+ )
+ elif self.valves.TITLE_SOURCE == "markdown_title":
+ # Try to find first header in the first message that has content
+ for msg in target_messages:
+ extracted = self.extract_title(msg.get("content", ""))
+ if extracted:
+ title = extracted
+ break
+
+ # Fallback for filename
+ if not title:
+ if chat_title:
+ title = chat_title
+ else:
+ # Try extracting from content again if not already tried
+ if self.valves.TITLE_SOURCE != "markdown_title":
+ for msg in target_messages:
+ extracted = self.extract_title(msg.get("content", ""))
+ if extracted:
+ title = extracted
+ break
+
+ current_datetime = datetime.datetime.now()
+ formatted_date = current_datetime.strftime("%Y%m%d")
+
+ if not title:
+ workbook_name = f"{user_name}_{formatted_date}"
+ else:
+ workbook_name = self.clean_filename(title)
+
+ filename = f"{workbook_name}.xlsx"
+ excel_file_path = os.path.join(
+ "app", "backend", "data", "temp", filename
+ )
+
+ os.makedirs(os.path.dirname(excel_file_path), exist_ok=True)
+
+ # Save tables to Excel
+ self.save_tables_to_excel_enhanced(
+ all_tables, excel_file_path, final_sheet_names
+ )
+
+ # Trigger file download
+ if __event_call__:
+ with open(excel_file_path, "rb") as file:
+ file_content = file.read()
+ base64_blob = base64.b64encode(file_content).decode("utf-8")
+
+ await __event_call__(
+ {
+ "type": "execute",
+ "data": {
+ "code": f"""
+ try {{
+ const base64Data = "{base64_blob}";
+ const binaryData = atob(base64Data);
+ const arrayBuffer = new Uint8Array(binaryData.length);
+ for (let i = 0; i < binaryData.length; i++) {{
+ arrayBuffer[i] = binaryData.charCodeAt(i);
+ }}
+ const blob = new Blob([arrayBuffer], {{ type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }});
+ const filename = "{filename}";
+
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.style.display = "none";
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ URL.revokeObjectURL(url);
+ document.body.removeChild(a);
+ }} catch (error) {{
+ console.error('Error triggering download:', error);
+ }}
+ """
+ },
+ }
+ )
+ await __event_emitter__(
+ {
+ "type": "status",
+ "data": {"description": "File saved", "done": True},
+ }
+ )
+
+ # Clean up temp file
+ if os.path.exists(excel_file_path):
+ os.remove(excel_file_path)
+
+ return {"message": "Download triggered"}
+
+ except HTTPException as e:
+ print(f"Error processing tables: {str(e.detail)}")
+ await __event_emitter__(
+ {
+ "type": "status",
+ "data": {
+ "description": f"Error saving file: {e.detail}",
+ "done": True,
+ },
+ }
+ )
+ await self._emit_notification(
+ __event_emitter__, "No tables found to export!", "error"
+ )
+ raise e
+ except Exception as e:
+ print(f"Error processing tables: {str(e)}")
+ await __event_emitter__(
+ {
+ "type": "status",
+ "data": {
+ "description": f"Error saving file: {str(e)}",
+ "done": True,
+ },
+ }
+ )
+ await self._emit_notification(
+ __event_emitter__, "No tables found to export!", "error"
+ )
+
+ async def generate_title_using_ai(
+ self,
+ body: dict,
+ content: str,
+ user_id: str,
+ request: Any,
+ event_emitter: Callable = None,
+ ) -> str:
+ if not request:
+ return ""
+
+ try:
+ user_obj = await _call_db(Users.get_user_by_id, user_id)
+ # Use configured MODEL_ID or fallback to current chat model
+ model = (
+ self.valves.MODEL_ID.strip()
+ if self.valves.MODEL_ID
+ else body.get("model")
+ )
+
+ payload = {
+ "model": model,
+ "messages": [
+ {
+ "role": "system",
+ "content": "You are a helpful assistant. Generate a short, concise filename (max 10 words) for an Excel export based on the following content. Do not use quotes or file extensions. Avoid special characters that are invalid in filenames. Only output the filename.",
+ },
+ {"role": "user", "content": content[:2000]}, # Limit content length
+ ],
+ "stream": False,
+ }
+
+ # Define the generation task
+ async def generate_task():
+ return await generate_chat_completion(request, payload, user_obj)
+
+ # Define the notification task
+ async def notification_task():
+ # Send initial notification immediately
+ if event_emitter:
+ await self._emit_notification(
+ event_emitter,
+ "AI is generating a filename for your Excel file...",
+ "info",
+ )
+
+ # Subsequent notifications every 5 seconds
+ while True:
+ await asyncio.sleep(5)
+ if event_emitter:
+ await self._emit_notification(
+ event_emitter,
+ "Still generating filename, please be patient...",
+ "info",
+ )
+
+ # Run tasks concurrently
+ gen_future = asyncio.ensure_future(generate_task())
+ notify_future = asyncio.ensure_future(notification_task())
+
+ done, pending = await asyncio.wait(
+ [gen_future, notify_future], return_when=asyncio.FIRST_COMPLETED
+ )
+
+ # Cancel notification task if generation is done
+ if not notify_future.done():
+ notify_future.cancel()
+
+ # Get result
+ if gen_future in done:
+ response = gen_future.result()
+ if response and "choices" in response:
+ return response["choices"][0]["message"]["content"].strip()
+ else:
+ # Should not happen if return_when=FIRST_COMPLETED and we cancel notify
+ await gen_future
+ response = gen_future.result()
+ if response and "choices" in response:
+ return response["choices"][0]["message"]["content"].strip()
+
+ except Exception as e:
+ print(f"Error generating title: {e}")
+ if event_emitter:
+ await self._emit_notification(
+ event_emitter,
+ f"AI title generation failed, using default title. Error: {str(e)}",
+ "warning",
+ )
+
+ return ""
+
+ def extract_title(self, content: str) -> str:
+ """Extract title from Markdown h1/h2 only"""
+ lines = content.split("\n")
+ for line in lines:
+ # Match h1-h2 headings only
+ match = re.match(r"^#{1,2}\s+(.+)$", line.strip())
+ if match:
+ return match.group(1).strip()
+ return ""
+
+ def _get_user_context(self, __user__: Optional[Dict[str, Any]]) -> Dict[str, str]:
+ """Safely extracts user context information."""
+ if isinstance(__user__, (list, tuple)):
+ user_data = __user__[0] if __user__ else {}
+ elif isinstance(__user__, dict):
+ user_data = __user__
+ else:
+ user_data = {}
+
+ return {
+ "user_id": user_data.get("id", "unknown_user"),
+ "user_name": user_data.get("name", "User"),
+ "user_language": user_data.get("language", "en-US"),
+ }
+
+ def _get_chat_context(
+ self, body: dict, __metadata__: Optional[dict] = None
+ ) -> Dict[str, str]:
+ """
+ Unified extraction of chat context information (chat_id, message_id).
+ Prioritizes extraction from body, then metadata.
+ """
+ chat_id = ""
+ message_id = ""
+
+ # 1. Try to get from body
+ if isinstance(body, dict):
+ chat_id = body.get("chat_id", "")
+ message_id = body.get("id", "") # message_id is usually 'id' in body
+
+ # Check body.metadata as fallback
+ if not chat_id or not message_id:
+ body_metadata = body.get("metadata", {})
+ if isinstance(body_metadata, dict):
+ if not chat_id:
+ chat_id = body_metadata.get("chat_id", "")
+ if not message_id:
+ message_id = body_metadata.get("message_id", "")
+
+ # 2. Try to get from __metadata__ (as supplement)
+ if __metadata__ and isinstance(__metadata__, dict):
+ if not chat_id:
+ chat_id = __metadata__.get("chat_id", "")
+ if not message_id:
+ message_id = __metadata__.get("message_id", "")
+
+ return {
+ "chat_id": str(chat_id).strip(),
+ "message_id": str(message_id).strip(),
+ }
+
+ async def fetch_chat_title(self, chat_id: str, user_id: str = "") -> str:
+ """Fetch chat title from database by chat_id"""
+ if not chat_id:
+ return ""
+
+ try:
+ chat = None
+ if user_id:
+ chat = await _call_db(
+ Chats.get_chat_by_id_and_user_id, id=chat_id, user_id=user_id
+ )
+ if not chat:
+ chat = await _call_db(Chats.get_chat_by_id, chat_id)
+ except Exception as exc:
+ print(f"Failed to load chat {chat_id}: {exc}")
+ return ""
+
+ if not chat:
+ return ""
+
+ data = getattr(chat, "chat", {}) or {}
+ title = data.get("title") or getattr(chat, "title", "")
+ return title.strip() if isinstance(title, str) else ""
+
+ def _extract_text_from_output(self, output: Any) -> str:
+ """Rebuild assistant text from structured ``output`` via OWUI's
+ ``convert_output_to_messages`` (reasoning excluded); "" if none."""
+ if not isinstance(output, list) or not output:
+ return ""
+ reconstructed = convert_output_to_messages(output)
+ assistant_texts = [
+ msg["content"]
+ for msg in reconstructed
+ if isinstance(msg, dict)
+ and msg.get("role") == "assistant"
+ and isinstance(msg.get("content"), str)
+ and msg["content"].strip()
+ ]
+ return "\n".join(assistant_texts)
+
+ async def _fetch_message_output_text(self, chat_id: str, message_id: str) -> str:
+ """Assistant text for a message via OWUI's ChatMessages store: its structured
+ ``output`` reconstructed by convert_output_to_messages. "" if not found."""
+ if not chat_id or not message_id:
+ return ""
+ message = await _call_db(
+ ChatMessages.get_message_by_id, f"{chat_id}-{message_id}"
+ )
+ return self._extract_text_from_output(message.output) if message else ""
+
+ def extract_tables_from_message(self, message: str) -> List[Dict]:
+ """
+ Extract Markdown tables and their positions from message text
+ Returns structure: [{
+ "data": table data,
+ "start_line": start line number,
+ "end_line": end line number
+ }]
+ """
+ table_row_pattern = r"^\s*\|.*\|.*\s*$"
+ rows = message.split("\n")
+ tables = []
+ current_table = []
+ start_line = None
+ current_line = 0
+
+ for row in rows:
+ current_line += 1
+ if re.search(table_row_pattern, row):
+ if start_line is None:
+ start_line = current_line # Record table start line
+
+ # Process table row
+ cells = [cell.strip() for cell in row.strip().strip("|").split("|")]
+
+ # Skip separator row
+ is_separator_row = all(re.fullmatch(r"[:\-]+", cell) for cell in cells)
+ if not is_separator_row:
+ current_table.append(cells)
+ elif current_table:
+ # Table ends
+ tables.append(
+ {
+ "data": current_table,
+ "start_line": start_line,
+ "end_line": current_line - 1,
+ }
+ )
+ current_table = []
+ start_line = None
+
+ # Process the last table
+ if current_table:
+ tables.append(
+ {
+ "data": current_table,
+ "start_line": start_line,
+ "end_line": current_line,
+ }
+ )
+
+ return tables
+
+ def generate_names_from_content(self, content: str, tables: List[Dict]) -> tuple:
+ """
+ Generate workbook name and sheet names based on content
+ - Ignore non-empty paragraphs, only use markdown headers (h1-h6).
+ - Single table: Use the closest header as workbook and sheet name.
+ - Multiple tables: Use the first header in the document as workbook name, and closest header for each table as sheet name.
+ - Default naming:
+ - Workbook: Handled in main flow (user_yyyymmdd.xlsx).
+ - Sheet: Sheet1, Sheet2, ...
+ """
+ lines = content.split("\n")
+ workbook_name = ""
+ sheet_names = []
+ all_headers = []
+
+ # 1. Find all h1-h6 headers and their positions
+ for i, line in enumerate(lines):
+ if re.match(r"^#{1,6}\s+", line):
+ all_headers.append(
+ {"text": re.sub(r"^#{1,6}\s+", "", line).strip(), "line_num": i}
+ )
+
+ # 2. Generate sheet name for each table
+ for i, table in enumerate(tables):
+ table_start_line = table["start_line"] - 1 # Convert to 0-based index
+ closest_header_text = None
+
+ # Find closest header above current table
+ candidate_headers = [
+ h for h in all_headers if h["line_num"] < table_start_line
+ ]
+ if candidate_headers:
+ # Find the header with the largest line number among candidates
+ closest_header = max(candidate_headers, key=lambda x: x["line_num"])
+ closest_header_text = closest_header["text"]
+
+ if closest_header_text:
+ # Clean and add found header
+ sheet_names.append(self.clean_sheet_name(closest_header_text))
+ else:
+ # If no header found, use default name "Sheet{i+1}"
+ sheet_names.append(f"Sheet{i+1}")
+
+ # 3. Determine workbook name based on table count
+ if len(tables) == 1:
+ # Single table: Use its sheet name as workbook name (if not default "Sheet1")
+ if sheet_names[0] != "Sheet1":
+ workbook_name = sheet_names[0]
+ elif len(tables) > 1:
+ # Multiple tables: Use the first header in the document as workbook name
+ if all_headers:
+ # Find header with smallest line number
+ first_header = min(all_headers, key=lambda x: x["line_num"])
+ workbook_name = first_header["text"]
+
+ # 4. Clean workbook name (if empty, main flow will use default name)
+ workbook_name = self.clean_filename(workbook_name) if workbook_name else ""
+
+ return workbook_name, sheet_names
+
+ def clean_filename(self, name: str) -> str:
+ """Clean illegal characters and clamp length for filesystem safety."""
+ if not isinstance(name, str):
+ return ""
+ cleaned = re.sub(r'[\\/*?:"<>|]', "", name)
+ cleaned = re.sub(r"\s+", " ", cleaned).strip().strip(".")
+ return cleaned[:50].strip()
+
+ def clean_sheet_name(self, name: str) -> str:
+ """Clean sheet name (limit 31 chars, remove illegal chars)"""
+ name = re.sub(r"[\\/*?[\]:]", "", name).strip()
+ return name[:31] if len(name) > 31 else name
+
+ # ======================== Enhanced Formatting ========================
+
+ def calculate_text_width(self, text: str) -> float:
+ """
+ Calculate text display width, considering CJK characters
+ CJK characters count as 2 units, others as 1 unit
+ """
+ if not text:
+ return 0
+
+ width = 0
+ for char in str(text):
+ # Check if CJK character
+ if "\u4e00" <= char <= "\u9fff" or "\u3000" <= char <= "\u303f":
+ width += 2
+ else:
+ width += 1
+
+ return width
+
+ def calculate_text_height(self, text: str, max_width: int = 50) -> int:
+ """
+ Calculate required lines for text display
+ Based on newlines and text length
+ """
+ if not text:
+ return 1
+
+ text = str(text)
+ # Calculate lines from newlines
+ explicit_lines = text.count("\n") + 1
+
+ # Calculate extra lines from wrapping
+ text_width = self.calculate_text_width(text.replace("\n", ""))
+ wrapped_lines = max(
+ 1, int(text_width / max_width) + (1 if text_width % max_width > 0 else 0)
+ )
+
+ return max(explicit_lines, wrapped_lines)
+
+ def get_column_letter(self, col_index: int) -> str:
+ """
+ Convert column index to Excel column letter (A, B, C, ..., AA, AB, ...)
+ """
+ result = ""
+ while col_index >= 0:
+ result = chr(65 + col_index % 26) + result
+ col_index = col_index // 26 - 1
+ return result
+
+ def determine_content_type(self, header: str, values: list) -> str:
+ """
+ Intelligently determine data type based on header and content
+ Returns: 'number', 'date', 'sequence', 'text'
+ """
+ header_lower = str(header).lower().strip()
+
+ # Check header keywords
+ number_keywords = [
+ "quantity",
+ "amount",
+ "price",
+ "cost",
+ "revenue",
+ "expense",
+ "total",
+ "subtotal",
+ "percentage",
+ "%",
+ "ratio",
+ "rate",
+ "value",
+ "score",
+ "points",
+ ]
+ date_keywords = ["date", "time", "year", "month", "moment"]
+ sequence_keywords = [
+ "no",
+ "no.",
+ "id",
+ "index",
+ "rank",
+ "order",
+ "sequence",
+ "code",
+ ]
+
+ # Check header
+ for keyword in number_keywords:
+ if keyword in header_lower:
+ return "number"
+
+ for keyword in date_keywords:
+ if keyword in header_lower:
+ return "date"
+
+ for keyword in sequence_keywords:
+ if keyword in header_lower:
+ return "sequence"
+
+ # Check data content
+ if not values:
+ return "text"
+
+ sample_values = [
+ str(v).strip() for v in values[:10] if str(v).strip()
+ ] # Use first 10 non-empty values as sample
+ if not sample_values:
+ return "text"
+
+ numeric_count = 0
+ date_count = 0
+ sequence_count = 0
+
+ for value in sample_values:
+ # Check if number
+ try:
+ float(value.replace(",", "").replace("%", ""))
+ numeric_count += 1
+ continue
+ except ValueError:
+ pass
+
+ # Check if date format
+ date_patterns = [
+ r"\d{4}[-/]\d{1,2}[-/]\d{1,2}",
+ r"\d{1,2}[-/]\d{1,2}[-/]\d{4}",
+ r"\d{4}\d{2}\d{2}",
+ ]
+ for pattern in date_patterns:
+ if re.match(pattern, value):
+ date_count += 1
+ break
+
+ # Check if sequence format
+ if (
+ re.match(r"^\d+$", value) and len(value) <= 4
+ ): # Pure digits and <= 4 chars, likely sequence
+ sequence_count += 1
+
+ total_count = len(sample_values)
+
+ # Determine type based on ratio
+ if numeric_count / total_count >= 0.7:
+ return "number"
+ elif date_count / total_count >= 0.7:
+ return "date"
+ elif sequence_count / total_count >= 0.8 and sequence_count > 2:
+ return "sequence"
+ else:
+ return "text"
+
+ def save_tables_to_excel_enhanced(
+ self, tables: List[Dict], file_path: str, sheet_names: List[str]
+ ):
+ """
+ Enhanced Excel saving function with standard formatting
+ """
+ try:
+ with pd.ExcelWriter(file_path, engine="xlsxwriter") as writer:
+ workbook = writer.book
+
+ # OpenWebUI-style theme colors
+ HEADER_BG = "#1f2937" # Dark gray (matches OpenWebUI sidebar)
+ HEADER_FG = "#ffffff" # White text
+ ROW_ODD_BG = "#ffffff" # White for odd rows
+ ROW_EVEN_BG = "#f3f4f6" # Light gray for even rows (zebra striping)
+ BORDER_COLOR = "#e5e7eb" # Light border
+
+ # Define header style - Center aligned
+ header_format = workbook.add_format(
+ {
+ "bold": True,
+ "font_size": 11,
+ "font_name": "Arial",
+ "font_color": HEADER_FG,
+ "bg_color": HEADER_BG,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "align": "center",
+ "valign": "vcenter",
+ "text_wrap": True,
+ }
+ )
+
+ # Text cell style - Left aligned (odd rows)
+ text_format = workbook.add_format(
+ {
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_ODD_BG,
+ "align": "left",
+ "valign": "vcenter",
+ "text_wrap": True,
+ }
+ )
+
+ # Text cell style - Left aligned (even rows - zebra)
+ text_format_alt = workbook.add_format(
+ {
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_EVEN_BG,
+ "align": "left",
+ "valign": "vcenter",
+ "text_wrap": True,
+ }
+ )
+
+ # Number cell style - Right aligned
+ number_format = workbook.add_format(
+ {
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_ODD_BG,
+ "align": "right",
+ "valign": "vcenter",
+ }
+ )
+
+ number_format_alt = workbook.add_format(
+ {
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_EVEN_BG,
+ "align": "right",
+ "valign": "vcenter",
+ }
+ )
+
+ # Integer format - Right aligned
+ integer_format = workbook.add_format(
+ {
+ "num_format": "0",
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_ODD_BG,
+ "align": "right",
+ "valign": "vcenter",
+ }
+ )
+
+ integer_format_alt = workbook.add_format(
+ {
+ "num_format": "0",
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_EVEN_BG,
+ "align": "right",
+ "valign": "vcenter",
+ }
+ )
+
+ # Decimal format - Right aligned
+ decimal_format = workbook.add_format(
+ {
+ "num_format": "0.00",
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_ODD_BG,
+ "align": "right",
+ "valign": "vcenter",
+ }
+ )
+
+ decimal_format_alt = workbook.add_format(
+ {
+ "num_format": "0.00",
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_EVEN_BG,
+ "align": "right",
+ "valign": "vcenter",
+ }
+ )
+
+ # Date format - Center aligned
+ date_format = workbook.add_format(
+ {
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_ODD_BG,
+ "align": "center",
+ "valign": "vcenter",
+ "text_wrap": True,
+ }
+ )
+
+ date_format_alt = workbook.add_format(
+ {
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_EVEN_BG,
+ "align": "center",
+ "valign": "vcenter",
+ "text_wrap": True,
+ }
+ )
+
+ # Sequence format - Center aligned
+ sequence_format = workbook.add_format(
+ {
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_ODD_BG,
+ "align": "center",
+ "valign": "vcenter",
+ }
+ )
+
+ sequence_format_alt = workbook.add_format(
+ {
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_EVEN_BG,
+ "align": "center",
+ "valign": "vcenter",
+ }
+ )
+
+ # Bold cell style (for full cell bolding)
+ text_bold_format = workbook.add_format(
+ {
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_ODD_BG,
+ "align": "left",
+ "valign": "vcenter",
+ "text_wrap": True,
+ "bold": True,
+ }
+ )
+
+ text_bold_format_alt = workbook.add_format(
+ {
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_EVEN_BG,
+ "align": "left",
+ "valign": "vcenter",
+ "text_wrap": True,
+ "bold": True,
+ }
+ )
+
+ # Italic cell style (for full cell italics)
+ text_italic_format = workbook.add_format(
+ {
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_ODD_BG,
+ "align": "left",
+ "valign": "vcenter",
+ "text_wrap": True,
+ "italic": True,
+ }
+ )
+
+ text_italic_format_alt = workbook.add_format(
+ {
+ "font_name": "Arial",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": ROW_EVEN_BG,
+ "align": "left",
+ "valign": "vcenter",
+ "text_wrap": True,
+ "italic": True,
+ }
+ )
+
+ # Code cell style (for inline code with highlight background)
+ CODE_BG = "#f0f0f0" # Light gray background for code
+ text_code_format = workbook.add_format(
+ {
+ "font_name": "Consolas",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": CODE_BG,
+ "align": "left",
+ "valign": "vcenter",
+ "text_wrap": True,
+ }
+ )
+
+ text_code_format_alt = workbook.add_format(
+ {
+ "font_name": "Consolas",
+ "font_size": 10,
+ "border": 1,
+ "border_color": BORDER_COLOR,
+ "bg_color": CODE_BG,
+ "align": "left",
+ "valign": "vcenter",
+ "text_wrap": True,
+ }
+ )
+
+ for i, table in enumerate(tables):
+ try:
+ table_data = table["data"]
+ if not table_data or len(table_data) < 1:
+ print(f"Skipping empty table at index {i}")
+ continue
+
+ print(f"Processing table {i+1} with {len(table_data)} rows")
+
+ # Get sheet name
+ sheet_name = (
+ sheet_names[i] if i < len(sheet_names) else f"Sheet{i+1}"
+ )
+
+ # Create DataFrame
+ headers = [
+ str(cell).strip()
+ for cell in table_data[0]
+ if str(cell).strip()
+ ]
+ if not headers:
+ print(f"Warning: No valid headers found for table {i+1}")
+ headers = [f"Col{j+1}" for j in range(len(table_data[0]))]
+
+ data_rows = []
+ if len(table_data) > 1:
+ max_cols = len(headers)
+ for row in table_data[1:]:
+ processed_row = []
+ for j in range(max_cols):
+ if j < len(row):
+ processed_row.append(str(row[j]))
+ else:
+ processed_row.append("")
+ data_rows.append(processed_row)
+ df = pd.DataFrame(data_rows, columns=headers)
+ else:
+ df = pd.DataFrame(columns=headers)
+
+ print(f"DataFrame created with columns: {list(df.columns)}")
+
+ # Smart data type conversion using pandas infer_objects
+ for col in df.columns:
+ # Try numeric conversion first
+ try:
+ df[col] = pd.to_numeric(df[col])
+ except (ValueError, TypeError):
+ # Try datetime conversion
+ try:
+ df[col] = pd.to_datetime(df[col], errors="raise")
+ except (ValueError, TypeError):
+ # Keep as string, use infer_objects for optimization
+ df[col] = df[col].infer_objects()
+
+ # Write data first (without header)
+ df.to_excel(
+ writer,
+ sheet_name=sheet_name,
+ index=False,
+ header=False,
+ startrow=1,
+ )
+ worksheet = writer.sheets[sheet_name]
+
+ # Apply enhanced formatting with zebra striping
+ formats = {
+ "header": header_format,
+ "text": [text_format, text_format_alt],
+ "number": [number_format, number_format_alt],
+ "integer": [integer_format, integer_format_alt],
+ "decimal": [decimal_format, decimal_format_alt],
+ "date": [date_format, date_format_alt],
+ "sequence": [sequence_format, sequence_format_alt],
+ "bold": [text_bold_format, text_bold_format_alt],
+ "italic": [text_italic_format, text_italic_format_alt],
+ "code": [text_code_format, text_code_format_alt],
+ }
+ self.apply_enhanced_formatting(
+ worksheet,
+ df,
+ headers,
+ workbook,
+ formats,
+ row_height=self.valves.ROW_HEIGHT,
+ column_width=self.valves.COLUMN_WIDTH,
+ )
+
+ except Exception as e:
+ print(f"Error processing table {i+1}: {str(e)}")
+ continue
+
+ except Exception as e:
+ print(f"Error saving Excel file: {str(e)}")
+ raise
+
+ def apply_enhanced_formatting(
+ self,
+ worksheet,
+ df,
+ headers,
+ workbook,
+ formats,
+ row_height: int = 0,
+ column_width: int = 0,
+ ):
+ """
+ Apply enhanced formatting with zebra striping
+ - Header: Center aligned (dark background)
+ - Number: Right aligned
+ - Text: Left aligned
+ - Date: Center aligned
+ - Sequence: Center aligned
+ - Zebra striping: alternating row colors
+ - Supports full cell Markdown bold (**text**) and italic (*text*)
+ - row_height: Fixed row height in points. 0 = auto-adjust based on content.
+ - column_width: Fixed column width in characters. 0 = auto-adjust based on content.
+ """
+ try:
+ # Extract format from formats dict
+ header_format = formats["header"]
+
+ # 1. Write headers (Center aligned)
+ print(f"Writing headers with enhanced alignment: {headers}")
+ for col_idx, header in enumerate(headers):
+ if header and str(header).strip():
+ worksheet.write(0, col_idx, str(header).strip(), header_format)
+ else:
+ default_header = f"Col{col_idx+1}"
+ worksheet.write(0, col_idx, default_header, header_format)
+
+ # 2. Analyze column types
+ column_types = {}
+ for col_idx, column in enumerate(headers):
+ if col_idx < len(df.columns):
+ column_values = df.iloc[:, col_idx].tolist()
+ column_types[col_idx] = self.determine_content_type(
+ column, column_values
+ )
+ print(
+ f"Column '{column}' determined as type: {column_types[col_idx]}"
+ )
+ else:
+ column_types[col_idx] = "text"
+
+ # 3. Write and format data with zebra striping
+ for row_idx, row in df.iterrows():
+ # Determine if odd or even row (0-indexed, so row 0 is odd visually as row 1)
+ is_alt_row = (
+ row_idx % 2 == 1
+ ) # Even index = odd visual row, use alt format
+
+ for col_idx, value in enumerate(row):
+ content_type = column_types.get(col_idx, "text")
+
+ # Select format based on content type and zebra striping
+ fmt_idx = 1 if is_alt_row else 0
+
+ if content_type == "number":
+ # Number - Right aligned
+ if pd.api.types.is_numeric_dtype(df.iloc[:, col_idx]):
+ if pd.api.types.is_integer_dtype(df.iloc[:, col_idx]):
+ current_format = formats["integer"][fmt_idx]
+ else:
+ try:
+ numeric_value = float(value)
+ if numeric_value.is_integer():
+ current_format = formats["integer"][fmt_idx]
+ value = int(numeric_value)
+ else:
+ current_format = formats["decimal"][fmt_idx]
+ except (ValueError, TypeError):
+ current_format = formats["decimal"][fmt_idx]
+ else:
+ current_format = formats["number"][fmt_idx]
+
+ elif content_type == "date":
+ # Date - Center aligned
+ current_format = formats["date"][fmt_idx]
+
+ elif content_type == "sequence":
+ # Sequence - Center aligned
+ current_format = formats["sequence"][fmt_idx]
+
+ else:
+ # Text - Left aligned
+ current_format = formats["text"][fmt_idx]
+
+ if content_type == "text" and isinstance(value, str):
+ # Check for full cell bold (**text**)
+ match_bold = re.fullmatch(r"\*\*(.+)\*\*", value.strip())
+ # Check for full cell italic (*text*)
+ match_italic = re.fullmatch(r"\*(.+)\*", value.strip())
+ # Check for full cell code (`text`)
+ match_code = re.fullmatch(r"`(.+)`", value.strip())
+
+ if match_bold:
+ # Extract content and apply bold format
+ clean_value = match_bold.group(1)
+ worksheet.write(
+ row_idx + 1,
+ col_idx,
+ clean_value,
+ formats["bold"][fmt_idx],
+ )
+ elif match_italic:
+ # Extract content and apply italic format
+ clean_value = match_italic.group(1)
+ worksheet.write(
+ row_idx + 1,
+ col_idx,
+ clean_value,
+ formats["italic"][fmt_idx],
+ )
+ elif match_code:
+ # Extract content and apply code format (highlighted)
+ clean_value = match_code.group(1)
+ worksheet.write(
+ row_idx + 1,
+ col_idx,
+ clean_value,
+ formats["code"][fmt_idx],
+ )
+ else:
+ # Remove partial markdown formatting symbols (can't render partial formatting in Excel)
+ # Remove bold markers **text** -> text
+ clean_value = re.sub(r"\*\*(.+?)\*\*", r"\1", value)
+ # Remove italic markers *text* -> text (but not inside **)
+ clean_value = re.sub(
+ r"(? text
+ clean_value = re.sub(r"`(.+?)`", r"\1", clean_value)
+ worksheet.write(
+ row_idx + 1, col_idx, clean_value, current_format
+ )
+ else:
+ worksheet.write(row_idx + 1, col_idx, value, current_format)
+
+ # 4. Column width
+ if column_width > 0:
+ # Fixed column width mode
+ for col_idx in range(len(headers)):
+ col_letter = self.get_column_letter(col_idx)
+ worksheet.set_column(f"{col_letter}:{col_letter}", column_width)
+ else:
+ # Auto-adjust column width based on content
+ for col_idx, column in enumerate(headers):
+ col_letter = self.get_column_letter(col_idx)
+
+ # Calculate header width
+ header_width = self.calculate_text_width(str(column))
+
+ # Calculate max data width
+ max_data_width = 0
+ if not df.empty and col_idx < len(df.columns):
+ for value in df.iloc[:, col_idx]:
+ value_width = self.calculate_text_width(str(value))
+ max_data_width = max(max_data_width, value_width)
+
+ # Base width
+ base_width = max(header_width, max_data_width)
+
+ # Adjust width based on type
+ content_type = column_types.get(col_idx, "text")
+ if content_type == "sequence":
+ optimal_width = max(8, min(15, base_width + 2))
+ elif content_type == "number":
+ optimal_width = max(12, min(25, base_width + 3))
+ elif content_type == "date":
+ optimal_width = max(15, min(20, base_width + 2))
+ else:
+ if base_width <= 10:
+ optimal_width = base_width + 3
+ elif base_width <= 20:
+ optimal_width = base_width + 4
+ else:
+ optimal_width = base_width + 5
+ optimal_width = max(10, min(60, optimal_width))
+
+ worksheet.set_column(f"{col_letter}:{col_letter}", optimal_width)
+
+ # 5. Row height
+ worksheet.set_row(0, 35)
+
+ if row_height > 0:
+ # Fixed row height mode
+ for row_idx in range(len(df)):
+ worksheet.set_row(row_idx + 1, row_height)
+ else:
+ # Auto-adjust row height based on content
+ for row_idx, row in df.iterrows():
+ max_row_height = 20
+
+ for col_idx, value in enumerate(row):
+ if col_idx < len(headers):
+ col_width = min(
+ 60,
+ max(
+ 10,
+ self.calculate_text_width(str(headers[col_idx]))
+ + 5,
+ ),
+ )
+ else:
+ col_width = 15
+
+ cell_lines = self.calculate_text_height(str(value), col_width)
+ cell_height = cell_lines * 20
+
+ max_row_height = max(max_row_height, cell_height)
+
+ final_height = min(120, max_row_height)
+ worksheet.set_row(row_idx + 1, final_height)
+
+ print(f"Successfully applied enhanced formatting")
+
+ except Exception as e:
+ print(f"Warning: Failed to apply enhanced formatting: {str(e)}")
+ self.apply_basic_formatting_fallback(worksheet, df)
+
+ def apply_basic_formatting_fallback(self, worksheet, df):
+ """
+ Basic formatting fallback
+ """
+ try:
+ for i, column in enumerate(df.columns):
+ column_width = (
+ max(
+ len(str(column)),
+ (df[column].astype(str).map(len).max() if not df.empty else 0),
+ )
+ + 2
+ )
+
+ col_letter = self.get_column_letter(i)
+ worksheet.set_column(
+ f"{col_letter}:{col_letter}", min(60, max(10, column_width))
+ )
+
+ except Exception as e:
+ print(f"Error in basic formatting: {str(e)}")
+
+ except Exception as e:
+ print(f"Error in basic formatting: {str(e)}")
diff --git a/integrations/openwebui-community-plugins/export_to_word.py b/integrations/openwebui-community-plugins/export_to_word.py
new file mode 100644
index 0000000..1eb4b98
--- /dev/null
+++ b/integrations/openwebui-community-plugins/export_to_word.py
@@ -0,0 +1,3436 @@
+"""
+title: Export to Word Enhanced
+author: Fu-Jie
+author_url: https://github.com/Fu-Jie/openwebui-extensions
+funding_url: https://github.com/open-webui
+version: 0.5.3
+required_open_webui_version: 0.10.2
+openwebui_id: fca6a315-2a45-42cc-8c96-55cbc85f87f2
+icon_url: data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNNiAyMmEyIDIgMCAwIDEtMi0yVjRhMiAyIDAgMCAxIDItMmg4YTIuNCAyLjQgMCAwIDEgMS43MDQuNzA2bDMuNTg4IDMuNTg4QTIuNCAyLjQgMCAwIDEgMjAgOHYxMmEyIDIgMCAwIDEtMiAyeiIgLz4KICA8cGF0aCBkPSJNMTQgMnY1YTEgMSAwIDAgMCAxIDFoNSIgLz4KICA8cGF0aCBkPSJNMTAgOUg4IiAvPgogIDxwYXRoIGQ9Ik0xNiAxM0g4IiAvPgogIDxwYXRoIGQ9Ik0xNiAxN0g4IiAvPgo8L3N2Zz4K
+requirements: python-docx, Pygments, latex2mathml, mathml2omml
+description: Export current conversation from Markdown to Word (.docx) with Mermaid diagrams rendered client-side (Mermaid.js, SVG+PNG), LaTeX math, real hyperlinks, improved tables, syntax highlighting, and blockquote support.
+notes: Added i18n support, configurable fonts/colors, and parallel PNG rendering optimization.
+"""
+
+from __future__ import annotations
+
+import re
+import base64
+import datetime
+import time
+import io
+import asyncio
+from inspect import iscoroutinefunction
+import logging
+import hashlib
+import struct
+import zlib
+import binascii
+from pathlib import Path
+from dataclasses import dataclass
+from typing import Optional, Callable, Awaitable, Any, List, Tuple, Dict, cast
+from urllib.parse import quote
+from docx import Document
+from docx.shared import Pt, Inches, RGBColor, Cm
+from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
+from docx.enum.table import WD_TABLE_ALIGNMENT
+from docx.enum.style import WD_STYLE_TYPE
+from docx.opc.constants import RELATIONSHIP_TYPE as RT
+from docx.oxml import parse_xml
+from docx.oxml.ns import qn, nsmap
+from docx.oxml import OxmlElement
+from open_webui.models.chats import Chats
+from open_webui.models.chat_messages import ChatMessages
+from open_webui.models.users import Users
+from open_webui.storage.provider import Storage
+from open_webui.retrieval.web.utils import get_ssrf_safe_session, validate_url
+from open_webui.utils.chat import generate_chat_completion
+
+# OWUI 0.10+ stores replies as structured `output`; rebuilds text (reasoning excluded). Requires >= 0.10.2.
+from open_webui.utils.misc import convert_output_to_messages
+from pydantic import BaseModel, Field
+
+# Files are used to embed internal /api/v1/files//content images.
+try:
+ from open_webui.models.files import Files # type: ignore
+except Exception: # pragma: no cover - depends on host Open WebUI runtime
+ Files = None
+
+# Pygments for syntax highlighting
+try:
+ from pygments import lex
+ from pygments.lexers import get_lexer_by_name, TextLexer
+ from pygments.token import Token
+
+ PYGMENTS_AVAILABLE = True
+except ImportError:
+ PYGMENTS_AVAILABLE = False
+
+try:
+ from latex2mathml.converter import convert as latex_to_mathml
+ import mathml2omml
+
+ LATEX_MATH_AVAILABLE = True
+except Exception:
+ LATEX_MATH_AVAILABLE = False
+
+
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
+)
+logger = logging.getLogger(__name__)
+
+# ── OpenWebUI version detection for async DB compatibility ──────────
+try:
+ from open_webui.env import VERSION as _owui_version
+except ImportError:
+ _owui_version = "0.0.0"
+
+
+def _owui_version_ge(threshold: str) -> bool:
+ try:
+ v = [int(x) for x in _owui_version.split(".")[:3]]
+ t = [int(x) for x in threshold.split(".")[:3]]
+ return v >= t
+ except (ValueError, TypeError):
+ return False
+
+
+async def _call_db(method, *args, **kwargs):
+ if iscoroutinefunction(method):
+ return await method(*args, **kwargs)
+ res = method(*args, **kwargs)
+ if asyncio.iscoroutine(res):
+ return await res
+ return res
+
+
+_AUTO_URL_RE = re.compile(r"(?:https?://|www\.)[^\s<>()]+")
+_DATA_IMAGE_URL_RE = re.compile(
+ r"^data:(?Pimage/[a-z0-9.+-]+)\s*;\s*base64\s*,\s*(?P.*)$",
+ re.IGNORECASE | re.DOTALL,
+)
+_OWUI_API_FILE_ID_RE = re.compile(
+ r"/api/v1/files/(?P[A-Za-z0-9-]+)(?:/content)?(?:[/?#]|$)",
+ re.IGNORECASE,
+)
+_CURRENCY_NUMBER_RE = re.compile(r"^\d[\d,]*(?:\.\d+)?$")
+
+_TRANSPARENT_1PX_PNG = base64.b64decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABDQottAAAAABJRU5ErkJggg=="
+)
+
+_ASVG_NS = "http://schemas.microsoft.com/office/drawing/2016/SVG/main"
+nsmap.setdefault("asvg", _ASVG_NS)
+
+_ALL_DETAILS_RE = re.compile(
+ r"]*>.*? ", re.IGNORECASE | re.DOTALL
+)
+_THINK_RE = re.compile(r"]*>.*? ", re.IGNORECASE | re.DOTALL)
+_ANALYSIS_RE = re.compile(
+ r"]*>.*? ", re.IGNORECASE | re.DOTALL
+)
+# Markdown reference-definition lines (`[label]: target`) render invisibly, so they
+# must be stripped from the export. Same pattern OpenWebUI uses in removeFormattings()
+# — src/lib/utils/index.ts: `/^\[[^\]]+\]:\s*.*$/gm`.
+_MD_REFERENCE_DEF_RE = re.compile(r"^\[[^\]]+\]:\s*.*$\n?", re.MULTILINE)
+# Markdown image URL:  with optional <...> wrapping — captures the URL.
+_MD_IMAGE_URL_RE = re.compile(r"!\[[^\]]*\]\(\s*([^)>\s]+)")
+
+
+@dataclass(frozen=True)
+class _CitationRef:
+ idx: int
+ anchor: str
+ title: str
+ url: Optional[str]
+ source_id: str
+
+
+class Action:
+ # Internationalization message dictionaries
+ _I18N_MESSAGES: Dict[str, Dict[str, str]] = {
+ "en": {
+ "converting": "Converting to Word document...",
+ "exported": "Word document exported",
+ "success": "Successfully exported to {filename}",
+ "error_no_content": "No content found to export!",
+ "error_export": "Error exporting Word document: {error}",
+ "export_failed": "Export failed: {error}",
+ "figure_prefix": "Figure",
+ "references": "References",
+ },
+ "zh": {
+ "converting": "正在转换为 Word 文档...",
+ "exported": "Word 文档导出完成",
+ "success": "成功导出至 {filename}",
+ "error_no_content": "没有找到可导出的内容!",
+ "error_export": "导出 Word 文档时出错: {error}",
+ "export_failed": "导出失败: {error}",
+ "figure_prefix": "图",
+ "references": "参考文献",
+ },
+ }
+
+ class Valves(BaseModel):
+ TITLE_SOURCE: str = Field(
+ default="chat_title",
+ description="Title Source: 'chat_title' (Chat Title), 'ai_generated' (AI Generated), 'markdown_title' (Markdown Title)",
+ )
+ SHOW_STATUS: bool = Field(
+ default=True,
+ description="Whether to show operation status updates.",
+ )
+ SHOW_DEBUG_LOG: bool = Field(
+ default=False,
+ description="Whether to print debug logs in the browser console.",
+ )
+
+ MAX_EMBED_IMAGE_MB: int = Field(
+ default=20,
+ description="Maximum image size to embed into DOCX (MB). Applies to data URLs and /api/v1/files//content images.",
+ )
+ EMBED_EXTERNAL_IMAGES: bool = Field(
+ default=False,
+ description="Download and embed images from external http(s) URLs, capped by MAX_EMBED_IMAGE_MB. Unfetchable images show a placeholder instead.",
+ )
+
+ # Font configuration
+ FONT_LATIN: str = Field(
+ default="Times New Roman",
+ description="Font for Latin characters (e.g., 'Times New Roman', 'Calibri', 'Arial')",
+ )
+ FONT_ASIAN: str = Field(
+ default="SimSun",
+ description="Font for Asian characters (e.g., 'SimSun', 'Microsoft YaHei', 'PingFang SC')",
+ )
+ FONT_CODE: str = Field(
+ default="Consolas",
+ description="Font for code blocks and inline code (e.g., 'Consolas', 'Courier New', 'Monaco')",
+ )
+ FONT_H1_LATIN: str = Field(
+ default="Aptos Display",
+ description="Font for Heading 1 Latin characters (e.g., 'Aptos Display', 'Calibri Light'). Empty uses FONT_LATIN.",
+ )
+ FONT_H1_ASIAN: str = Field(
+ default="SimHei",
+ description="Font for Heading 1 Asian characters (e.g., 'SimHei', 'Microsoft YaHei'). Empty uses FONT_ASIAN.",
+ )
+ FONT_H2_LATIN: str = Field(
+ default="Calibri Light",
+ description="Font for Heading 2 Latin characters (e.g., 'Aptos Display', 'Calibri Light'). Empty uses FONT_LATIN.",
+ )
+ FONT_H2_ASIAN: str = Field(
+ default="SimHei",
+ description="Font for Heading 2 Asian characters (e.g., 'SimHei', 'Microsoft YaHei'). Empty uses FONT_ASIAN.",
+ )
+
+ # Title alignment
+ TITLE_ALIGNMENT: str = Field(
+ default="center",
+ description="Title alignment: 'left', 'center', or 'right'",
+ )
+
+ # Table styling
+ TABLE_HEADER_COLOR: str = Field(
+ default="F2F2F2",
+ description="Table header background color (hex, without #)",
+ )
+ TABLE_ZEBRA_COLOR: str = Field(
+ default="FBFBFB",
+ description="Table zebra stripe background color for alternate rows (hex, without #)",
+ )
+
+ MERMAID_JS_URL: str = Field(
+ default="https://cdn.jsdelivr.net/npm/mermaid@11.12.2/dist/mermaid.min.js",
+ description="Mermaid JS CDN URL",
+ )
+ MERMAID_JSZIP_URL: str = Field(
+ default="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js",
+ description="JSZip CDN URL (DOCX manipulation)",
+ )
+ MERMAID_PNG_SCALE: float = Field(
+ default=3.0,
+ description="PNG render resolution multiplier (higher = clearer, larger file)",
+ )
+ MERMAID_DISPLAY_SCALE: float = Field(
+ default=1.0,
+ description="Diagram width relative to available page width (<=1 recommended)",
+ )
+ MERMAID_OPTIMIZE_LAYOUT: bool = Field(
+ default=False,
+ description="Optimize Mermaid layout: convert LR to TD for graph/flowchart",
+ )
+ MERMAID_BACKGROUND: str = Field(
+ default="",
+ description="Mermaid background color. Empty = transparent (recommended for Word dark mode). Used only for optional PNG fill.",
+ )
+
+ MERMAID_CAPTIONS_ENABLE: bool = Field(
+ default=True,
+ description="Add figure captions under Mermaid images/charts",
+ )
+ MERMAID_CAPTION_STYLE: str = Field(
+ default="Caption",
+ description="Paragraph style name for Mermaid captions (uses 'Caption' if available, otherwise creates a safe custom style)",
+ )
+ MERMAID_CAPTION_PREFIX: str = Field(
+ default="",
+ description="Caption prefix label (e.g., 'Figure' or '图'). Empty = auto-detect based on user language.",
+ )
+
+ MATH_ENABLE: bool = Field(
+ default=True,
+ description="Enable LaTeX math block conversion (\\[...\\] and $$...$$) into Word equations",
+ )
+ MATH_INLINE_DOLLAR_ENABLE: bool = Field(
+ default=True,
+ description="Enable inline $...$ math conversion into Word equations (conservative parsing to reduce false positives)",
+ )
+
+ # Language configuration
+ UI_LANGUAGE: str = Field(
+ default="en",
+ description="UI language for export messages. Options: 'en' (English), 'zh' (Chinese)",
+ )
+
+ class UserValves(BaseModel):
+ TITLE_SOURCE: Optional[str] = Field(
+ default=None,
+ description="Title Source: 'chat_title' (Chat Title), 'ai_generated' (AI Generated), 'markdown_title' (Markdown Title)",
+ )
+ UI_LANGUAGE: Optional[str] = Field(
+ default=None,
+ description="UI language for export messages. Options: 'en' (English), 'zh' (Chinese)",
+ )
+ FONT_LATIN: Optional[str] = Field(
+ default=None,
+ description="Font for Latin characters (e.g., 'Times New Roman', 'Calibri', 'Arial')",
+ )
+ FONT_ASIAN: Optional[str] = Field(
+ default=None,
+ description="Font for Asian characters (e.g., 'SimSun', 'Microsoft YaHei', 'PingFang SC')",
+ )
+ FONT_CODE: Optional[str] = Field(
+ default=None,
+ description="Font for code blocks and inline code (e.g., 'Consolas', 'Courier New', 'Monaco')",
+ )
+ FONT_H1_LATIN: Optional[str] = Field(
+ default=None,
+ description="Font for Heading 1 Latin characters (e.g., 'Aptos Display', 'Calibri Light'). Empty uses FONT_LATIN.",
+ )
+ FONT_H1_ASIAN: Optional[str] = Field(
+ default=None,
+ description="Font for Heading 1 Asian characters (e.g., 'SimHei', 'Microsoft YaHei'). Empty uses FONT_ASIAN.",
+ )
+ FONT_H2_LATIN: Optional[str] = Field(
+ default=None,
+ description="Font for Heading 2 Latin characters (e.g., 'Aptos Display', 'Calibri Light'). Empty uses FONT_LATIN.",
+ )
+ FONT_H2_ASIAN: Optional[str] = Field(
+ default=None,
+ description="Font for Heading 2 Asian characters (e.g., 'SimHei', 'Microsoft YaHei'). Empty uses FONT_ASIAN.",
+ )
+ TABLE_HEADER_COLOR: Optional[str] = Field(
+ default=None,
+ description="Table header background color (hex, without #)",
+ )
+ TABLE_ZEBRA_COLOR: Optional[str] = Field(
+ default=None,
+ description="Table zebra stripe background color for alternate rows (hex, without #)",
+ )
+ MERMAID_PNG_SCALE: Optional[float] = Field(
+ default=None,
+ description="PNG render resolution multiplier (higher = clearer, larger file)",
+ )
+ MERMAID_DISPLAY_SCALE: Optional[float] = Field(
+ default=None,
+ description="Diagram width relative to available page width (<=1 recommended)",
+ )
+ MERMAID_OPTIMIZE_LAYOUT: Optional[bool] = Field(
+ default=None,
+ description="Optimize Mermaid layout: convert LR to TD for graph/flowchart",
+ )
+ MERMAID_BACKGROUND: Optional[str] = Field(
+ default=None,
+ description="Mermaid background color. Empty = transparent (recommended for Word dark mode). Used only for optional PNG fill.",
+ )
+ MERMAID_CAPTIONS_ENABLE: Optional[bool] = Field(
+ default=None,
+ description="Add figure captions under Mermaid images/charts",
+ )
+ MATH_ENABLE: Optional[bool] = Field(
+ default=None,
+ description="Enable LaTeX math block conversion (\\\\[...\\\\] and $$...$$) into Word equations",
+ )
+ MATH_INLINE_DOLLAR_ENABLE: Optional[bool] = Field(
+ default=None,
+ description="Enable inline $...$ math conversion into Word equations (conservative parsing to reduce false positives)",
+ )
+
+ def __init__(self):
+ self.valves = self.Valves()
+ self._mermaid_figure_counter: int = 0
+ self._mermaid_placeholder_counter: int = 0
+ self._caption_style_name: Optional[str] = None
+ self._citation_anchor_by_index: Dict[int, str] = {}
+ self._citation_refs: List[_CitationRef] = []
+ self._bookmark_id_counter: int = 1
+ self._active_doc: Optional[Document] = None
+ self._user_lang: str = "en" # Will be set per-request
+ self._prefetched_files: dict = (
+ {}
+ ) # file_id -> FileModel, pre-fetched async before sync doc build
+ self._prefetched_external_images: dict = {} # url -> bytes, pre-fetched async
+
+ def _get_lang_key(self, user_language: str) -> str:
+ """Convert user language code to i18n key (e.g., 'zh-CN' -> 'zh', 'en-US' -> 'en')."""
+ lang = (user_language or "en").lower().split("-")[0]
+ return lang if lang in self._I18N_MESSAGES else "en"
+
+ def _get_msg(self, key: str, **kwargs) -> str:
+ """Get internationalized message by key with optional formatting."""
+ messages = self._I18N_MESSAGES.get(self._user_lang, self._I18N_MESSAGES["en"])
+ msg = messages.get(key, self._I18N_MESSAGES["en"].get(key, key))
+ if kwargs:
+ try:
+ return msg.format(**kwargs)
+ except KeyError:
+ return msg
+ return msg
+
+ def _get_user_context(self, __user__: Optional[Dict[str, Any]]) -> Dict[str, str]:
+ """Safely extracts user context information."""
+ if isinstance(__user__, (list, tuple)):
+ user_data = __user__[0] if __user__ else {}
+ elif isinstance(__user__, dict):
+ user_data = __user__
+ else:
+ user_data = {}
+
+ return {
+ "user_id": user_data.get("id", "unknown_user"),
+ "user_name": user_data.get("name", "User"),
+ "user_language": user_data.get("language", "en-US"),
+ }
+
+ def _get_chat_context(
+ self, body: dict, __metadata__: Optional[dict] = None
+ ) -> Dict[str, str]:
+ """
+ Unified extraction of chat context information (chat_id, message_id).
+ Prioritizes extraction from body, then metadata.
+ """
+ chat_id = ""
+ message_id = ""
+
+ # 1. Try to get from body
+ if isinstance(body, dict):
+ chat_id = body.get("chat_id", "")
+ message_id = body.get("id", "") # message_id is usually 'id' in body
+
+ # Check body.metadata as fallback
+ if not chat_id or not message_id:
+ body_metadata = body.get("metadata", {})
+ if isinstance(body_metadata, dict):
+ if not chat_id:
+ chat_id = body_metadata.get("chat_id", "")
+ if not message_id:
+ message_id = body_metadata.get("message_id", "")
+
+ # 2. Try to get from __metadata__ (as supplement)
+ if __metadata__ and isinstance(__metadata__, dict):
+ if not chat_id:
+ chat_id = __metadata__.get("chat_id", "")
+ if not message_id:
+ message_id = __metadata__.get("message_id", "")
+
+ return {
+ "chat_id": str(chat_id).strip(),
+ "message_id": str(message_id).strip(),
+ }
+
+ async def _emit_status(
+ self,
+ emitter: Optional[Callable[[Any], Awaitable[None]]],
+ description: str,
+ done: bool = False,
+ ):
+ """Emits a status update event."""
+ if self.valves.SHOW_STATUS and emitter:
+ await emitter(
+ {"type": "status", "data": {"description": description, "done": done}}
+ )
+
+ async def _emit_notification(
+ self,
+ emitter: Optional[Callable[[Any], Awaitable[None]]],
+ content: str,
+ ntype: str = "info",
+ ):
+ """Emits a notification event (info, success, warning, error)."""
+ if emitter:
+ await emitter(
+ {"type": "notification", "data": {"type": ntype, "content": content}}
+ )
+
+ async def _emit_debug_log(self, emitter, title: str, data: dict):
+ """Print structured debug logs in the browser console"""
+ if not self.valves.SHOW_DEBUG_LOG or not emitter:
+ return
+
+ try:
+ import json
+
+ js_code = f"""
+ (async function() {{
+ console.group("🛠️ {title}");
+ console.log({json.dumps(data, ensure_ascii=False)});
+ console.groupEnd();
+ }})();
+ """
+
+ await emitter({"type": "execute", "data": {"code": js_code}})
+ except Exception as e:
+ print(f"Error emitting debug log: {e}")
+
+ async def action(
+ self,
+ body: dict,
+ __user__=None,
+ __event_emitter__=None,
+ __event_call__: Optional[Callable[[Any], Awaitable[None]]] = None,
+ __metadata__: Optional[dict] = None,
+ __request__: Optional[Any] = None,
+ ):
+ logger.info(f"action:{__name__}")
+
+ # Parse user info
+ user_name = "User"
+ user_id = "unknown_user"
+ if isinstance(__user__, (list, tuple)):
+ user_name = __user__[0].get("name", "User") if __user__[0] else "User"
+ user_id = (
+ __user__[0]["id"]
+ if __user__ and "id" in __user__[0]
+ else "unknown_user"
+ )
+ elif isinstance(__user__, dict):
+ user_name = __user__.get("name", "User")
+ user_id = __user__.get("id", "unknown_user")
+
+ # Apply UserValves if present
+ if __user__:
+ # Robustly parse UserValves whether it's a dict or Pydantic model
+ raw_valves = __user__.get("valves", {})
+ if isinstance(raw_valves, self.UserValves):
+ user_valves = raw_valves
+ elif isinstance(raw_valves, dict):
+ user_valves = self.UserValves(**raw_valves)
+ else:
+ user_valves = None
+
+ if user_valves:
+ for key, value in user_valves.model_dump(exclude_unset=True).items():
+ # Only override if the value is not None (and explicitly set)
+ if hasattr(self.valves, key) and value is not None:
+ setattr(self.valves, key, value)
+
+ # Get user language from Valves configuration
+ self._user_lang = self._get_lang_key(self.valves.UI_LANGUAGE)
+
+ if __event_emitter__:
+ last_assistant_message = body["messages"][-1]
+
+ await __event_emitter__(
+ {
+ "type": "status",
+ "data": {
+ "description": self._get_msg("converting"),
+ "done": False,
+ },
+ }
+ )
+
+ try:
+ chat_ctx = self._get_chat_context(body, __metadata__)
+ chat_id = chat_ctx["chat_id"]
+
+ message_content = last_assistant_message.get("content")
+ if isinstance(message_content, str):
+ if __event_emitter__ and self.valves.SHOW_DEBUG_LOG:
+ debug_data = {}
+ for name, regex in [
+ ("Details Block", _ALL_DETAILS_RE),
+ ("Think Block", _THINK_RE),
+ ("Analysis Block", _ANALYSIS_RE),
+ ]:
+ matches = regex.findall(message_content)
+ if matches:
+ debug_data[name] = [
+ (m[:200] + "...") if len(m) > 200 else m
+ for m in matches
+ ]
+ if debug_data:
+ await self._emit_debug_log(
+ __event_emitter__,
+ "Context Stripping Analysis",
+ debug_data,
+ )
+
+ # Log font configuration
+ await self._emit_debug_log(
+ __event_emitter__,
+ "Font Configuration",
+ {
+ "Latin Font": self.valves.FONT_LATIN,
+ "Asian Font": self.valves.FONT_ASIAN,
+ "Code Font": self.valves.FONT_CODE,
+ },
+ )
+
+ message_content = self._strip_reasoning_blocks(message_content)
+
+ # 0.10+ leaves flat `content` empty (text is in `output`, not
+ # forwarded here); recover it from the DB.
+ if not message_content or (
+ isinstance(message_content, str) and not message_content.strip()
+ ):
+ output_text = await self._fetch_message_output_text(
+ chat_id, chat_ctx["message_id"]
+ )
+ if output_text:
+ message_content = self._strip_reasoning_blocks(output_text)
+
+ if isinstance(message_content, str):
+ message_content = self._strip_reference_definitions(message_content)
+
+ if not message_content or not message_content.strip():
+ await self._emit_notification(
+ __event_emitter__, self._get_msg("error_no_content"), "error"
+ )
+ return
+
+ # Generate filename
+ title = ""
+
+ # Fetch chat_title directly via chat_id as it's usually missing in body
+ chat_title = ""
+ if chat_id:
+ chat_title = await self.fetch_chat_title(chat_id, user_id)
+
+ if (
+ self.valves.TITLE_SOURCE.strip() == "chat_title"
+ or not self.valves.TITLE_SOURCE.strip()
+ ):
+ title = chat_title
+ elif self.valves.TITLE_SOURCE.strip() == "markdown_title":
+ title = self.extract_title(message_content)
+ elif self.valves.TITLE_SOURCE.strip() == "ai_generated":
+ title = await self.generate_title_using_ai(
+ body, message_content, user_id, __request__
+ )
+
+ # Fallback logic
+ if not title:
+ if self.valves.TITLE_SOURCE.strip() != "chat_title" and chat_title:
+ title = chat_title
+ elif self.valves.TITLE_SOURCE.strip() != "markdown_title":
+ extracted = self.extract_title(message_content)
+ if extracted:
+ title = extracted
+
+ current_datetime = datetime.datetime.now()
+ formatted_date = current_datetime.strftime("%Y%m%d")
+
+ cleaned_title = self.clean_filename(title) if title else ""
+ if cleaned_title:
+ filename = f"{cleaned_title}.docx"
+ else:
+ clean_user = self.clean_filename(user_name)
+ filename = f"{clean_user}_{formatted_date}.docx"
+
+ # Escape filename for JS string
+ js_filename = filename.replace("\\", "\\\\").replace('"', '\\"')
+
+ top_heading = ""
+ if chat_title:
+ top_heading = chat_title
+ elif title:
+ top_heading = title
+
+ # Create Word document; if no h1 exists, inject chat title as h1
+ has_h1 = bool(re.search(r"^#\s+.+$", message_content, re.MULTILINE))
+
+ # Heading level normalization (Relative Algorithm)
+ if not has_h1:
+ # Find the minimum heading level in the content
+ heading_levels = [
+ len(m.group(1))
+ for m in re.finditer(r"^(#+)\s+.+$", message_content, re.MULTILINE)
+ ]
+ if heading_levels:
+ min_level = min(heading_levels)
+ if min_level > 1:
+ shift = min_level - 1
+ # Perform promotion: replace ^### with ^##, etc.
+ def _promote(m):
+ current_level = len(m.group(1))
+ new_level = max(1, current_level - shift)
+ return "#" * new_level + m.group(2)
+
+ message_content = re.sub(
+ r"^(#+)(\s+.+)$", _promote, message_content, flags=re.MULTILINE
+ )
+ # After promotion, we now have H1
+ has_h1 = True
+ await self._emit_debug_log(
+ __event_emitter__,
+ "Relative Heading Algorithm",
+ f"Normalized headings by shifting -{shift} levels.",
+ )
+ sources = (
+ last_assistant_message.get("sources") or body.get("sources") or []
+ )
+ doc = await self.markdown_to_docx(
+ message_content,
+ top_heading=top_heading,
+
+ sources=sources,
+ event_emitter=__event_emitter__,
+ user_name=user_name,
+ title=title,
+ )
+
+ # Save to memory
+ doc_buffer = io.BytesIO()
+ doc.save(doc_buffer)
+ doc_buffer.seek(0)
+ file_content = doc_buffer.read()
+ base64_blob = base64.b64encode(file_content).decode("utf-8")
+
+ # Trigger file download
+ if __event_call__:
+ await __event_call__(
+ {
+ "type": "execute",
+ "data": {
+ "code": f"""
+ (async function() {{
+ const base64Data = "{base64_blob}";
+ const filename = "{js_filename}";
+ const mermaidUrl = "{self.valves.MERMAID_JS_URL}";
+ const jszipUrl = "{self.valves.MERMAID_JSZIP_URL}";
+ const pngScale = {float(self.valves.MERMAID_PNG_SCALE)};
+ const displayScale = {float(self.valves.MERMAID_DISPLAY_SCALE)};
+ const bgRaw = "{(self.valves.MERMAID_BACKGROUND or '').strip()}";
+ const bg = (bgRaw || "").trim();
+ const bgFill = (bg && bg.toLowerCase() !== "transparent") ? bg : "";
+ const themeBackground = bgFill || "transparent";
+
+ function downloadBlob(blob, filename) {{
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.style.display = "none";
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ URL.revokeObjectURL(url);
+ document.body.removeChild(a);
+ }}
+
+ async function loadScript(url, globalName) {{
+ if (globalName && window[globalName]) return;
+ await new Promise((resolve, reject) => {{
+ const script = document.createElement("script");
+ script.src = url;
+ script.onload = resolve;
+ script.onerror = reject;
+ document.head.appendChild(script);
+ }});
+ }}
+
+ function decodeBase64ToUint8Array(b64) {{
+ const binary = atob(b64);
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
+ return bytes;
+ }}
+
+ function parseViewBox(vb) {{
+ if (!vb) return null;
+ const parts = vb.trim().split(/\\s+/).map(Number);
+ if (parts.length !== 4 || parts.some((n) => !isFinite(n))) return null;
+ return {{ minX: parts[0], minY: parts[1], width: parts[2], height: parts[3] }};
+ }}
+
+ function normalizeSvgForWord(svgText) {{
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(svgText, "image/svg+xml");
+ const svgEl = doc.documentElement;
+ if (!svgEl || svgEl.tagName.toLowerCase() !== "svg") return svgText;
+
+ // Pad viewBox a little to reduce clipping in Word.
+ const vb0 = parseViewBox(svgEl.getAttribute("viewBox"));
+ if (vb0 && vb0.width > 0 && vb0.height > 0) {{
+ const minDim = Math.min(vb0.width, vb0.height);
+ let pad = Math.max(8.0, minDim * 0.02);
+ pad = Math.min(pad, 24.0);
+ const vb = {{
+ minX: vb0.minX - pad,
+ minY: vb0.minY - pad,
+ width: vb0.width + 2 * pad,
+ height: vb0.height + 2 * pad,
+ }};
+ svgEl.setAttribute("viewBox", `${{vb.minX}} ${{vb.minY}} ${{vb.width}} ${{vb.height}}`);
+ }}
+
+ const vb = parseViewBox(svgEl.getAttribute("viewBox"));
+ const widthAttr = (svgEl.getAttribute("width") || "").trim();
+ const heightAttr = (svgEl.getAttribute("height") || "").trim();
+ const widthPct = widthAttr.endsWith("%");
+ const heightPct = heightAttr.endsWith("%");
+ if (vb && vb.width > 0 && vb.height > 0 && (!widthAttr || !heightAttr || widthPct || heightPct)) {{
+ svgEl.setAttribute("width", `${{vb.width}}`);
+ svgEl.setAttribute("height", `${{vb.height}}`);
+ }}
+
+ svgEl.removeAttribute("style");
+ svgEl.setAttribute("preserveAspectRatio", "xMidYMid meet");
+ svgEl.setAttribute("overflow", "visible");
+
+ const removeNode = (n) => {{
+ try {{ n && n.parentNode && n.parentNode.removeChild(n); }} catch (_e) {{}}
+ }};
+
+ // Remove Mermaid/OWUI background rectangles to avoid \"white box\" rendering in Word dark mode.
+ svgEl
+ .querySelectorAll('rect[data-owui-bg=\"1\"], rect.background, rect[class~=\"background\"], rect#background')
+ .forEach(removeNode);
+ try {{
+ const isWhiteish = (fill) => {{
+ const f = (fill || "").trim().toLowerCase();
+ return (
+ f === "white" ||
+ f === "#fff" ||
+ f === "#ffffff" ||
+ f === "rgb(255,255,255)" ||
+ f === "rgb(255, 255, 255)"
+ );
+ }};
+ const nearly = (a, b) => Math.abs(a - b) <= 1e-3;
+ const rectMatches = (r, box) => {{
+ if (!box) return false;
+ const x = parseFloat(r.getAttribute("x") || "0");
+ const y = parseFloat(r.getAttribute("y") || "0");
+ const w = parseFloat(r.getAttribute("width") || "");
+ const h = parseFloat(r.getAttribute("height") || "");
+ if (!isFinite(x) || !isFinite(y) || !isFinite(w) || !isFinite(h)) return false;
+ return (
+ nearly(x, box.minX) &&
+ nearly(y, box.minY) &&
+ nearly(w, box.width) &&
+ nearly(h, box.height)
+ );
+ }};
+ const vbNow = parseViewBox(svgEl.getAttribute("viewBox"));
+ svgEl.querySelectorAll("rect[fill]").forEach((r) => {{
+ const fill = r.getAttribute("fill");
+ if (!isWhiteish(fill)) return;
+ if (rectMatches(r, vb0) || rectMatches(r, vbNow)) removeNode(r);
+ }});
+ }} catch (_e) {{}}
+ try {{
+ const vbCanvas = parseViewBox(svgEl.getAttribute(\"viewBox\")) || vb0 || vb;
+ if (vbCanvas) {{
+ const existing = svgEl.querySelector('rect[data-owui-canvas=\"1\"]');
+ const rect = existing || doc.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\");
+ rect.setAttribute(\"data-owui-canvas\", \"1\");
+ rect.setAttribute(\"x\", `${{vbCanvas.minX}}`);
+ rect.setAttribute(\"y\", `${{vbCanvas.minY}}`);
+ rect.setAttribute(\"width\", `${{vbCanvas.width}}`);
+ rect.setAttribute(\"height\", `${{vbCanvas.height}}`);
+ rect.setAttribute(\"fill\", \"#FFFFFF\");
+ // Word quirk: without a full-canvas rect with *non-zero* opacity, Word will often
+ // only offer \"Convert to Shape\" when clicking on an actual stroke/fill (not empty space).
+ // We keep this rect nearly transparent and non-interactive.
+ rect.setAttribute(\"fill-opacity\", \"0.001\");
+ rect.setAttribute(\"stroke\", \"none\");
+ rect.setAttribute(\"stroke-opacity\", \"0\");
+ rect.setAttribute(\"pointer-events\", \"none\");
+ if (!existing) {{
+ const first = svgEl.firstChild;
+ svgEl.insertBefore(rect, first);
+ }}
+ }}
+ }} catch (_e) {{}}
+
+ return new XMLSerializer().serializeToString(svgEl);
+ }}
+
+ function getMaxWidthEmu(xmlDoc) {{
+ try {{
+ const sects = xmlDoc.getElementsByTagName("w:sectPr");
+ const sect = sects && sects.length ? sects[sects.length - 1] : null;
+ if (!sect) return 5486400; // 6 in
+ const pgSz = sect.getElementsByTagName("w:pgSz")[0];
+ const pgMar = sect.getElementsByTagName("w:pgMar")[0];
+ if (!pgSz || !pgMar) return 5486400;
+ const pageW = parseInt(pgSz.getAttribute("w:w") || "", 10);
+ const left = parseInt(pgMar.getAttribute("w:left") || "", 10);
+ const right = parseInt(pgMar.getAttribute("w:right") || "", 10);
+ if (!isFinite(pageW) || !isFinite(left) || !isFinite(right)) return 5486400;
+ const twips = Math.max(1, pageW - left - right);
+ return Math.round(twips * 635); // 1 twip = 635 EMU
+ }} catch (_e) {{
+ return 5486400;
+ }}
+ }}
+
+ function getChildByTag(parent, tag) {{
+ const nodes = parent.getElementsByTagName(tag);
+ return nodes && nodes.length ? nodes[0] : null;
+ }}
+
+ try {{
+ await loadScript(jszipUrl, "JSZip");
+ await loadScript(mermaidUrl, "mermaid");
+
+ // Mermaid init: disable htmlLabels to keep SVG Word-friendly; PNG fallback still included.
+ try {{
+ window.mermaid.initialize({{
+ startOnLoad: false,
+ theme: "default",
+ themeVariables: {{
+ background: themeBackground,
+ fontFamily: "Calibri, Segoe UI, Arial, sans-serif",
+ fontSize: "10pt",
+ }},
+ themeCSS: ".slice {{ font-size: 10pt !important; }}\\n.legend text {{ font-size: 10pt !important; }}\\n.pieTitleText {{ font-size: 10pt !important; }}",
+ fontFamily: "Calibri, Segoe UI, Arial, sans-serif",
+ securityLevel: "strict",
+ htmlLabels: false,
+ flowchart: {{ htmlLabels: false }},
+ }});
+ }} catch (_e) {{
+ // Ignore and proceed with defaults.
+ }}
+
+ const bytes = decodeBase64ToUint8Array(base64Data);
+ const zip = new window.JSZip();
+ await zip.loadAsync(bytes);
+
+ const docXml = await zip.file("word/document.xml").async("string");
+ const relsXml = await zip.file("word/_rels/document.xml.rels").async("string");
+ const parser = new DOMParser();
+ const xmlDoc = parser.parseFromString(docXml, "application/xml");
+ const relsDoc = parser.parseFromString(relsXml, "application/xml");
+
+ // Build rId -> target path mapping
+ const rels = relsDoc.getElementsByTagName("Relationship");
+ const rIdToTarget = {{}};
+ for (let i = 0; i < rels.length; i++) {{
+ const rel = rels[i];
+ const id = rel.getAttribute("Id");
+ const target = rel.getAttribute("Target");
+ if (id && target) rIdToTarget[id] = target;
+ }}
+
+ const maxWidthEmu = getMaxWidthEmu(xmlDoc);
+ const maxWidthEmuScaled = Math.max(1, Math.round(maxWidthEmu * Math.min(1.0, Math.max(0.1, displayScale || 1.0))));
+
+ const drawings = xmlDoc.getElementsByTagName("w:drawing");
+ const placeholders = [];
+
+ for (let i = 0; i < drawings.length; i++) {{
+ const drawing = drawings[i];
+ const docPr = getChildByTag(drawing, "wp:docPr");
+ if (!docPr) continue;
+ const descr = docPr.getAttribute("descr") || "";
+ if (!descr.startsWith("MERMAID_SRC:")) continue;
+ const encoded = descr.substring("MERMAID_SRC:".length);
+ const code = decodeURIComponent(encoded);
+
+ const blip = getChildByTag(drawing, "a:blip");
+ const ridPng = blip ? blip.getAttribute("r:embed") : null;
+ const svgBlip = getChildByTag(drawing, "asvg:svgBlip");
+ const ridSvg = svgBlip ? svgBlip.getAttribute("r:embed") : null;
+
+ const container = getChildByTag(drawing, "wp:inline") || getChildByTag(drawing, "wp:anchor");
+ const extent = container ? getChildByTag(container, "wp:extent") : null;
+
+ const xfrm = getChildByTag(drawing, "a:xfrm");
+ const xfrmExt = xfrm ? getChildByTag(xfrm, "a:ext") : null;
+
+ placeholders.push({{ code, ridPng, ridSvg, extent, xfrmExt, svgBlip }});
+ }}
+
+ if (!placeholders.length) {{
+ const blob = new Blob([bytes], {{ type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }});
+ downloadBlob(blob, filename);
+ return;
+ }}
+
+ // Phase 1: Render all Mermaid diagrams sequentially (mermaid needs DOM)
+ const renderResults = [];
+ for (let i = 0; i < placeholders.length; i++) {{
+ const item = placeholders[i];
+ try {{
+ const id = "owui-mermaid-" + i;
+ const rendered = await window.mermaid.render(id, item.code);
+ let svgText = rendered && rendered.svg ? rendered.svg : rendered;
+ if (!svgText || typeof svgText !== "string") throw new Error("Mermaid returned empty SVG");
+
+ svgText = normalizeSvgForWord(svgText);
+ const hasForeignObject = / 0 && vb.height > 0 ? (vb.width / vb.height) : (4/3);
+
+ const widthEmu = maxWidthEmuScaled;
+ const heightEmu = Math.max(1, Math.round(widthEmu / ratio));
+
+ renderResults.push({{ item, svgText, widthEmu, heightEmu, success: true }});
+ }} catch (err) {{
+ console.error("Mermaid render failed for block", i, err);
+ renderResults.push({{ item, svgText: null, widthEmu: 0, heightEmu: 0, success: false }});
+ }}
+ }}
+
+ // Phase 2: Convert SVG to PNG in parallel for performance
+ async function svgToPng(svgText, targetWidthPx, targetHeightPx) {{
+ const canvas = document.createElement("canvas");
+ const ctx = canvas.getContext("2d");
+ const scale = Math.max(1.0, pngScale || 1.0);
+ canvas.width = Math.round(targetWidthPx * scale);
+ canvas.height = Math.round(targetHeightPx * scale);
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ if (bgFill) {{
+ ctx.fillStyle = bgFill;
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ }}
+ ctx.scale(scale, scale);
+
+ const img = new Image();
+ await new Promise((resolve, reject) => {{
+ img.onload = resolve;
+ img.onerror = reject;
+ img.src = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgText)));
+ }});
+
+ ctx.drawImage(img, 0, 0, targetWidthPx, targetHeightPx);
+ const pngDataUrl = canvas.toDataURL("image/png");
+ return pngDataUrl.split(",")[1];
+ }}
+
+ // Create PNG conversion promises for parallel execution
+ const pngPromises = renderResults.map(async (result, i) => {{
+ if (!result.success || !result.svgText) return null;
+ const {{ item, widthEmu, heightEmu }} = result;
+ if (!item.ridPng || !rIdToTarget[item.ridPng]) return null;
+
+ const targetWidthPx = Math.max(1, Math.round(widthEmu / 9525));
+ const targetHeightPx = Math.max(1, Math.round(heightEmu / 9525));
+
+ try {{
+ const pngBase64 = await svgToPng(result.svgText, targetWidthPx, targetHeightPx);
+ return {{ index: i, pngBase64, path: "word/" + rIdToTarget[item.ridPng] }};
+ }} catch (err) {{
+ console.error("PNG conversion failed for block", i, err);
+ return null;
+ }}
+ }});
+
+ // Wait for all PNG conversions to complete
+ const pngResults = await Promise.all(pngPromises);
+
+ // Phase 3: Update ZIP with all results
+ for (let i = 0; i < renderResults.length; i++) {{
+ const result = renderResults[i];
+ if (!result.success) continue;
+
+ const {{ item, svgText, widthEmu, heightEmu }} = result;
+
+ // Update extent in XML
+ if (item.extent) {{
+ item.extent.setAttribute("cx", `${{widthEmu}}`);
+ item.extent.setAttribute("cy", `${{heightEmu}}`);
+ }}
+ if (item.xfrmExt) {{
+ item.xfrmExt.setAttribute("cx", `${{widthEmu}}`);
+ item.xfrmExt.setAttribute("cy", `${{heightEmu}}`);
+ }}
+
+ // Write SVG part
+ if (item.ridSvg && rIdToTarget[item.ridSvg]) {{
+ zip.file("word/" + rIdToTarget[item.ridSvg], svgText);
+ }}
+ }}
+
+ // Write PNG files from parallel results
+ for (const pngResult of pngResults) {{
+ if (pngResult && pngResult.pngBase64) {{
+ zip.file(pngResult.path, pngResult.pngBase64, {{ base64: true }});
+ }}
+ }}
+
+ const newDocXml = new XMLSerializer().serializeToString(xmlDoc);
+ zip.file("word/document.xml", newDocXml);
+
+ const finalBlob = await zip.generateAsync({{
+ type: "blob",
+ compression: "DEFLATE",
+ compressionOptions: {{ level: 6 }},
+ }});
+ downloadBlob(finalBlob, filename);
+ }} catch (error) {{
+ console.error("Export pipeline failed:", error);
+ const bytes = decodeBase64ToUint8Array(base64Data);
+ const blob = new Blob([bytes], {{ type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }});
+ downloadBlob(blob, filename);
+ }}
+ }})();
+ """
+ },
+ }
+ )
+
+ await __event_emitter__(
+ {
+ "type": "status",
+ "data": {
+ "description": self._get_msg("exported"),
+ "done": True,
+ },
+ }
+ )
+
+ await self._emit_notification(
+ __event_emitter__,
+ self._get_msg("success", filename=filename),
+ "success",
+ )
+
+ return {"message": "Download triggered"}
+
+ except Exception as e:
+ logger.exception(f"Error exporting to Word: {str(e)}")
+ await __event_emitter__(
+ {
+ "type": "status",
+ "data": {
+ "description": self._get_msg("export_failed", error=str(e)),
+ "done": True,
+ },
+ }
+ )
+ await self._emit_notification(
+ __event_emitter__,
+ self._get_msg("error_export", error=str(e)),
+ "error",
+ )
+
+ async def generate_title_using_ai(
+ self, body: dict, content: str, user_id: str, request: Any
+ ) -> str:
+ if not request:
+ return ""
+
+ try:
+ user_obj = await _call_db(Users.get_user_by_id, user_id)
+ model = body.get("model")
+
+ payload = {
+ "model": model,
+ "messages": [
+ {
+ "role": "system",
+ "content": "You are a helpful assistant. Generate a short, concise title (max 10 words) for the following text. Do not use quotes. Only output the title.",
+ },
+ {"role": "user", "content": content[:2000]}, # Limit content length
+ ],
+ "stream": False,
+ }
+
+ response = await generate_chat_completion(request, payload, user_obj)
+ if response and "choices" in response:
+ return response["choices"][0]["message"]["content"].strip()
+ except Exception as e:
+ logger.error(f"Error generating title: {e}")
+
+ return ""
+
+ def extract_title(self, content: str) -> str:
+ """Extract title from Markdown h1/h2 only"""
+ lines = content.split("\n")
+ for line in lines:
+ # Match h1-h2 headings only
+ match = re.match(r"^#{1,2}\s+(.+)$", line.strip())
+ if match:
+ return match.group(1).strip()
+ return ""
+
+ def extract_chat_title(self, body: dict) -> str:
+ """Extract chat title from common payload fields."""
+ if not isinstance(body, dict):
+ return ""
+
+ candidates = []
+
+ for key in ("chat", "conversation"):
+ if isinstance(body.get(key), dict):
+ candidates.append(body.get(key, {}).get("title", ""))
+
+ for key in ("title", "chat_title"):
+ value = body.get(key)
+ if isinstance(value, str):
+ candidates.append(value)
+
+ for candidate in candidates:
+ if candidate and isinstance(candidate, str):
+ return candidate.strip()
+ return ""
+
+ def extract_chat_id(self, body: dict, metadata: Optional[dict]) -> str:
+ """Extract chat_id from body or metadata"""
+ if isinstance(body, dict):
+ chat_id = body.get("chat_id") or body.get("id")
+ if isinstance(chat_id, str) and chat_id.strip():
+ return chat_id.strip()
+
+ for key in ("chat", "conversation"):
+ nested = body.get(key)
+ if isinstance(nested, dict):
+ nested_id = nested.get("id") or nested.get("chat_id")
+ if isinstance(nested_id, str) and nested_id.strip():
+ return nested_id.strip()
+ if isinstance(metadata, dict):
+ chat_id = metadata.get("chat_id")
+ if isinstance(chat_id, str) and chat_id.strip():
+ return chat_id.strip()
+ return ""
+
+ async def fetch_chat_title(self, chat_id: str, user_id: str = "") -> str:
+ """Fetch chat title from database by chat_id"""
+ if not chat_id:
+ return ""
+
+ try:
+ chat = None
+ if user_id:
+ chat = await _call_db(
+ Chats.get_chat_by_id_and_user_id, id=chat_id, user_id=user_id
+ )
+ if not chat:
+ chat = await _call_db(Chats.get_chat_by_id, chat_id)
+ except Exception as exc:
+ logger.warning(f"Failed to load chat {chat_id}: {exc}")
+ return ""
+
+ if not chat:
+ return ""
+
+ data = getattr(chat, "chat", {}) or {}
+ title = data.get("title") or getattr(chat, "title", "")
+ return title.strip() if isinstance(title, str) else ""
+
+ def _extract_text_from_output(self, output: Any) -> str:
+ """Rebuild assistant text from structured ``output`` via OWUI's
+ ``convert_output_to_messages`` (reasoning excluded); "" if none."""
+ if not isinstance(output, list) or not output:
+ return ""
+
+ reconstructed = convert_output_to_messages(output)
+ assistant_texts = [
+ msg["content"]
+ for msg in reconstructed
+ if isinstance(msg, dict)
+ and msg.get("role") == "assistant"
+ and isinstance(msg.get("content"), str)
+ and msg["content"].strip()
+ ]
+ return "\n".join(assistant_texts)
+
+ async def _fetch_message_output_text(self, chat_id: str, message_id: str) -> str:
+ """Assistant text for a message via OWUI's ChatMessages store: its structured
+ ``output`` reconstructed by convert_output_to_messages. "" if not found."""
+ if not chat_id or not message_id:
+ return ""
+ message = await _call_db(
+ ChatMessages.get_message_by_id, f"{chat_id}-{message_id}"
+ )
+ return self._extract_text_from_output(message.output) if message else ""
+
+ def clean_filename(self, name: str) -> str:
+ """Clean illegal characters from filename and strip emoji."""
+ if not isinstance(name, str):
+ return ""
+
+ without_emoji = self._remove_emojis(name)
+ cleaned = re.sub(r'[\\/*?:"<>|]', "", without_emoji)
+ cleaned = re.sub(r"\s+", " ", cleaned).strip().strip(".")
+ return cleaned[:50].strip()
+
+ def _max_embed_image_bytes(self) -> int:
+ mb = getattr(self.valves, "MAX_EMBED_IMAGE_MB", 20)
+ try:
+ mb_i = int(mb)
+ except Exception:
+ mb_i = 20
+ mb_i = max(1, mb_i)
+ return mb_i * 1024 * 1024
+
+ def _extract_owui_api_file_id(self, url: str) -> Optional[str]:
+ if not isinstance(url, str) or not url:
+ return None
+ m = _OWUI_API_FILE_ID_RE.search(url)
+ if not m:
+ return None
+ fid = (m.group("id") or "").strip()
+ return fid or None
+
+ def _read_file_bytes_limited(self, path: Path, max_bytes: int) -> Optional[bytes]:
+ try:
+ if not path.exists():
+ return None
+ try:
+ size = path.stat().st_size
+ if size > max_bytes:
+ return None
+ except Exception:
+ pass
+ with path.open("rb") as f:
+ data = f.read(max_bytes + 1)
+ if len(data) > max_bytes:
+ return None
+ return data
+ except Exception:
+ return None
+
+ def _decode_base64_limited(self, b64: str, max_bytes: int) -> Optional[bytes]:
+ if not isinstance(b64, str):
+ return None
+ s = re.sub(r"\s+", "", b64.strip())
+ if not s:
+ return None
+
+ # Rough pre-check: base64 expands by ~4/3. Avoid decoding clearly oversized payloads.
+ est = (len(s) * 3) // 4
+ if est > max_bytes:
+ return None
+
+ pad = (-len(s)) % 4
+ if pad:
+ s = s + ("=" * pad)
+ try:
+ out = base64.b64decode(s, validate=False)
+ except (binascii.Error, ValueError):
+ return None
+ if len(out) > max_bytes:
+ return None
+ return out
+
+ def _image_bytes_from_data_url(self, url: str, max_bytes: int) -> Optional[bytes]:
+ if not isinstance(url, str):
+ return None
+ m = _DATA_IMAGE_URL_RE.match(url.strip())
+ if not m:
+ return None
+ b64 = m.group("b64") or ""
+ return self._decode_base64_limited(b64, max_bytes)
+
+ def _image_bytes_from_owui_file_id(
+ self, file_id: str, max_bytes: int
+ ) -> Optional[bytes]:
+ if not file_id:
+ return None
+
+ if Files is None:
+ logger.error(
+ "Files model is not available (import failed). Cannot retrieve file content."
+ )
+ return None
+
+ # Use pre-fetched file object (populated async before document build)
+ file_obj = self._prefetched_files.get(file_id)
+ if file_obj is None:
+ logger.warning(f"File {file_id} not found in prefetch cache.")
+ return None
+
+ # 1. Try data field (DB stored)
+ data_field = getattr(file_obj, "data", None)
+ if isinstance(data_field, dict):
+ blob_value = data_field.get("bytes")
+ if isinstance(blob_value, (bytes, bytearray)):
+ raw = bytes(blob_value)
+ return raw if len(raw) <= max_bytes else None
+ for key in ("b64", "base64", "data"):
+ inline = data_field.get(key)
+ if isinstance(inline, str) and inline.strip():
+ return self._decode_base64_limited(inline, max_bytes)
+
+ # 2. Storage-backed content: OWUI's Storage provider resolves file.path
+ # (local / S3 / GCS / Azure, using OWUI's configured storage) to a local path.
+ path = getattr(file_obj, "path", None)
+ if isinstance(path, str) and path.strip():
+ try:
+ local_path = Storage.get_file(path)
+ except Exception as exc:
+ logger.warning(f"Storage.get_file failed for {file_id} ({path}): {exc}")
+ else:
+ raw = self._read_file_bytes_limited(Path(local_path), max_bytes)
+ if raw is not None:
+ return raw
+
+ logger.warning(f"File {file_id} found but no content accessible via Storage.")
+ return None
+
+ async def _fetch_external_image(self, url: str) -> Optional[bytes]:
+ """Download an external image URL to bytes (gated by EMBED_EXTERNAL_IMAGES).
+
+ SSRF protection is OpenWebUI's: validate_url() pre-flight + a
+ get_ssrf_safe_session() whose resolver re-validates the resolved IP at
+ connect time (defeats DNS rebinding). Enforces MAX_EMBED_IMAGE_MB and an
+ image/* content type. Returns None (-> placeholder) on any failure.
+ """
+ max_bytes = self._max_embed_image_bytes()
+ try:
+ validate_url(url)
+ except Exception as exc:
+ logger.warning(f"External image blocked by validate_url: {url} ({exc})")
+ return None
+ try:
+ async with get_ssrf_safe_session() as session:
+ async with session.get(url) as resp:
+ if not (200 <= resp.status < 300):
+ logger.warning(f"External image HTTP {resp.status}: {url}")
+ return None
+ ctype = (
+ (resp.headers.get("Content-Type") or "")
+ .split(";")[0]
+ .strip()
+ .lower()
+ )
+ if ctype and not ctype.startswith("image/"):
+ logger.warning(
+ f"External URL is not an image (Content-Type={ctype}): {url}"
+ )
+ return None
+ buf = bytearray()
+ async for chunk in resp.content.iter_chunked(65536):
+ buf += chunk
+ if len(buf) > max_bytes:
+ logger.warning(
+ f"External image exceeds {max_bytes} bytes: {url}"
+ )
+ return None
+ return bytes(buf)
+ except Exception as exc:
+ logger.warning(f"Failed to fetch external image {url}: {exc}")
+ return None
+
+ def _add_image_placeholder(self, paragraph, alt: str, reason: str):
+ label = (alt or "").strip() or "image"
+ msg = f"[{label} not embedded: {reason}]"
+ self._add_text_run(paragraph, msg, bold=False, italic=False, strike=False)
+
+ def _try_embed_image(
+ self, paragraph, image_bytes: bytes
+ ) -> Tuple[bool, Optional[str]]:
+ if not image_bytes:
+ return False, "empty image bytes"
+ try:
+ run = paragraph.add_run()
+ width = None
+ if self._active_doc is not None:
+ try:
+ width = self._available_block_width(self._active_doc)
+ except Exception:
+ width = None
+ run.add_picture(cast(Any, io.BytesIO(image_bytes)), width=width)
+ return True, None
+ except Exception as e:
+ return False, str(e)
+
+ def _embed_markdown_image(self, paragraph, alt: str, url: str):
+ max_bytes = self._max_embed_image_bytes()
+ u = (url or "").strip()
+ if not u:
+ self._add_image_placeholder(paragraph, alt, "missing URL")
+ return
+
+ image_bytes: Optional[bytes] = None
+ if u.lower().startswith("data:"):
+ image_bytes = self._image_bytes_from_data_url(u, max_bytes)
+ if image_bytes is None:
+ self._add_image_placeholder(
+ paragraph,
+ alt,
+ f"invalid data URL or exceeds {self.valves.MAX_EMBED_IMAGE_MB}MB",
+ )
+ return
+ else:
+ file_id = self._extract_owui_api_file_id(u)
+ if not file_id:
+ # External image: embed prefetched bytes when the opt-in valve is on,
+ # otherwise leave a placeholder.
+ image_bytes = (
+ self._prefetched_external_images.get(u)
+ if self.valves.EMBED_EXTERNAL_IMAGES
+ else None
+ )
+ if image_bytes is None:
+ self._add_image_placeholder(paragraph, alt, "external URL")
+ return
+ else:
+ image_bytes = self._image_bytes_from_owui_file_id(file_id, max_bytes)
+ if image_bytes is None:
+ self._add_image_placeholder(
+ paragraph, alt, f"file unavailable ({file_id})"
+ )
+ return
+
+ success, error_msg = self._try_embed_image(paragraph, image_bytes)
+ if not success:
+ self._add_image_placeholder(
+ paragraph, alt, f"unsupported image type: {error_msg}"
+ )
+
+ async def markdown_to_docx(
+ self,
+ markdown_text: str,
+ top_heading: str = "",
+
+ sources: Optional[List[dict]] = None,
+ event_emitter: Optional[Callable] = None,
+ user_name: str = "",
+ title: str = "",
+ ) -> Document:
+ """
+ Convert Markdown text to Word document
+ Supports: headings, paragraphs, bold, italic, code blocks, lists, tables, links
+ Additionally: Mermaid fenced blocks (```mermaid) rendered client-side via Mermaid.js (SVG+PNG),
+ LaTeX math to Word equations, and OpenWebUI citations to References.
+ """
+ doc = Document()
+ self._sanitize_metadata(doc, author=user_name, title=title)
+ self._active_doc = doc
+ try:
+ self._mermaid_figure_counter = 0
+ self._mermaid_placeholder_counter = 0
+ self._caption_style_name = None
+ self._citation_anchor_by_index = {}
+ self._citation_refs = self._build_citation_refs(sources or [])
+ self._bookmark_id_counter = 1
+ for ref in self._citation_refs:
+ self._citation_anchor_by_index[ref.idx] = ref.anchor
+
+ # Pre-fetch all OWUI file objects referenced in this markdown (needed for sync image embedding)
+ if Files is not None:
+ file_ids = list(set(_OWUI_API_FILE_ID_RE.findall(markdown_text)))
+ self._prefetched_files = {}
+ for fid in file_ids:
+ try:
+ fobj = await _call_db(Files.get_file_by_id, fid)
+ if fobj:
+ self._prefetched_files[fid] = fobj
+ except Exception as e:
+ logger.warning(f"Failed to prefetch file {fid}: {e}")
+
+ # Pre-fetch external images (opt-in) so the sync doc build can embed them.
+ self._prefetched_external_images = {}
+ if self.valves.EMBED_EXTERNAL_IMAGES:
+ ext_urls = {
+ u
+ for u in (
+ m.group(1).strip()
+ for m in _MD_IMAGE_URL_RE.finditer(markdown_text)
+ )
+ if u.lower().startswith(("http://", "https://"))
+ and not self._extract_owui_api_file_id(u)
+ }
+ urls = list(ext_urls)
+ results = await asyncio.gather(
+ *(self._fetch_external_image(u) for u in urls)
+ )
+ self._prefetched_external_images = {
+ u: d for u, d in zip(urls, results) if d
+ }
+
+ # Set default fonts
+ self.set_document_default_font(doc)
+
+ # Inject Document Title (Style Level 0)
+ if top_heading:
+ # Remove emojis from title for a professional look
+ clean_title = self._remove_emojis(top_heading)
+ # Use Title style (level 0) for the main document title
+ self.add_heading(doc, clean_title, 0)
+
+ lines = markdown_text.split("\n")
+ i = 0
+ in_code_block = False
+ code_block_content = []
+ code_block_info_raw = ""
+ code_block_lang = ""
+ code_block_attrs: List[str] = []
+ in_math_block = False
+ math_block_delim = ""
+ math_block_lines: List[str] = []
+ in_list = False
+ list_items = []
+ list_type = None # 'ordered' or 'unordered'
+
+ total_lines = len(lines)
+ last_update_time = time.time()
+
+ while i < len(lines):
+ # Update status every 2 seconds
+ if event_emitter and time.time() - last_update_time > 2.0:
+ progress = int((i / total_lines) * 100)
+ await event_emitter(
+ {
+ "type": "status",
+ "data": {
+ "description": f"{self._get_msg('converting')} ({progress}%)",
+ "done": False,
+ },
+ }
+ )
+ last_update_time = time.time()
+
+ line = lines[i]
+
+ # Handle display math blocks (\[...\] or $$...$$)
+ if not in_code_block and self.valves.MATH_ENABLE:
+ single_line = self._extract_single_line_math(line)
+ if single_line is not None:
+ if in_list and list_items:
+ self.add_list_to_doc(doc, list_items, list_type)
+ list_items = []
+ in_list = False
+ self._add_display_equation(doc, single_line)
+ i += 1
+ continue
+
+ if not in_math_block:
+ stripped = line.strip()
+ if stripped in (r"\[", "$$"):
+ if in_list and list_items:
+ self.add_list_to_doc(doc, list_items, list_type)
+ list_items = []
+ in_list = False
+ in_math_block = True
+ math_block_delim = stripped
+ math_block_lines = []
+ i += 1
+ continue
+ else:
+ stripped = line.strip()
+ close = r"\]" if math_block_delim == r"\[" else "$$"
+ if stripped == close:
+ in_math_block = False
+ latex = "\n".join(math_block_lines).strip()
+ self._add_display_equation(doc, latex)
+ math_block_delim = ""
+ math_block_lines = []
+ i += 1
+ continue
+ math_block_lines.append(line)
+ i += 1
+ continue
+
+ # Handle code blocks
+ if line.strip().startswith("```"):
+ if not in_code_block:
+ # Process pending list first
+ if in_list and list_items:
+ self.add_list_to_doc(doc, list_items, list_type)
+ list_items = []
+ in_list = False
+
+ in_code_block = True
+ code_block_info_raw = line.strip()[3:].strip()
+ code_block_lang, code_block_attrs = self._parse_fence_info(
+ code_block_info_raw
+ )
+ code_block_content = []
+ else:
+ # End code block
+ in_code_block = False
+ code_text = "\n".join(code_block_content)
+ if code_block_lang.lower() == "mermaid":
+ self._insert_mermaid_placeholder(doc, code_text)
+ else:
+ self.add_code_block(doc, code_text, code_block_lang)
+ code_block_content = []
+ code_block_info_raw = ""
+ code_block_lang = ""
+ code_block_attrs = []
+ i += 1
+ continue
+
+ if in_code_block:
+ code_block_content.append(line)
+ i += 1
+ continue
+
+ # Handle tables
+ if line.strip().startswith("|") and line.strip().endswith("|"):
+ # Process pending list first
+ if in_list and list_items:
+ self.add_list_to_doc(doc, list_items, list_type)
+ list_items = []
+ in_list = False
+
+ table_lines = []
+ while i < len(lines) and lines[i].strip().startswith("|"):
+ table_lines.append(lines[i])
+ i += 1
+ self.add_table(doc, table_lines)
+ continue
+
+ # Handle headings
+ header_match = re.match(r"^(#{1,6})\s+(.+)$", line.strip())
+ if header_match:
+ # Process pending list first
+ if in_list and list_items:
+ self.add_list_to_doc(doc, list_items, list_type)
+ list_items = []
+ in_list = False
+
+ level = len(header_match.group(1))
+ text = header_match.group(2)
+ self.add_heading(doc, text, level)
+ i += 1
+ continue
+
+ # Handle unordered lists
+ unordered_match = re.match(r"^(\s*)[-*+]\s+(.+)$", line)
+ if unordered_match:
+ if not in_list or list_type != "unordered":
+ if in_list and list_items:
+ self.add_list_to_doc(doc, list_items, list_type)
+ list_items = []
+ in_list = True
+ list_type = "unordered"
+ indent = len(unordered_match.group(1)) // 2
+ list_items.append((indent, unordered_match.group(2)))
+ i += 1
+ continue
+
+ # Handle ordered lists
+ ordered_match = re.match(r"^(\s*)\d+[.)]\s+(.+)$", line)
+ if ordered_match:
+ if not in_list or list_type != "ordered":
+ if in_list and list_items:
+ self.add_list_to_doc(doc, list_items, list_type)
+ list_items = []
+ in_list = True
+ list_type = "ordered"
+ indent = len(ordered_match.group(1)) // 2
+ list_items.append((indent, ordered_match.group(2)))
+ i += 1
+ continue
+
+ # Handle blockquotes
+ if line.strip().startswith(">"):
+ # Process pending list first
+ if in_list and list_items:
+ self.add_list_to_doc(doc, list_items, list_type)
+ list_items = []
+ in_list = False
+
+ # Collect consecutive quote lines
+ blockquote_lines = []
+ while i < len(lines) and lines[i].strip().startswith(">"):
+ # Remove leading > and optional space
+ quote_line = re.sub(r"^>\s?", "", lines[i])
+ blockquote_lines.append(quote_line)
+ i += 1
+ self.add_blockquote(doc, "\n".join(blockquote_lines))
+ continue
+
+ # Handle horizontal rules
+ if re.match(r"^[-*_]{3,}$", line.strip()):
+ # Process pending list first
+ if in_list and list_items:
+ self.add_list_to_doc(doc, list_items, list_type)
+ list_items = []
+ in_list = False
+
+ self.add_horizontal_rule(doc)
+ i += 1
+ continue
+
+ # Handle empty lines
+ if not line.strip():
+ # End list
+ if in_list and list_items:
+ self.add_list_to_doc(doc, list_items, list_type)
+ list_items = []
+ in_list = False
+ i += 1
+ continue
+
+ # Handle normal paragraphs
+ if in_list and list_items:
+ self.add_list_to_doc(doc, list_items, list_type)
+ list_items = []
+ in_list = False
+
+ self.add_paragraph(doc, line)
+ i += 1
+
+ # Process remaining list
+ if in_list and list_items:
+ self.add_list_to_doc(doc, list_items, list_type)
+
+ # If math block wasn't closed, render it as plain text for robustness.
+ if in_math_block and math_block_lines:
+ self.add_paragraph(doc, r"\[")
+ for l in math_block_lines:
+ self.add_paragraph(doc, l)
+ self.add_paragraph(doc, r"\]")
+
+ if self._citation_refs:
+ self._add_references_section(doc)
+
+ return doc
+ finally:
+ self._active_doc = None
+
+ def _extract_single_line_math(self, line: str) -> Optional[str]:
+ s = line.strip()
+ # \[ ... \]
+ m = re.match(r"^\\\[(.*)\\\]$", s)
+ if m:
+ return m.group(1).strip()
+ # $$ ... $$
+ m = re.match(r"^\$\$(.*)\$\$$", s)
+ if m:
+ return m.group(1).strip()
+ return None
+
+ def _strip_reference_definitions(self, text: str) -> str:
+ """Remove markdown reference-definition lines (``[label]: target``), which
+ render invisibly and would otherwise appear as literal text in the export.
+ Matches OpenWebUI's own removeFormattings pattern."""
+ if not text:
+ return text
+ return _MD_REFERENCE_DEF_RE.sub("", text)
+
+ def _strip_reasoning_blocks(self, text: str) -> str:
+ """
+ Strip model reasoning blocks from assistant Markdown before export.
+
+ OpenWebUI can include reasoning as interleaved ...
+ (and sometimes / blocks). These should never be exported into DOCX.
+ """
+ if not text:
+ return text
+
+ cur = text
+ for _ in range(10):
+ prev = cur
+ cur = _ALL_DETAILS_RE.sub("", cur)
+ cur = _THINK_RE.sub("", cur)
+ cur = _ANALYSIS_RE.sub("", cur)
+ if cur == prev:
+ break
+
+ # Clean up excessive blank lines left by removals.
+ cur = re.sub(r"\n{4,}", "\n\n\n", cur)
+ return cur
+
+ def _add_display_equation(self, doc: Document, latex: str):
+ latex = (latex or "").strip()
+ if not latex:
+ return
+
+ if not LATEX_MATH_AVAILABLE:
+ self.add_code_block(doc, latex, "latex")
+ return
+
+ try:
+ mathml = latex_to_mathml(latex)
+ omml = mathml2omml.convert(mathml)
+ para = doc.add_paragraph()
+ para.alignment = WD_ALIGN_PARAGRAPH.CENTER
+ cast(Any, para)._p.append(self._wrap_omml_for_word(omml))
+ except Exception as exc:
+ logger.warning(f"Math conversion failed; falling back to text: {exc}")
+ self.add_code_block(doc, latex, "latex")
+
+ def _wrap_omml_for_word(self, omml: str):
+ m_ns = "http://schemas.openxmlformats.org/officeDocument/2006/math"
+ w_ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+ # Keep the OMML payload as-is, but ensure it has the math namespace declared.
+ xml = f'{omml} '
+ return parse_xml(xml)
+
+ # (Math warning paragraphs removed)
+
+ def _build_citation_refs(self, sources: List[dict]) -> List[_CitationRef]:
+ citation_idx_map: Dict[str, int] = {}
+ refs_by_idx: Dict[int, _CitationRef] = {}
+
+ for source in sources or []:
+ if not isinstance(source, dict):
+ continue
+
+ documents = source.get("document") or []
+ metadatas = source.get("metadata") or []
+ src_info = source.get("source") or {}
+
+ src_name = src_info.get("name") if isinstance(src_info, dict) else None
+ src_id_default = src_info.get("id") if isinstance(src_info, dict) else None
+ src_urls = src_info.get("urls") if isinstance(src_info, dict) else None
+
+ if not isinstance(documents, list):
+ documents = []
+ if not isinstance(metadatas, list):
+ metadatas = []
+
+ for idx_doc, _doc_text in enumerate(documents):
+ meta = metadatas[idx_doc] if idx_doc < len(metadatas) else {}
+ if not isinstance(meta, dict):
+ meta = {}
+
+ source_id = meta.get("source") or src_id_default or "N/A"
+ source_id_str = str(source_id)
+
+ if source_id_str not in citation_idx_map:
+ citation_idx_map[source_id_str] = len(citation_idx_map) + 1
+ idx = citation_idx_map[source_id_str]
+
+ if idx in refs_by_idx:
+ continue
+
+ url: Optional[str] = None
+ if isinstance(source_id, str) and re.match(r"^https?://", source_id):
+ url = source_id
+ elif isinstance(meta.get("url"), str) and re.match(
+ r"^https?://", meta["url"]
+ ):
+ url = meta["url"]
+ elif isinstance(src_urls, list) and src_urls:
+ if isinstance(src_urls[0], str) and re.match(
+ r"^https?://", src_urls[0]
+ ):
+ url = src_urls[0]
+
+ title = (
+ (meta.get("title") if isinstance(meta.get("title"), str) else None)
+ or (meta.get("name") if isinstance(meta.get("name"), str) else None)
+ or (
+ src_name
+ if isinstance(src_name, str) and src_name.strip()
+ else None
+ )
+ or (url if url else None)
+ or source_id_str
+ )
+
+ anchor = f"OWUIRef{idx}"
+ refs_by_idx[idx] = _CitationRef(
+ idx=idx,
+ anchor=anchor,
+ title=title,
+ url=url,
+ source_id=source_id_str,
+ )
+
+ return [refs_by_idx[i] for i in sorted(refs_by_idx.keys())]
+
+ def _add_bookmark(self, paragraph, name: str):
+ bookmark_id = self._bookmark_id_counter
+ self._bookmark_id_counter += 1
+
+ start = OxmlElement("w:bookmarkStart")
+ start.set(qn("w:id"), str(bookmark_id))
+ start.set(qn("w:name"), name)
+
+ end = OxmlElement("w:bookmarkEnd")
+ end.set(qn("w:id"), str(bookmark_id))
+
+ p = cast(Any, paragraph)._p
+ p.insert(0, start)
+ p.append(end)
+
+ def _add_internal_hyperlink(self, paragraph, display_text: str, anchor: str):
+ hyperlink = OxmlElement("w:hyperlink")
+ hyperlink.set(qn("w:anchor"), anchor)
+
+ new_run = OxmlElement("w:r")
+ rPr = OxmlElement("w:rPr")
+ rStyle = OxmlElement("w:rStyle")
+ rStyle.set(qn("w:val"), "Hyperlink")
+ rPr.append(rStyle)
+
+ new_run.append(rPr)
+ t = OxmlElement("w:t")
+ t.text = display_text
+ new_run.append(t)
+
+ hyperlink.append(new_run)
+ cast(Any, paragraph)._p.append(hyperlink)
+
+ def _add_references_section(self, doc: Document):
+ self.add_heading(doc, self._get_msg("references"), 2)
+
+ for ref in self._citation_refs:
+ para = doc.add_paragraph(style="List Number")
+ self._add_bookmark(para, ref.anchor)
+ # Include URL as an external link when available.
+ if ref.url:
+ self._add_hyperlink(para, ref.title, ref.url, display_text=ref.title)
+ else:
+ self._add_text_run(
+ para, ref.title, bold=False, italic=False, strike=False
+ )
+
+ def _parse_fence_info(self, info_raw: str) -> Tuple[str, List[str]]:
+ parts = [p for p in (info_raw or "").split() if p.strip()]
+ if not parts:
+ return "", []
+ return parts[0], parts[1:]
+
+ def _normalize_mermaid_text(self, source: str) -> str:
+ text = (source or "").replace("\r\n", "\n").replace("\r", "\n").strip()
+ return text + "\n"
+
+ def _prepare_mermaid_for_js(self, source: str) -> str:
+ """
+ Prepare Mermaid source for client-side rendering:
+ - strip title directives (caption already carries it),
+ """
+ text = self._strip_mermaid_title_for_render(source)
+ return text
+
+ def _png_with_text_chunk(self, png_bytes: bytes, keyword: str, value: str) -> bytes:
+ """
+ Ensure placeholder PNGs stay distinct in the DOCX package:
+ python-docx may deduplicate identical image bytes into one media part.
+ We insert a small tEXt chunk so each placeholder is unique, without changing
+ dimensions or requiring external imaging libraries.
+ """
+ if not png_bytes.startswith(b"\x89PNG\r\n\x1a\n"):
+ return png_bytes
+
+ keyword_b = (keyword or "owui").encode("latin-1", errors="ignore")[:79]
+ keyword_b = keyword_b.replace(b"\x00", b"") or b"owui"
+ value_b = (value or "").encode("latin-1", errors="ignore")
+ data = keyword_b + b"\x00" + value_b
+ chunk_type = b"tEXt"
+ crc = zlib.crc32(chunk_type + data) & 0xFFFFFFFF
+ chunk = (
+ struct.pack("!I", len(data)) + chunk_type + data + struct.pack("!I", crc)
+ )
+
+ out = bytearray()
+ out.extend(png_bytes[:8])
+ offset = 8
+ inserted = False
+ while offset + 8 <= len(png_bytes):
+ length = struct.unpack("!I", png_bytes[offset : offset + 4])[0]
+ ctype = png_bytes[offset + 4 : offset + 8]
+ chunk_total = 12 + length
+ if offset + chunk_total > len(png_bytes):
+ break
+ if ctype == b"IEND" and not inserted:
+ out.extend(chunk)
+ inserted = True
+ out.extend(png_bytes[offset : offset + chunk_total])
+ offset += chunk_total
+ if ctype == b"IEND":
+ break
+ if not inserted:
+ return png_bytes
+ return bytes(out)
+
+ def _make_mermaid_placeholder_png(self, seed: str) -> bytes:
+ return self._png_with_text_chunk(_TRANSPARENT_1PX_PNG, "owui", seed)
+
+ def _dummy_mermaid_svg_bytes(self) -> bytes:
+ return (
+ ' '
+ ).encode("utf-8")
+
+ def _insert_mermaid_placeholder(self, doc: Document, mermaid_source: str):
+ caption_title: Optional[str] = (
+ self._extract_mermaid_title(mermaid_source)
+ if self.valves.MERMAID_CAPTIONS_ENABLE
+ else None
+ )
+
+ source_for_render = mermaid_source
+ if self.valves.MERMAID_OPTIMIZE_LAYOUT:
+ source_for_render = re.sub(
+ r"^(graph|flowchart)\s+LR\b",
+ r"\1 TD",
+ source_for_render,
+ flags=re.MULTILINE | re.IGNORECASE,
+ )
+ source_for_render = self._prepare_mermaid_for_js(source_for_render)
+
+ self._mermaid_placeholder_counter += 1
+ seed = hashlib.sha256(
+ f"{self._mermaid_placeholder_counter}\n{source_for_render}".encode(
+ "utf-8", errors="replace"
+ )
+ ).hexdigest()[:16]
+ png_bytes = self._make_mermaid_placeholder_png(seed)
+
+ try:
+ shape = doc.add_picture(cast(Any, io.BytesIO(png_bytes)))
+ except Exception as e:
+ logger.warning(f"Failed to add Mermaid placeholder image: {e}")
+ self.add_paragraph(doc, f"[Mermaid placeholder failed: {e}]")
+ return
+ try:
+ doc.paragraphs[-1].alignment = WD_ALIGN_PARAGRAPH.CENTER
+ except Exception:
+ pass
+
+ # Attach a dummy SVG part so we can later overwrite it client-side (SVG+PNG).
+ self._attach_svg_blip(doc, shape, self._dummy_mermaid_svg_bytes())
+
+ try:
+ encoded = quote(source_for_render)
+ inline = shape._inline
+ docPr = inline.docPr
+ docPr.set("descr", f"MERMAID_SRC:{encoded}")
+ docPr.set("title", "Mermaid Diagram Placeholder")
+ except Exception as exc:
+ logger.warning(f"Failed to annotate Mermaid placeholder: {exc}")
+
+ self._add_mermaid_caption(doc, caption_title)
+
+ def _extract_mermaid_title(self, source: str) -> Optional[str]:
+ lines = self._normalize_mermaid_text(source).split("\n")
+ header_found = False
+ for raw in lines:
+ line = raw.strip()
+ if not line:
+ continue
+ if line.startswith("%%{") and line.endswith("}%%"):
+ continue
+ if line.startswith("%%"):
+ continue
+ # diagram header line
+ if not header_found:
+ header_found = True
+ # Mermaid beta/diagram headers can embed a title on the header line, e.g.:
+ # - radar-beta title Foo
+ # - xychart-beta title: "Foo"
+ mt = re.match(
+ r"^(?P\S.*?)(?:\s+title\s*:?\s+)(?P.+)$",
+ line,
+ re.IGNORECASE,
+ )
+ if mt:
+ title = (mt.group("title") or "").strip().strip('"').strip("'")
+ if title:
+ return title
+ continue
+
+ # title "Foo" / title Foo
+ m = re.match(r'^title\s*:?\s+"(.+)"\s*$', line, re.IGNORECASE)
+ if m:
+ return m.group(1).strip()
+ m = re.match(r"^title\s*:?\s+(.+)$", line, re.IGNORECASE)
+ if m:
+ return m.group(1).strip().strip('"').strip("'")
+ return None
+
+ def _strip_mermaid_title_for_render(self, source: str) -> str:
+ """
+ Removes Mermaid title directives from the source before rendering.
+ Captions already carry the title.
+ """
+ lines = self._normalize_mermaid_text(source).split("\n")
+ out: List[str] = []
+ header_found = False
+ title_stripped = False
+ meaningful_after_header = False
+
+ for raw in lines:
+ line = raw.rstrip("\n")
+ stripped = line.strip()
+
+ if not stripped:
+ out.append(line)
+ continue
+
+ if stripped.startswith("%%{") and stripped.endswith("}%%"):
+ out.append(line)
+ continue
+ if stripped.startswith("%%"):
+ out.append(line)
+ continue
+
+ if not header_found:
+ header_found = True
+ # Some Mermaid diagram headers can embed a title on the header line, e.g.:
+ # - radar-beta title Foo
+ # - xychart-beta title: "Foo"
+ mt = re.match(
+ r"^(?P\S.*?)(?:\s+title\s*:?\s+)(?P.+)$",
+ stripped,
+ re.IGNORECASE,
+ )
+ if mt:
+ cleaned = (mt.group("header") or "").strip()
+ out.append(cleaned if cleaned else stripped)
+ title_stripped = True
+ continue
+ out.append(line)
+ continue
+
+ if not title_stripped and not meaningful_after_header:
+ # Strip a standalone title directive line early in the diagram.
+ if re.match(r'^title\s*:?\s+(".+"|.+)$', stripped, re.IGNORECASE):
+ title_stripped = True
+ continue
+
+ # Consider this a meaningful content line after header.
+ meaningful_after_header = True
+ out.append(line)
+
+ return "\n".join(out).strip() + "\n"
+
+ def _ensure_caption_style(self, doc: Document) -> str:
+ if self._caption_style_name is not None:
+ return self._caption_style_name
+
+ style_name = (self.valves.MERMAID_CAPTION_STYLE or "").strip()
+ if style_name == "":
+ # Empty means: do not apply a caption style.
+ self._caption_style_name = ""
+ return ""
+
+ # Prefer existing style if present.
+ try:
+ _ = doc.styles[style_name]
+ self._caption_style_name = style_name
+ return style_name
+ except KeyError:
+ pass
+
+ # If user requested "Caption" but it's missing, create a safe custom style name.
+ if style_name.lower() == "caption":
+ style_name = "OWUI Caption"
+
+ try:
+ _ = doc.styles[style_name]
+ self._caption_style_name = style_name
+ return style_name
+ except KeyError:
+ pass
+
+ try:
+ style = doc.styles.add_style(style_name, WD_STYLE_TYPE.PARAGRAPH)
+ style.font.name = "Calibri"
+ style.font.size = Pt(9)
+ style.font.color.rgb = RGBColor(80, 80, 80)
+ style.paragraph_format.space_before = Pt(2)
+ style.paragraph_format.space_after = Pt(8)
+ self._caption_style_name = style_name
+ return style_name
+ except Exception:
+ self._caption_style_name = "Normal"
+ return "Normal"
+
+ def _add_mermaid_caption(self, doc: Document, title: Optional[str]):
+ if not self.valves.MERMAID_CAPTIONS_ENABLE:
+ return
+
+ # Use configured prefix, or auto-detect from user language
+ prefix = (self.valves.MERMAID_CAPTION_PREFIX or "").strip()
+ if prefix == "":
+ prefix = self._get_msg("figure_prefix")
+
+ if prefix == "" and not title:
+ return
+
+ self._mermaid_figure_counter += 1
+ if prefix == "":
+ caption = title or ""
+ else:
+ base = f"{prefix} {self._mermaid_figure_counter}"
+ caption = f"{base}: {title}" if title else base
+ if caption == "":
+ return
+
+ para = doc.add_paragraph()
+ style_name = self._ensure_caption_style(doc)
+ if style_name:
+ para.style = style_name
+ para.alignment = WD_ALIGN_PARAGRAPH.CENTER
+ self.add_formatted_text(para, caption)
+
+ def _available_block_width(self, doc: Document):
+ section = doc.sections[0]
+ return section.page_width - section.left_margin - section.right_margin
+
+ def _attach_svg_blip(self, doc: Document, inline_shape: Any, svg_bytes: bytes):
+ if not svg_bytes:
+ return
+
+ try:
+ pkg = doc.part.package
+ partname = pkg.next_partname("/word/media/image%d.svg")
+ from docx.opc.part import Part
+
+ svg_part = Part(partname, "image/svg+xml", svg_bytes)
+ rid_svg = doc.part.relate_to(svg_part, RT.IMAGE)
+
+ inline = inline_shape._inline
+ blips = inline.xpath(".//a:blip")
+ if not blips:
+ return
+ blip = blips[0]
+
+ existing = blip.xpath(".//asvg:svgBlip")
+ if existing:
+ existing[0].set(qn("r:embed"), rid_svg)
+ return
+
+ extLst = OxmlElement("a:extLst")
+ ext = OxmlElement("a:ext")
+ ext.set("uri", "{96DAC541-7B7A-43D3-8B79-37D633B846F1}")
+
+ svgBlip = OxmlElement("asvg:svgBlip")
+ svgBlip.set(qn("r:embed"), rid_svg)
+ ext.append(svgBlip)
+ extLst.append(ext)
+ blip.append(extLst)
+ except Exception as exc:
+ logger.warning(f"Failed to attach SVG blip; keeping PNG fallback: {exc}")
+
+ # (Mermaid warning paragraphs removed)
+
+ def set_document_default_font(self, doc: Document):
+ """Set document default font using configured fonts."""
+ style = doc.styles["Normal"]
+ font = style.font
+ font.name = self.valves.FONT_LATIN
+ font.size = Pt(11)
+
+ # Ensure rPr element exists
+ rPr = style._element.get_or_add_rPr()
+ rFonts = rPr.get_or_add_rFonts()
+
+ # Set Latin and Asian fonts explicitly
+ rFonts.set(qn("w:ascii"), self.valves.FONT_LATIN)
+ rFonts.set(qn("w:hAnsi"), self.valves.FONT_LATIN)
+ rFonts.set(qn("w:eastAsia"), self.valves.FONT_ASIAN)
+
+ # CRITICAL: Clear theme fonts to prevent Word from overriding with defaults (like SimSun)
+ rFonts.set(qn("w:asciiTheme"), "")
+ rFonts.set(qn("w:hAnsiTheme"), "")
+ rFonts.set(qn("w:eastAsiaTheme"), "")
+ rFonts.set(qn("w:cstheme"), "")
+
+ # Set language to zh-CN to prevent MS Gothic fallback (Japanese font)
+ # Even for English interface, we want to prioritize Chinese glyphs over Japanese for CJK
+ lang = rPr.find(qn("w:lang"))
+ if lang is None:
+ lang = OxmlElement("w:lang")
+ rPr.append(lang)
+ lang.set(qn("w:val"), "en-US")
+ lang.set(qn("w:eastAsia"), "zh-CN")
+
+ logger.info(
+ f"[Font Config] Latin: {self.valves.FONT_LATIN}, Asian: {self.valves.FONT_ASIAN}"
+ )
+
+ # Set paragraph format
+ paragraph_format = style.paragraph_format
+ paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE
+ paragraph_format.space_after = Pt(6)
+
+ # Configure Title style (used for document title)
+ # Standard format: 22pt (二号), bold, centered, 24pt space after
+ if "Title" in doc.styles:
+ title_style = doc.styles["Title"]
+ title_font = title_style.font
+ title_font.name = self.valves.FONT_LATIN
+ title_font.size = Pt(22) # 二号字体
+ title_font.bold = True
+ title_font.color.rgb = RGBColor(0, 0, 0)
+
+ # Set paragraph format: alignment based on configuration
+ title_pf = title_style.paragraph_format
+ alignment_map = {
+ "left": WD_ALIGN_PARAGRAPH.LEFT,
+ "center": WD_ALIGN_PARAGRAPH.CENTER,
+ "right": WD_ALIGN_PARAGRAPH.RIGHT,
+ }
+ title_pf.alignment = alignment_map.get(
+ self.valves.TITLE_ALIGNMENT.lower(), WD_ALIGN_PARAGRAPH.CENTER
+ )
+ title_pf.space_before = Pt(0)
+ title_pf.space_after = Pt(24)
+
+ # Explicitly disable underline and borders for Title style
+ title_font.underline = False
+ title_p_el = title_style._element.get_or_add_pPr()
+ title_pbdr = title_p_el.find(qn("w:pBdr"))
+ if title_pbdr is not None:
+ title_p_el.remove(title_pbdr)
+
+ t_rPr = title_style._element.get_or_add_rPr()
+ t_rFonts = t_rPr.get_or_add_rFonts()
+ t_rFonts.set(qn("w:ascii"), self.valves.FONT_LATIN)
+ t_rFonts.set(qn("w:hAnsi"), self.valves.FONT_LATIN)
+ t_rFonts.set(qn("w:eastAsia"), self.valves.FONT_ASIAN)
+
+ # Clear theme fonts for Title
+ t_rFonts.set(qn("w:asciiTheme"), "")
+ t_rFonts.set(qn("w:hAnsiTheme"), "")
+ t_rFonts.set(qn("w:eastAsiaTheme"), "")
+
+ t_lang = t_rPr.find(qn("w:lang"))
+ if t_lang is None:
+ t_lang = OxmlElement("w:lang")
+ t_rPr.append(t_lang)
+ t_lang.set(qn("w:val"), "en-US")
+ t_lang.set(qn("w:eastAsia"), "zh-CN")
+
+ # Standard heading sizes based on Chinese document standards:
+ # Heading 1: 16pt (三号), bold, space before 24pt, space after 12pt
+ # Heading 2: 15pt (小三), bold, space before 18pt, space after 6pt
+ # Heading 3: 14pt (四号), bold, space before 12pt, space after 6pt
+ # Heading 4-9: 12pt (小四), bold, gradually reduced spacing
+ heading_formats = {
+ 1: {"size": 16, "space_before": 24, "space_after": 12},
+ 2: {"size": 15, "space_before": 18, "space_after": 6},
+ 3: {"size": 14, "space_before": 12, "space_after": 6},
+ 4: {"size": 12, "space_before": 12, "space_after": 6},
+ 5: {"size": 12, "space_before": 6, "space_after": 6},
+ 6: {"size": 11, "space_before": 6, "space_after": 3},
+ 7: {"size": 11, "space_before": 6, "space_after": 3},
+ 8: {"size": 10.5, "space_before": 6, "space_after": 3},
+ 9: {"size": 10.5, "space_before": 6, "space_after": 3},
+ }
+
+ # Apply font and formatting settings to Heading 1-9
+ for i in range(1, 10):
+ style_id = f"Heading {i}"
+ if style_id in doc.styles:
+ heading_style = doc.styles[style_id]
+ heading_font = heading_style.font
+ heading_font.color.rgb = RGBColor(0, 0, 0)
+
+ # Determine fonts to use (fallback to document defaults)
+ if i == 1:
+ target_latin = (
+ self.valves.FONT_H1_LATIN.strip() or self.valves.FONT_LATIN
+ )
+ target_asian = (
+ self.valves.FONT_H1_ASIAN.strip() or self.valves.FONT_ASIAN
+ )
+ elif i == 2:
+ target_latin = (
+ self.valves.FONT_H2_LATIN.strip() or self.valves.FONT_LATIN
+ )
+ target_asian = (
+ self.valves.FONT_H2_ASIAN.strip() or self.valves.FONT_ASIAN
+ )
+ else:
+ target_latin = self.valves.FONT_LATIN
+ target_asian = self.valves.FONT_ASIAN
+
+ heading_font.name = target_latin
+
+ # Apply standard formatting (size, bold, spacing)
+ fmt = heading_formats.get(
+ i, {"size": 11, "space_before": 6, "space_after": 3}
+ )
+ heading_font.size = Pt(fmt["size"])
+ heading_font.bold = True
+
+ heading_pf = heading_style.paragraph_format
+ heading_pf.space_before = Pt(fmt["space_before"])
+ heading_pf.space_after = Pt(fmt["space_after"])
+
+ # Explicitly disable underline and borders for Heading style
+ heading_font.underline = False
+ h_p_el = heading_style._element.get_or_add_pPr()
+ h_pbdr = h_p_el.find(qn("w:pBdr"))
+ if h_pbdr is not None:
+ h_p_el.remove(h_pbdr)
+
+ # Ensure rPr exists
+ h_rPr = heading_style._element.get_or_add_rPr()
+ h_rFonts = h_rPr.get_or_add_rFonts()
+
+ # Set Latin and Asian fonts explicitly in XML
+ h_rFonts.set(qn("w:ascii"), target_latin)
+ h_rFonts.set(qn("w:hAnsi"), target_latin)
+ h_rFonts.set(qn("w:eastAsia"), target_asian)
+
+ # Clear theme fonts for Headings
+ h_rFonts.set(qn("w:asciiTheme"), "")
+ h_rFonts.set(qn("w:hAnsiTheme"), "")
+ h_rFonts.set(qn("w:eastAsiaTheme"), "")
+
+ # Set language to zh-CN
+ h_lang = h_rPr.find(qn("w:lang"))
+ if h_lang is None:
+ h_lang = OxmlElement("w:lang")
+ h_rPr.append(h_lang)
+ h_lang.set(qn("w:val"), "en-US")
+ h_lang.set(qn("w:eastAsia"), "zh-CN")
+
+ def _remove_emojis(self, text: str) -> str:
+ """Remove emojis from text based on unicode ranges."""
+ if not isinstance(text, str):
+ return ""
+
+ def _is_emoji_codepoint(codepoint: int) -> bool:
+ # Common emoji ranges + flag regional indicators.
+ return (
+ 0x1F000 <= codepoint <= 0x1FAFF
+ or 0x1F1E6 <= codepoint <= 0x1F1FF
+ or 0x2600 <= codepoint <= 0x26FF
+ or 0x2700 <= codepoint <= 0x27BF
+ or 0x2300 <= codepoint <= 0x23FF
+ or 0x2B00 <= codepoint <= 0x2BFF
+ )
+
+ def _is_emoji_modifier(codepoint: int) -> bool:
+ # VS15/VS16, ZWJ, keycap, skin tones, and tag characters used in some emoji sequences.
+ return (
+ codepoint in (0x200D, 0xFE0E, 0xFE0F, 0x20E3)
+ or 0x1F3FB <= codepoint <= 0x1F3FF
+ or 0xE0020 <= codepoint <= 0xE007F
+ )
+
+ return "".join(
+ ch
+ for ch in text
+ if not (_is_emoji_codepoint(ord(ch)) or _is_emoji_modifier(ord(ch)))
+ )
+
+ def add_heading(self, doc: Document, text: str, level: int):
+ """Add heading"""
+ # Word heading levels start from 0, Markdown from 1
+ heading_level = min(level, 9) # Word supports up to Heading 9
+ heading = doc.add_heading(level=heading_level)
+
+ # Parse and add formatted text
+ self.add_formatted_text(heading, text)
+
+ def add_paragraph(self, doc: Document, text: str):
+ """Add paragraph with inline formatting support"""
+ paragraph = doc.add_paragraph()
+ self.add_formatted_text(paragraph, text)
+
+ def add_formatted_text(self, paragraph, text: str):
+ """
+ Parse Markdown inline formatting and add to paragraph.
+ Supports: bold, italic, inline code, links, strikethrough, auto-link URLs,
+ and inline LaTeX math \\(...\\) when MATH_ENABLE is on.
+ """
+ self._add_inline_segments(
+ paragraph, text or "", bold=False, italic=False, strike=False
+ )
+
+ def _add_text_run(self, paragraph, s: str, bold: bool, italic: bool, strike: bool):
+ if not s:
+ return
+ run = paragraph.add_run(s)
+ if bold:
+ run.bold = True
+ if italic:
+ run.italic = True
+ if strike:
+ run.font.strike = True
+
+ # Explicitly set East Asian font at Run level for heading paragraphs.
+ # Style-level fonts alone are unreliable for headings because Word's theme
+ # font inheritance (w:eastAsiaTheme) on the run's rPr can override style-level
+ # rFonts. Setting it here ensures SimHei (or the configured heading font) wins
+ # regardless of the document template or theme settings.
+ style_name = getattr(getattr(paragraph, "style", None), "name", "") or ""
+ if style_name.startswith("Heading"):
+ # Extract heading level number from style name (e.g., "Heading 1" → 1)
+ parts = style_name.split()
+ heading_level = int(parts[1]) if len(parts) == 2 and parts[1].isdigit() else 0
+ if heading_level == 1:
+ target_asian = (
+ self.valves.FONT_H1_ASIAN.strip() or self.valves.FONT_ASIAN
+ )
+ elif heading_level == 2:
+ target_asian = (
+ self.valves.FONT_H2_ASIAN.strip() or self.valves.FONT_ASIAN
+ )
+ else:
+ target_asian = self.valves.FONT_ASIAN
+
+ rPr = run._element.get_or_add_rPr()
+ rFonts = rPr.get_or_add_rFonts()
+ rFonts.set(qn("w:eastAsia"), target_asian)
+ # Clear theme font to prevent Word from overriding our explicit font choice
+ rFonts.set(qn("w:eastAsiaTheme"), "")
+
+ def _add_inline_code(self, paragraph, s: str):
+ if s == "":
+ return
+
+ def _add_code_run(chunk: str):
+ if not chunk:
+ return
+ run = paragraph.add_run(chunk)
+ run.font.name = self.valves.FONT_CODE
+ run._element.rPr.rFonts.set(qn("w:eastAsia"), self.valves.FONT_CODE)
+ run.font.size = Pt(10)
+ shading = OxmlElement("w:shd")
+ shading.set(qn("w:fill"), "E8E8E8")
+ run._element.rPr.append(shading)
+
+ i = 0
+ for m in _AUTO_URL_RE.finditer(s):
+ start, end = m.span()
+ if start > i:
+ _add_code_run(s[i:start])
+
+ raw = m.group(0)
+ trimmed = raw
+ while trimmed and trimmed[-1] in ".,;:!?)]}":
+ trimmed = trimmed[:-1]
+ suffix = raw[len(trimmed) :]
+
+ normalized = self._normalize_url(trimmed)
+ if normalized:
+ self._add_hyperlink_code(
+ paragraph, display_text=trimmed, url=normalized
+ )
+ else:
+ _add_code_run(raw)
+
+ if suffix:
+ _add_code_run(suffix)
+
+ i = end
+
+ if i < len(s):
+ _add_code_run(s[i:])
+
+ def _add_hyperlink_code(self, paragraph, display_text: str, url: str):
+ u = self._normalize_url(url)
+ if not u:
+ self._add_inline_code(paragraph, display_text)
+ return
+
+ part = getattr(paragraph, "part", None)
+ if part is None or not hasattr(part, "relate_to"):
+ self._add_inline_code(paragraph, display_text)
+ return
+
+ r_id = part.relate_to(u, RT.HYPERLINK, is_external=True)
+
+ hyperlink = OxmlElement("w:hyperlink")
+ hyperlink.set(qn("r:id"), r_id)
+
+ new_run = OxmlElement("w:r")
+ rPr = OxmlElement("w:rPr")
+
+ rFonts = OxmlElement("w:rFonts")
+ rFonts.set(qn("w:ascii"), self.valves.FONT_CODE)
+ rFonts.set(qn("w:hAnsi"), self.valves.FONT_CODE)
+ rFonts.set(qn("w:eastAsia"), self.valves.FONT_CODE)
+ rPr.append(rFonts)
+
+ sz = OxmlElement("w:sz")
+ sz.set(qn("w:val"), "20") # 10pt
+ rPr.append(sz)
+ sz_cs = OxmlElement("w:szCs")
+ sz_cs.set(qn("w:val"), "20")
+ rPr.append(sz_cs)
+
+ shading = OxmlElement("w:shd")
+ shading.set(qn("w:fill"), "E8E8E8")
+ rPr.append(shading)
+
+ new_run.append(rPr)
+
+ t = OxmlElement("w:t")
+ t.text = display_text
+ new_run.append(t)
+
+ hyperlink.append(new_run)
+ cast(Any, paragraph)._p.append(hyperlink)
+
+ def _add_inline_segments(
+ self, paragraph, text: str, bold: bool, italic: bool, strike: bool
+ ):
+ i = 0
+ n = len(text)
+
+ def next_special(start: int) -> int:
+ candidates = []
+ for ch in ("`", "!", "[", "*", "_", "~", "$", "\\"):
+ idx = text.find(ch, start)
+ if idx != -1:
+ candidates.append(idx)
+ idx = text.find(r"\(", start)
+ if idx != -1:
+ candidates.append(idx)
+ idx = text.find("http://", start)
+ if idx != -1:
+ candidates.append(idx)
+ idx = text.find("https://", start)
+ if idx != -1:
+ candidates.append(idx)
+ idx = text.find("www.", start)
+ if idx != -1:
+ candidates.append(idx)
+ return min(candidates) if candidates else n
+
+ while i < n:
+ # Markdown image: 
+ if text.startswith("![", i):
+ close = text.find("]", i + 2)
+ if close != -1 and close + 1 < n and text[close + 1] == "(":
+ close_paren = text.find(")", close + 2)
+ if close_paren != -1:
+ alt = text[i + 2 : close]
+ url = text[close + 2 : close_paren].strip()
+ # Allow angle-bracket wrapped URLs: ![]()
+ if url.startswith("<") and url.endswith(">") and len(url) >= 2:
+ url = url[1:-1].strip()
+ self._embed_markdown_image(paragraph, alt=alt, url=url)
+ i = close_paren + 1
+ continue
+
+ if text[i] == "`":
+ j = text.find("`", i + 1)
+ if j != -1:
+ self._add_inline_code(paragraph, text[i + 1 : j])
+ i = j + 1
+ continue
+
+ if text.startswith(r"\(", i):
+ j = text.find(r"\)", i + 2)
+ if j != -1:
+ self._add_inline_equation(
+ paragraph,
+ text[i + 2 : j],
+ bold=bold,
+ italic=italic,
+ strike=strike,
+ )
+ i = j + 2
+ continue
+
+ # Handle backslash escapes
+ if text[i] == "\\":
+ if i + 1 < n:
+ ch = text[i + 1]
+ # Standard Markdown escapes + $ for math
+ if ch in "\\`*_{}[]()#+-.!|$":
+ self._add_text_run(paragraph, ch, bold, italic, strike)
+ i += 2
+ continue
+ # Keep other backslashes literal
+ self._add_text_run(paragraph, "\\", bold, italic, strike)
+ i += 1
+ continue
+
+ # Handle long run of underscores (fill-in-the-blank)
+ if text[i] == "_":
+ run_len = 0
+ while i + run_len < n and text[i + run_len] == "_":
+ run_len += 1
+ if run_len >= 4:
+ self._add_text_run(
+ paragraph, text[i : i + run_len], bold, italic, strike
+ )
+ i += run_len
+ continue
+
+ # Handle long run of asterisks (separator/mask)
+ if text[i] == "*":
+ run_len = 0
+ while i + run_len < n and text[i + run_len] == "*":
+ run_len += 1
+ if run_len >= 4:
+ self._add_text_run(
+ paragraph, text[i : i + run_len], bold, italic, strike
+ )
+ i += run_len
+ continue
+
+ # Handle long run of tildes (separator)
+ if text[i] == "~":
+ run_len = 0
+ while i + run_len < n and text[i + run_len] == "~":
+ run_len += 1
+ if run_len >= 4:
+ self._add_text_run(
+ paragraph, text[i : i + run_len], bold, italic, strike
+ )
+ i += run_len
+ continue
+
+ # Inline $...$ math (conservative parsing)
+ if (
+ text[i] == "$"
+ and self.valves.MATH_ENABLE
+ and self.valves.MATH_INLINE_DOLLAR_ENABLE
+ ):
+ # Avoid treating $$ as inline math here (block math uses $$ on its own line).
+ if text.startswith("$$", i):
+ self._add_text_run(paragraph, "$", bold, italic, strike)
+ i += 1
+ continue
+
+ # Markdown-ish heuristics to reduce false positives:
+ # - Do not allow whitespace right after opening or right before closing
+ # - Avoid cases like "USD$5" where opening is attached to an alnum
+ if i + 1 >= n or text[i + 1].isspace():
+ self._add_text_run(paragraph, "$", bold, italic, strike)
+ i += 1
+ continue
+ if i > 0 and text[i - 1].isalnum():
+ self._add_text_run(paragraph, "$", bold, italic, strike)
+ i += 1
+ continue
+
+ j = i + 1
+ while True:
+ j = text.find("$", j)
+ if j == -1:
+ break
+ # Skip escaped dollars inside: "\$"
+ if j > 0 and text[j - 1] == "\\":
+ j += 1
+ continue
+ break
+
+ if j != -1:
+ inner = text[i + 1 : j]
+ if (
+ inner
+ and "\n" not in inner
+ and not inner[0].isspace()
+ and not inner[-1].isspace()
+ ):
+ # Treat "$5" as currency more often than math.
+ if _CURRENCY_NUMBER_RE.match(inner) and (
+ i == 0 or text[i - 1].isspace()
+ ):
+ self._add_text_run(paragraph, "$", bold, italic, strike)
+ i += 1
+ continue
+ # Disallow digit immediately following the closing $ (common in prices like "$5.00" already handled above).
+ if j + 1 < n and text[j + 1].isdigit():
+ self._add_text_run(paragraph, "$", bold, italic, strike)
+ i += 1
+ continue
+ self._add_inline_equation(
+ paragraph, inner, bold=bold, italic=italic, strike=strike
+ )
+ i = j + 1
+ continue
+
+ self._add_text_run(paragraph, "$", bold, italic, strike)
+ i += 1
+ continue
+
+ if text.startswith("~~", i):
+ j = text.find("~~", i + 2)
+ if j != -1:
+ self._add_inline_segments(
+ paragraph,
+ text[i + 2 : j],
+ bold=bold,
+ italic=italic,
+ strike=True,
+ )
+ i = j + 2
+ continue
+
+ if text.startswith("**", i):
+ j = text.find("**", i + 2)
+ if j != -1:
+ self._add_inline_segments(
+ paragraph,
+ text[i + 2 : j],
+ bold=True,
+ italic=italic,
+ strike=strike,
+ )
+ i = j + 2
+ continue
+
+ if text.startswith("__", i):
+ j = text.find("__", i + 2)
+ if j != -1:
+ self._add_inline_segments(
+ paragraph,
+ text[i + 2 : j],
+ bold=True,
+ italic=italic,
+ strike=strike,
+ )
+ i = j + 2
+ continue
+
+ if text[i] == "*" and (i + 1 >= n or text[i + 1] != "*"):
+ j = text.find("*", i + 1)
+ if j != -1:
+ self._add_inline_segments(
+ paragraph,
+ text[i + 1 : j],
+ bold=bold,
+ italic=True,
+ strike=strike,
+ )
+ i = j + 1
+ continue
+
+ if text[i] == "_" and (i + 1 >= n or text[i + 1] != "_"):
+ j = text.find("_", i + 1)
+ if j != -1:
+ self._add_inline_segments(
+ paragraph,
+ text[i + 1 : j],
+ bold=bold,
+ italic=True,
+ strike=strike,
+ )
+ i = j + 1
+ continue
+
+ if text[i] == "[":
+ close = text.find("]", i + 1)
+ if close != -1 and close + 1 < n and text[close + 1] == "(":
+ close_paren = text.find(")", close + 2)
+ if close_paren != -1:
+ label = text[i + 1 : close]
+ url = text[close + 2 : close_paren]
+ self._add_hyperlink(paragraph, label, url)
+ i = close_paren + 1
+ continue
+ # Citation marker like [12] -> internal link to References.
+ if close != -1:
+ inner = text[i + 1 : close].strip()
+ if inner.isdigit():
+ idx = int(inner)
+ anchor = self._citation_anchor_by_index.get(idx)
+ if anchor:
+ self._add_internal_hyperlink(paragraph, f"[{idx}]", anchor)
+ i = close + 1
+ continue
+
+ m = _AUTO_URL_RE.match(text, i)
+ if m:
+ raw = m.group(0)
+ trimmed = raw
+ while trimmed and trimmed[-1] in ".,;:!?)]}":
+ trimmed = trimmed[:-1]
+ suffix = raw[len(trimmed) :]
+
+ normalized = self._normalize_url(trimmed)
+ if normalized:
+ # Display the original (trimmed) text; use normalized URL as the target.
+ self._add_hyperlink(
+ paragraph, trimmed, normalized, display_text=trimmed
+ )
+ else:
+ self._add_text_run(paragraph, raw, bold, italic, strike)
+ i += len(raw)
+ continue
+
+ if suffix:
+ self._add_text_run(paragraph, suffix, bold, italic, strike)
+ i += len(raw)
+ continue
+
+ j = next_special(i)
+ if j == i:
+ # Unmatched special character; treat literally to avoid infinite loops.
+ self._add_text_run(paragraph, text[i], bold, italic, strike)
+ i += 1
+ else:
+ self._add_text_run(paragraph, text[i:j], bold, italic, strike)
+ i = j
+
+ def _normalize_url(self, url: str) -> str:
+ u = (url or "").strip()
+ if u.lower().startswith("www."):
+ u = "https://" + u
+
+ # Trim common trailing punctuation that often follows URLs in prose.
+ while u and u[-1] in ".,;:!?)]}":
+ u = u[:-1]
+ return u
+
+ def _add_hyperlink(
+ self, paragraph, text: str, url: str, display_text: Optional[str] = None
+ ):
+ u = self._normalize_url(url)
+ if not u:
+ run = paragraph.add_run(display_text or text)
+ # Set East Asian font to prevent MS Gothic fallback
+ rPr = run._element.get_or_add_rPr()
+ rFonts = rPr.get_or_add_rFonts()
+ rFonts.set(qn("w:eastAsia"), self.valves.FONT_ASIAN)
+ return
+
+ part = getattr(paragraph, "part", None)
+ if part is None or not hasattr(part, "relate_to"):
+ # Fallback if relationship API isn't available.
+ run = paragraph.add_run(display_text or text)
+ run.font.color.rgb = RGBColor(0, 0, 255)
+ run.font.underline = True
+ # Set East Asian font to prevent MS Gothic fallback
+ rPr = run._element.get_or_add_rPr()
+ rFonts = rPr.get_or_add_rFonts()
+ rFonts.set(qn("w:eastAsia"), self.valves.FONT_ASIAN)
+ return
+
+ r_id = part.relate_to(u, RT.HYPERLINK, is_external=True)
+
+ hyperlink = OxmlElement("w:hyperlink")
+ hyperlink.set(qn("r:id"), r_id)
+
+ new_run = OxmlElement("w:r")
+ rPr = OxmlElement("w:rPr")
+ rStyle = OxmlElement("w:rStyle")
+ rStyle.set(qn("w:val"), "Hyperlink")
+ rPr.append(rStyle)
+
+ # Set East Asian font to prevent MS Gothic fallback
+ rFonts = OxmlElement("w:rFonts")
+ rFonts.set(qn("w:eastAsia"), self.valves.FONT_ASIAN)
+ rPr.append(rFonts)
+
+ color = OxmlElement("w:color")
+ color.set(qn("w:val"), "0000FF")
+ rPr.append(color)
+
+ u_el = OxmlElement("w:u")
+ u_el.set(qn("w:val"), "single")
+ rPr.append(u_el)
+
+ new_run.append(rPr)
+
+ t = OxmlElement("w:t")
+ t.text = display_text or text
+ new_run.append(t)
+
+ hyperlink.append(new_run)
+ cast(Any, paragraph)._p.append(hyperlink)
+
+ def _add_inline_equation(
+ self,
+ paragraph,
+ latex: str,
+ bold: bool = False,
+ italic: bool = False,
+ strike: bool = False,
+ ):
+ latex = (latex or "").strip()
+ if not latex:
+ return
+
+ if not self.valves.MATH_ENABLE or not LATEX_MATH_AVAILABLE:
+ self._add_text_run(
+ paragraph, f"\\({latex}\\)", bold=bold, italic=italic, strike=strike
+ )
+ return
+
+ try:
+ mathml = latex_to_mathml(latex)
+ omml = mathml2omml.convert(mathml)
+ o_math = self._omml_oMath_element(omml)
+ run = paragraph.add_run()
+ run.bold = bold
+ run.italic = italic
+ run.font.strike = strike
+ cast(Any, run)._r.append(o_math)
+ except Exception as exc:
+ logger.warning(f"Inline math conversion failed; keeping literal: {exc}")
+ self._add_text_run(
+ paragraph, f"\\({latex}\\)", bold=bold, italic=italic, strike=strike
+ )
+
+ def _omml_oMath_element(self, omml: str):
+ # Ensure the OMML element declares the math namespace so parse_xml works.
+ m_ns = "http://schemas.openxmlformats.org/officeDocument/2006/math"
+ s = (omml or "").strip()
+ if s.startswith("") and s.endswith(" "):
+ inner = s[len("") : -len(" ")]
+ s = f'{inner} '
+ elif s.startswith("", 1)[0]:
+ s = s.replace(" str:
+ c = c.strip().lstrip("#")
+ if re.fullmatch(r"[0-9A-Fa-f]{6}", c):
+ return c
+ return default
+
+ header_fill = _validate_hex(self.valves.TABLE_HEADER_COLOR, "F2F2F2")
+ zebra_fill = _validate_hex(self.valves.TABLE_ZEBRA_COLOR, "FBFBFB")
+
+ def _split_row(line: str) -> List[str]:
+ # Keep empty cells, trim surrounding pipes.
+ raw = line.strip().strip("|")
+ return [c.strip() for c in raw.split("|")]
+
+ def _is_separator_row(cells: List[str]) -> bool:
+ # Markdown separator: --- / :--- / ---: / :---:
+ if not cells:
+ return False
+ ok = 0
+ for c in cells:
+ c = c.strip()
+ if re.fullmatch(r":?-{3,}:?", c):
+ ok += 1
+ return ok == len(cells)
+
+ def _col_align(cell: str) -> WD_ALIGN_PARAGRAPH:
+ s = (cell or "").strip()
+ if s.startswith(":") and s.endswith(":"):
+ return WD_ALIGN_PARAGRAPH.CENTER
+ if s.endswith(":"):
+ return WD_ALIGN_PARAGRAPH.RIGHT
+ return WD_ALIGN_PARAGRAPH.LEFT
+
+ def _set_cell_shading(cell, fill: str):
+ tc_pr = cell._element.get_or_add_tcPr()
+ shd = OxmlElement("w:shd")
+ shd.set(qn("w:fill"), fill)
+ tc_pr.append(shd)
+
+ raw_rows = [_split_row(l) for l in table_lines if l.strip().startswith("|")]
+ if not raw_rows:
+ return
+
+ sep_idx = 1 if len(raw_rows) > 1 and _is_separator_row(raw_rows[1]) else -1
+ header = raw_rows[0]
+ body = raw_rows[sep_idx + 1 :] if sep_idx >= 0 else raw_rows[1:]
+
+ num_cols = max(len(header), *(len(r) for r in body)) if body else len(header)
+ header = header + [""] * (num_cols - len(header))
+ body = [r + [""] * (num_cols - len(r)) for r in body]
+
+ aligns = [
+ _col_align(c) for c in (raw_rows[1] if sep_idx == 1 else [""] * num_cols)
+ ]
+
+ table = doc.add_table(rows=1 + len(body), cols=num_cols)
+ table.style = "Table Grid"
+ table.alignment = WD_TABLE_ALIGNMENT.LEFT
+ cast(Any, table).autofit = False
+
+ # Cell margins (twips): smaller padding for compact tables.
+ self._set_table_cell_margins(table, top=60, bottom=60, left=90, right=90)
+
+ # Column widths: proportional to content, bounded, then normalized to page width.
+ available_width = int(self._available_block_width(doc))
+ min_col = max(int(Inches(0.55)), available_width // max(1, num_cols * 3))
+
+ def _plain_len(s: str) -> int:
+ t = re.sub(r"`([^`]+)`", r"\1", s or "")
+ t = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r"\1", t)
+ t = re.sub(r"\s+", " ", t).strip()
+ return len(t)
+
+ weights: List[int] = []
+ for ci in range(num_cols):
+ max_len = _plain_len(header[ci])
+ for r in body:
+ max_len = max(max_len, _plain_len(r[ci]))
+ weights.append(max(1, min(max_len, 40)))
+
+ sum_w = sum(weights) or 1
+ widths = [max(min_col, int(available_width * w / sum_w)) for w in weights]
+ total = sum(widths)
+ if total > available_width:
+ even = max(1, available_width // max(1, num_cols))
+ widths = [even] * num_cols
+ total = sum(widths)
+ if total < available_width:
+ rem = available_width - total
+ order = sorted(range(num_cols), key=lambda i: weights[i], reverse=True)
+ oi = 0
+ while rem > 0 and order:
+ widths[order[oi % len(order)]] += 1
+ rem -= 1
+ oi += 1
+
+ for ci, w in enumerate(widths):
+ table.columns[ci].width = w
+ for row in table.rows:
+ row.cells[ci].width = w
+
+ def _format_cell_paragraph(para, align: WD_ALIGN_PARAGRAPH):
+ para.alignment = align
+ pf = para.paragraph_format
+ pf.space_before = Pt(0)
+ pf.space_after = Pt(0)
+ pf.line_spacing_rule = WD_LINE_SPACING.SINGLE
+
+ def _fill_cell(cell, text: str, align: WD_ALIGN_PARAGRAPH, bold: bool = False):
+ cell.text = ""
+ parts = [
+ p for p in re.split(r"(?: |\n)", text or "") if p is not None
+ ]
+ if not parts:
+ parts = [""]
+ for pi, part in enumerate(parts):
+ para = cell.paragraphs[0] if pi == 0 else cell.add_paragraph()
+ _format_cell_paragraph(para, align)
+ self.add_formatted_text(para, part)
+ for run in para.runs:
+ run.font.size = Pt(9)
+ if bold:
+ run.bold = True
+
+ # Header row
+ header_row = table.rows[0]
+ self._set_table_header_row_repeat(header_row)
+ for ci in range(num_cols):
+ cell = header_row.cells[ci]
+ _set_cell_shading(cell, header_fill)
+ _fill_cell(
+ cell,
+ header[ci],
+ aligns[ci] if ci < len(aligns) else WD_ALIGN_PARAGRAPH.LEFT,
+ bold=True,
+ )
+
+ # Body rows
+ for ri, row_data in enumerate(body, start=1):
+ row = table.rows[ri]
+ for ci in range(num_cols):
+ cell = row.cells[ci]
+ if (ri % 2) == 0:
+ _set_cell_shading(cell, zebra_fill)
+ _fill_cell(
+ cell,
+ row_data[ci],
+ aligns[ci] if ci < len(aligns) else WD_ALIGN_PARAGRAPH.LEFT,
+ )
+
+ def _set_table_cell_margins(
+ self, table, top: int, bottom: int, left: int, right: int
+ ):
+ tbl_pr = cast(Any, table)._tbl.tblPr
+ tbl_cell_mar = OxmlElement("w:tblCellMar")
+ for tag, val in (
+ ("top", top),
+ ("bottom", bottom),
+ ("left", left),
+ ("right", right),
+ ):
+ el = OxmlElement(f"w:{tag}")
+ el.set(qn("w:w"), str(int(val)))
+ el.set(qn("w:type"), "dxa")
+ tbl_cell_mar.append(el)
+ tbl_pr.append(tbl_cell_mar)
+
+ def _set_table_header_row_repeat(self, row):
+ tr_pr = row._tr.get_or_add_trPr()
+ tbl_header = OxmlElement("w:tblHeader")
+ tbl_header.set(qn("w:val"), "true")
+ tr_pr.append(tbl_header)
+
+ def add_list_to_doc(
+ self, doc: Document, items: List[Tuple[int, str]], list_type: str
+ ):
+ """Add list"""
+ for indent, text in items:
+ paragraph = doc.add_paragraph()
+
+ if list_type == "unordered":
+ # Unordered list with bullets
+ paragraph.style = "List Bullet"
+ else:
+ # Ordered list with numbers
+ paragraph.style = "List Number"
+
+ # Set indent
+ paragraph.paragraph_format.left_indent = Cm(0.5 * (indent + 1))
+
+ # Add formatted text
+ self.add_formatted_text(paragraph, text)
+
+ def add_horizontal_rule(self, doc: Document):
+ """Add horizontal rule"""
+ paragraph = doc.add_paragraph()
+ paragraph.paragraph_format.space_before = Pt(12)
+ paragraph.paragraph_format.space_after = Pt(12)
+
+ # Add bottom border as horizontal rule
+ pPr = paragraph._element.get_or_add_pPr()
+ pBdr = OxmlElement("w:pBdr")
+ bottom = OxmlElement("w:bottom")
+ bottom.set(qn("w:val"), "single")
+ bottom.set(qn("w:sz"), "6")
+ bottom.set(qn("w:space"), "1")
+ bottom.set(qn("w:color"), "auto")
+ pBdr.append(bottom)
+ pPr.append(pBdr)
+
+ def add_blockquote(self, doc: Document, text: str):
+ """Add blockquote with left border and gray background"""
+ for line in text.split("\n"):
+ paragraph = doc.add_paragraph()
+ paragraph.paragraph_format.left_indent = Cm(1.0)
+ paragraph.paragraph_format.space_before = Pt(3)
+ paragraph.paragraph_format.space_after = Pt(3)
+
+ # Add left border
+ pPr = paragraph._element.get_or_add_pPr()
+ pBdr = OxmlElement("w:pBdr")
+ left = OxmlElement("w:left")
+ left.set(qn("w:val"), "single")
+ left.set(qn("w:sz"), "24") # Border thickness
+ left.set(qn("w:space"), "4") # Space between border and text
+ left.set(qn("w:color"), "CCCCCC") # Gray border
+ pBdr.append(left)
+ pPr.append(pBdr)
+
+ # Add light gray background
+ shading = OxmlElement("w:shd")
+ shading.set(qn("w:fill"), "F9F9F9")
+ pPr.append(shading)
+
+ # Add formatted text
+ self.add_formatted_text(paragraph, line)
+
+ # Set font to italic gray
+ for run in paragraph.runs:
+ run.font.color.rgb = RGBColor(85, 85, 85) # Dark gray text
+ run.italic = True
+
+ def _sanitize_metadata(self, doc: Document, author: str = "", title: str = ""):
+ """Removes library fingerprints and sets professional defaults."""
+ p = doc.core_properties
+ p.author = author # Set your preferred author name
+ p.comments = "" # Clears any default library comments
+ p.title = title # Initialise as empty; logic fills this later
+ p.keywords = ""
+ p.subject = ""
+ p.last_modified_by = author
+
+ try:
+ from docx.opc.constants import CONTENT_TYPE as CT
+
+ # Setting these to an empty string or a custom value
+ # obscures the default 'python-docx' signature.
+ p.category = ""
+ p.content_status = ""
+ except Exception:
+ pass
diff --git a/integrations/openwebui-community-plugins/inline_visualizer.py b/integrations/openwebui-community-plugins/inline_visualizer.py
new file mode 100644
index 0000000..22304d5
--- /dev/null
+++ b/integrations/openwebui-community-plugins/inline_visualizer.py
@@ -0,0 +1,4171 @@
+"""
+title: Inline Visualizer
+author: Classic298
+author_url: https://github.com/Classic298
+funding_url: https://github.com/Classic298
+version: 2.2.3
+required_open_webui_version: 0.10.2
+description: Renders interactive HTML/SVG visualizations inline in chat. Requires "iframe Sandbox Allow Same Origin" to be enabled in Open WebUI Settings -> Interface. For design instructions, the model should call view_skill("visualize").
+"""
+
+import re
+import asyncio
+from typing import Literal
+
+# Build marker embedded into the rendered iframe so the running
+# version can be verified at runtime (search DevTools for
+# `data-iv-build` on ). Keep in sync with the frontmatter version.
+_IV_BUILD = "2.2.3"
+
+from fastapi.responses import HTMLResponse
+from pydantic import BaseModel, Field
+
+# ---------------------------------------------------------------------------
+# Injected CSS — Theme variables (light default, dark via data-theme)
+# ---------------------------------------------------------------------------
+
+THEME_CSS = """
+:root {
+ --color-text-primary: #1F2937;
+ --color-text-secondary: #6B7280;
+ --color-text-tertiary: #9CA3AF;
+ --color-text-info: #2563EB;
+ --color-text-success: #059669;
+ --color-text-warning: #D97706;
+ --color-text-danger: #DC2626;
+ --color-bg-primary: #FFFFFF;
+ --color-bg-secondary: #F9FAFB;
+ --color-bg-tertiary: #F3F4F6;
+ --color-border-tertiary: rgba(0,0,0,0.15);
+ --color-border-secondary: rgba(0,0,0,0.3);
+ --color-border-primary: rgba(0,0,0,0.4);
+ --font-sans: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
+ --font-mono: 'SF Mono', Menlo, Consolas, monospace;
+ --radius-md: 8px;
+ --radius-lg: 12px;
+ --radius-xl: 16px;
+ /* --- Color ramp variables (light) --- */
+ --ramp-purple-fill:#EEEDFE; --ramp-purple-stroke:#534AB7; --ramp-purple-th:#3C3489; --ramp-purple-ts:#534AB7;
+ --ramp-teal-fill:#E1F5EE; --ramp-teal-stroke:#0F6E56; --ramp-teal-th:#085041; --ramp-teal-ts:#0F6E56;
+ --ramp-coral-fill:#FAECE7; --ramp-coral-stroke:#993C1D; --ramp-coral-th:#712B13; --ramp-coral-ts:#993C1D;
+ --ramp-pink-fill:#FBEAF0; --ramp-pink-stroke:#993556; --ramp-pink-th:#72243E; --ramp-pink-ts:#993556;
+ --ramp-gray-fill:#F1EFE8; --ramp-gray-stroke:#5F5E5A; --ramp-gray-th:#444441; --ramp-gray-ts:#5F5E5A;
+ --ramp-blue-fill:#E6F1FB; --ramp-blue-stroke:#185FA5; --ramp-blue-th:#0C447C; --ramp-blue-ts:#185FA5;
+ --ramp-green-fill:#EAF3DE; --ramp-green-stroke:#3B6D11; --ramp-green-th:#27500A; --ramp-green-ts:#3B6D11;
+ --ramp-amber-fill:#FAEEDA; --ramp-amber-stroke:#854F0B; --ramp-amber-th:#633806; --ramp-amber-ts:#854F0B;
+ --ramp-red-fill:#FCEBEB; --ramp-red-stroke:#A32D2D; --ramp-red-th:#791F1F; --ramp-red-ts:#A32D2D;
+ /* --- Common aliases (catch hallucinated variable names) --- */
+ /* Text */
+ --fg: var(--color-text-primary);
+ --text: var(--color-text-primary);
+ --foreground: var(--color-text-primary);
+ --text-primary: var(--color-text-primary);
+ --text-color: var(--color-text-primary);
+ --color-text: var(--color-text-primary);
+ --color-foreground: var(--color-text-primary);
+ --body-color: var(--color-text-primary);
+ --muted: var(--color-text-secondary);
+ --muted-foreground: var(--color-text-secondary);
+ --text-muted: var(--color-text-secondary);
+ --text-secondary: var(--color-text-secondary);
+ --secondary: var(--color-text-secondary);
+ --subtle: var(--color-text-tertiary);
+ --text-tertiary: var(--color-text-tertiary);
+ /* Backgrounds */
+ --bg: var(--color-bg-primary);
+ --background: var(--color-bg-primary);
+ --bg-primary: var(--color-bg-primary);
+ --body-bg: var(--color-bg-primary);
+ --color-bg: var(--color-bg-primary);
+ --surface: var(--color-bg-secondary);
+ --surface-1: var(--color-bg-secondary);
+ --surface-2: var(--color-bg-tertiary);
+ --card: var(--color-bg-secondary);
+ --card-bg: var(--color-bg-secondary);
+ --card-foreground: var(--color-text-primary);
+ --card-background: var(--color-bg-secondary);
+ --popover: var(--color-bg-secondary);
+ --popover-foreground: var(--color-text-primary);
+ --hover: rgba(0,0,0,0.04);
+ /* Borders */
+ --border: var(--color-border-tertiary);
+ --border-color: var(--color-border-tertiary);
+ --divider: var(--color-border-tertiary);
+ --separator: var(--color-border-tertiary);
+ --input: var(--color-border-tertiary);
+ --ring: var(--color-border-secondary);
+ /* Accent / Primary (AI uses --accent as brand color, not surface) */
+ --primary: #6c2eb9;
+ --primary-foreground: #ffffff;
+ --accent: #6c2eb9;
+ --accent-foreground: #ffffff;
+ /* Themed select chevron (light) — used by the pre-styled */
+ --select-arrow: url("data:image/svg+xml;utf8, ");
+}
+:root[data-theme="dark"] {
+ --color-text-primary: #E5E7EB;
+ --color-text-secondary: #9CA3AF;
+ --color-text-tertiary: #6B7280;
+ --color-text-info: #60A5FA;
+ --color-text-success: #34D399;
+ --color-text-warning: #FBBF24;
+ --color-text-danger: #F87171;
+ --color-bg-primary: #1A1A1A;
+ --color-bg-secondary: #262626;
+ --color-bg-tertiary: #111111;
+ --color-border-tertiary: rgba(255,255,255,0.15);
+ --color-border-secondary: rgba(255,255,255,0.3);
+ --color-border-primary: rgba(255,255,255,0.4);
+ --ramp-purple-fill:#3C3489; --ramp-purple-stroke:#AFA9EC; --ramp-purple-th:#CECBF6; --ramp-purple-ts:#AFA9EC;
+ --ramp-teal-fill:#085041; --ramp-teal-stroke:#5DCAA5; --ramp-teal-th:#9FE1CB; --ramp-teal-ts:#5DCAA5;
+ --ramp-coral-fill:#712B13; --ramp-coral-stroke:#F0997B; --ramp-coral-th:#F5C4B3; --ramp-coral-ts:#F0997B;
+ --ramp-pink-fill:#72243E; --ramp-pink-stroke:#ED93B1; --ramp-pink-th:#F4C0D1; --ramp-pink-ts:#ED93B1;
+ --ramp-gray-fill:#444441; --ramp-gray-stroke:#B4B2A9; --ramp-gray-th:#D3D1C7; --ramp-gray-ts:#B4B2A9;
+ --ramp-blue-fill:#0C447C; --ramp-blue-stroke:#85B7EB; --ramp-blue-th:#B5D4F4; --ramp-blue-ts:#85B7EB;
+ --ramp-green-fill:#27500A; --ramp-green-stroke:#97C459; --ramp-green-th:#C0DD97; --ramp-green-ts:#97C459;
+ --ramp-amber-fill:#633806; --ramp-amber-stroke:#EF9F27; --ramp-amber-th:#FAC775; --ramp-amber-ts:#EF9F27;
+ --ramp-red-fill:#791F1F; --ramp-red-stroke:#F09595; --ramp-red-th:#F7C1C1; --ramp-red-ts:#F09595;
+ /* --- Common aliases (dark overrides) --- */
+ --text: var(--color-text-primary);
+ --foreground: var(--color-text-primary);
+ --text-primary: var(--color-text-primary);
+ --text-color: var(--color-text-primary);
+ --color-text: var(--color-text-primary);
+ --body-color: var(--color-text-primary);
+ --muted: var(--color-text-secondary);
+ --muted-foreground: var(--color-text-secondary);
+ --text-muted: var(--color-text-secondary);
+ --text-secondary: var(--color-text-secondary);
+ --secondary: var(--color-text-secondary);
+ --subtle: var(--color-text-tertiary);
+ --text-tertiary: var(--color-text-tertiary);
+ --bg: var(--color-bg-primary);
+ --background: var(--color-bg-primary);
+ --bg-primary: var(--color-bg-primary);
+ --body-bg: var(--color-bg-primary);
+ --color-bg: var(--color-bg-primary);
+ --surface: var(--color-bg-secondary);
+ --surface-1: var(--color-bg-secondary);
+ --surface-2: var(--color-bg-tertiary);
+ --card: var(--color-bg-secondary);
+ --card-bg: var(--color-bg-secondary);
+ --card-foreground: var(--color-text-primary);
+ --card-background: var(--color-bg-secondary);
+ --popover: var(--color-bg-secondary);
+ --popover-foreground: var(--color-text-primary);
+ --hover: rgba(255,255,255,0.06);
+ --border: var(--color-border-tertiary);
+ --border-color: var(--color-border-tertiary);
+ --divider: var(--color-border-tertiary);
+ --separator: var(--color-border-tertiary);
+ --input: var(--color-border-tertiary);
+ --ring: var(--color-border-secondary);
+ --primary: #a78bfa;
+ --primary-foreground: #1A1A1A;
+ --accent: #a78bfa;
+ --accent-foreground: #ffffff;
+ --select-arrow: url("data:image/svg+xml;utf8, ");
+}
+
+/* --- Named accent palette ---
+ * Apply data-accent="" on for global, on any element
+ * for local override. The variants reuse the existing color-ramp
+ * stroke colors so charts and forms share visual vocabulary
+ * (teal here = teal in a chart). Each variant works in both
+ * light and dark themes — --accent picks up the ramp's per-theme
+ * stroke automatically; --accent-foreground flips dark in dark
+ * mode so text stays legible on pastel accents.
+ */
+[data-accent="purple"] { --accent: var(--ramp-purple-stroke); --accent-foreground: #ffffff; }
+[data-accent="teal"] { --accent: var(--ramp-teal-stroke); --accent-foreground: #ffffff; }
+[data-accent="coral"] { --accent: var(--ramp-coral-stroke); --accent-foreground: #ffffff; }
+[data-accent="pink"] { --accent: var(--ramp-pink-stroke); --accent-foreground: #ffffff; }
+[data-accent="gray"] { --accent: var(--ramp-gray-stroke); --accent-foreground: #ffffff; }
+[data-accent="blue"] { --accent: var(--ramp-blue-stroke); --accent-foreground: #ffffff; }
+[data-accent="green"] { --accent: var(--ramp-green-stroke); --accent-foreground: #ffffff; }
+[data-accent="amber"] { --accent: var(--ramp-amber-stroke); --accent-foreground: #ffffff; }
+[data-accent="red"] { --accent: var(--ramp-red-stroke); --accent-foreground: #ffffff; }
+
+[data-theme="dark"] [data-accent],
+[data-theme="dark"][data-accent] {
+ --accent-foreground: #1A1A1A;
+}
+"""
+
+# ---------------------------------------------------------------------------
+# Injected CSS — SVG utility classes + color ramp selectors
+# ---------------------------------------------------------------------------
+
+SVG_CLASSES = """
+/* --- Text --- */
+.t { font: 400 14px/1.4 var(--font-sans); fill: var(--color-text-primary); }
+.ts { font: 400 12px/1.4 var(--font-sans); fill: var(--color-text-secondary); }
+.th { font: 500 14px/1.4 var(--font-sans); fill: var(--color-text-primary); }
+
+/* --- Shapes --- */
+.box { fill: var(--color-bg-secondary); stroke: var(--color-border-tertiary); stroke-width: 0.5; }
+.node { cursor: pointer; }
+.node:hover { opacity: 0.85; }
+.arr { stroke: var(--color-border-secondary); stroke-width: 1.5; fill: none; }
+.leader { stroke: var(--color-text-tertiary); stroke-width: 0.5; stroke-dasharray: 3 2; fill: none; }
+
+/* --- Color ramp selectors (fill/stroke adapt via CSS vars) --- */
+/* color: on the group resolves currentColor marks to the series color.
+ path/polygon get the saturated stroke stop (pale fill stops sit behind
+ label text and are indistinguishable side by side in a pie); classed
+ or explicitly-filled marks keep their own styling. */
+.c-purple>rect,.c-purple>circle,.c-purple>ellipse{fill:var(--ramp-purple-fill);stroke:var(--ramp-purple-stroke);stroke-width:.5}
+g.c-purple{color:var(--ramp-purple-stroke)} .c-purple>path:not([class]):not([fill]),.c-purple>polygon:not([class]):not([fill]){fill:var(--ramp-purple-stroke)}
+.c-purple>.th{fill:var(--ramp-purple-th)!important} .c-purple>.ts{fill:var(--ramp-purple-ts)!important}
+.c-teal>rect,.c-teal>circle,.c-teal>ellipse{fill:var(--ramp-teal-fill);stroke:var(--ramp-teal-stroke);stroke-width:.5}
+g.c-teal{color:var(--ramp-teal-stroke)} .c-teal>path:not([class]):not([fill]),.c-teal>polygon:not([class]):not([fill]){fill:var(--ramp-teal-stroke)}
+.c-teal>.th{fill:var(--ramp-teal-th)!important} .c-teal>.ts{fill:var(--ramp-teal-ts)!important}
+.c-coral>rect,.c-coral>circle,.c-coral>ellipse{fill:var(--ramp-coral-fill);stroke:var(--ramp-coral-stroke);stroke-width:.5}
+g.c-coral{color:var(--ramp-coral-stroke)} .c-coral>path:not([class]):not([fill]),.c-coral>polygon:not([class]):not([fill]){fill:var(--ramp-coral-stroke)}
+.c-coral>.th{fill:var(--ramp-coral-th)!important} .c-coral>.ts{fill:var(--ramp-coral-ts)!important}
+.c-pink>rect,.c-pink>circle,.c-pink>ellipse{fill:var(--ramp-pink-fill);stroke:var(--ramp-pink-stroke);stroke-width:.5}
+g.c-pink{color:var(--ramp-pink-stroke)} .c-pink>path:not([class]):not([fill]),.c-pink>polygon:not([class]):not([fill]){fill:var(--ramp-pink-stroke)}
+.c-pink>.th{fill:var(--ramp-pink-th)!important} .c-pink>.ts{fill:var(--ramp-pink-ts)!important}
+.c-gray>rect,.c-gray>circle,.c-gray>ellipse{fill:var(--ramp-gray-fill);stroke:var(--ramp-gray-stroke);stroke-width:.5}
+g.c-gray{color:var(--ramp-gray-stroke)} .c-gray>path:not([class]):not([fill]),.c-gray>polygon:not([class]):not([fill]){fill:var(--ramp-gray-stroke)}
+.c-gray>.th{fill:var(--ramp-gray-th)!important} .c-gray>.ts{fill:var(--ramp-gray-ts)!important}
+.c-blue>rect,.c-blue>circle,.c-blue>ellipse{fill:var(--ramp-blue-fill);stroke:var(--ramp-blue-stroke);stroke-width:.5}
+g.c-blue{color:var(--ramp-blue-stroke)} .c-blue>path:not([class]):not([fill]),.c-blue>polygon:not([class]):not([fill]){fill:var(--ramp-blue-stroke)}
+.c-blue>.th{fill:var(--ramp-blue-th)!important} .c-blue>.ts{fill:var(--ramp-blue-ts)!important}
+.c-green>rect,.c-green>circle,.c-green>ellipse{fill:var(--ramp-green-fill);stroke:var(--ramp-green-stroke);stroke-width:.5}
+g.c-green{color:var(--ramp-green-stroke)} .c-green>path:not([class]):not([fill]),.c-green>polygon:not([class]):not([fill]){fill:var(--ramp-green-stroke)}
+.c-green>.th{fill:var(--ramp-green-th)!important} .c-green>.ts{fill:var(--ramp-green-ts)!important}
+.c-amber>rect,.c-amber>circle,.c-amber>ellipse{fill:var(--ramp-amber-fill);stroke:var(--ramp-amber-stroke);stroke-width:.5}
+g.c-amber{color:var(--ramp-amber-stroke)} .c-amber>path:not([class]):not([fill]),.c-amber>polygon:not([class]):not([fill]){fill:var(--ramp-amber-stroke)}
+.c-amber>.th{fill:var(--ramp-amber-th)!important} .c-amber>.ts{fill:var(--ramp-amber-ts)!important}
+.c-red>rect,.c-red>circle,.c-red>ellipse{fill:var(--ramp-red-fill);stroke:var(--ramp-red-stroke);stroke-width:.5}
+g.c-red{color:var(--ramp-red-stroke)} .c-red>path:not([class]):not([fill]),.c-red>polygon:not([class]):not([fill]){fill:var(--ramp-red-stroke)}
+.c-red>.th{fill:var(--ramp-red-th)!important} .c-red>.ts{fill:var(--ramp-red-ts)!important}
+"""
+
+# ---------------------------------------------------------------------------
+# Injected CSS — Base resets & interactive element styles
+# ---------------------------------------------------------------------------
+
+BASE_STYLES = """
+* { box-sizing: border-box; margin: 0; font-family: var(--font-sans); }
+html, body { overflow: hidden; }
+body { background: transparent; color: var(--color-text-primary); line-height: 1.5; padding: 8px; }
+svg { overflow: visible; }
+svg text { fill: var(--color-text-primary); }
+h1 { font-size: 22px; font-weight: 500; color: var(--color-text-primary); margin-bottom: 12px; }
+h2 { font-size: 18px; font-weight: 500; color: var(--color-text-primary); margin-bottom: 8px; }
+h3 { font-size: 16px; font-weight: 500; color: var(--color-text-primary); margin-bottom: 6px; }
+p { font-size: 14px; color: var(--color-text-secondary); margin-bottom: 8px; }
+/* --- Pre-styled form elements ---
+ * Each rule is gated with :not([class]):not([style]) so the model
+ * opts in by emitting bare HTML. Adding either attribute is treated
+ * as opting out — the default suppresses and the model styles from
+ * scratch. Keeps token cost low for vanilla cases without locking
+ * the design space.
+ */
+button:not([class]):not([style]) {
+ background: transparent; border: 0.5px solid var(--color-border-secondary);
+ border-radius: var(--radius-md); padding: 6px 14px; font-size: 13px;
+ color: var(--color-text-primary); cursor: pointer; font-family: var(--font-sans);
+}
+button:not([class]):not([style]):hover { background: var(--color-bg-secondary); }
+
+input[type="text"]:not([class]):not([style]),
+input[type="number"]:not([class]):not([style]),
+input[type="email"]:not([class]):not([style]),
+input[type="search"]:not([class]):not([style]),
+input[type="password"]:not([class]):not([style]),
+input[type="tel"]:not([class]):not([style]),
+input[type="url"]:not([class]):not([style]),
+input[type="date"]:not([class]):not([style]),
+input[type="time"]:not([class]):not([style]),
+input[type="datetime-local"]:not([class]):not([style]) {
+ background: var(--color-bg-primary);
+ border: 0.5px solid var(--color-border-tertiary);
+ border-radius: var(--radius-md); padding: 6px 10px; font-size: 13px;
+ color: var(--color-text-primary); font-family: var(--font-sans);
+ outline: none; transition: border-color 0.15s ease;
+}
+input[type="text"]:not([class]):not([style]):focus,
+input[type="number"]:not([class]):not([style]):focus,
+input[type="email"]:not([class]):not([style]):focus,
+input[type="search"]:not([class]):not([style]):focus,
+input[type="password"]:not([class]):not([style]):focus,
+input[type="tel"]:not([class]):not([style]):focus,
+input[type="url"]:not([class]):not([style]):focus,
+input[type="date"]:not([class]):not([style]):focus,
+input[type="time"]:not([class]):not([style]):focus,
+input[type="datetime-local"]:not([class]):not([style]):focus {
+ border-color: var(--color-border-primary);
+}
+
+/* Drop the type=number spinner — clashes with the field's borders. */
+input[type="number"]:not([class]):not([style]) {
+ -moz-appearance: textfield; appearance: textfield;
+}
+input[type="number"]:not([class]):not([style])::-webkit-outer-spin-button,
+input[type="number"]:not([class]):not([style])::-webkit-inner-spin-button {
+ -webkit-appearance: none; margin: 0;
+}
+
+textarea:not([class]) {
+ background: var(--color-bg-primary);
+ border: 0.5px solid var(--color-border-tertiary);
+ border-radius: var(--radius-md); padding: 8px 10px; font-size: 13px;
+ color: var(--color-text-primary); font-family: var(--font-sans);
+ outline: none; resize: vertical; min-height: 60px;
+ transition: border-color 0.15s ease;
+}
+textarea:not([class]):focus { border-color: var(--color-border-primary); }
+
+/* accent-color always applies, regardless of class/style — it's a
+ * tint property the model is highly unlikely to set themselves, and
+ * letting it ride keeps palette switches consistent even when the
+ * model adds inline width/max-width styling to the slider. */
+input[type="range"], input[type="checkbox"], input[type="radio"] {
+ accent-color: var(--accent);
+}
+input[type="range"]:not([class]):not([style]) { width: 100%; }
+
+input[type="checkbox"]:not([class]):not([style]),
+input[type="radio"]:not([class]):not([style]) {
+ /* accent-color comes from the always-on rule above. */
+ cursor: pointer;
+}
+
+select:not([class]):not([style]) {
+ appearance: none; -webkit-appearance: none; -moz-appearance: none;
+ background-color: var(--color-bg-secondary);
+ background-image: var(--select-arrow);
+ background-repeat: no-repeat;
+ background-position: right 10px center;
+ border: 0.5px solid var(--color-border-tertiary);
+ border-radius: var(--radius-md); padding: 6px 28px 6px 10px;
+ font-size: 13px; color: var(--color-text-primary); font-family: var(--font-sans);
+ outline: none; cursor: pointer;
+}
+select:not([class]):not([style]):focus { border-color: var(--color-border-primary); }
+
+label:not([class]):not([style]) {
+ font-size: 13px; color: var(--color-text-primary); cursor: pointer;
+}
+fieldset:not([class]):not([style]) {
+ border: 0.5px solid var(--color-border-tertiary);
+ border-radius: var(--radius-md); padding: 12px;
+}
+legend:not([class]):not([style]) {
+ font-size: 12px; color: var(--color-text-secondary); padding: 0 6px;
+}
+
+/* Validation error border — standard a11y attribute, no class needed. */
+input[aria-invalid="true"]:not([class]):not([style]),
+textarea[aria-invalid="true"]:not([class]),
+select[aria-invalid="true"]:not([class]):not([style]) {
+ border-color: var(--color-text-danger);
+}
+
+/* Keyboard-only focus rings (accent outline). Mouse focus stays subtle. */
+button:not([class]):not([style]):focus-visible,
+input:not([class]):not([style]):focus-visible,
+textarea:not([class]):focus-visible,
+select:not([class]):not([style]):focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 1px;
+}
+
+code {
+ font-family: var(--font-mono); font-size: 13px; background: var(--color-bg-tertiary);
+ padding: 2px 6px; border-radius: 4px;
+}
+
+/* — keyboard-key pill (cmd/ctrl/k style). */
+kbd:not([class]):not([style]) {
+ font-family: var(--font-mono); font-size: 12px;
+ background: var(--color-bg-secondary);
+ border: 0.5px solid var(--color-border-tertiary);
+ border-radius: 4px; padding: 1px 6px;
+ color: var(--color-text-primary);
+}
+
+/* — flat divider matching the rest of the borders. */
+hr:not([class]):not([style]) {
+ border: none;
+ border-top: 0.5px solid var(--color-border-tertiary);
+ margin: 1.5rem 0;
+}
+
+/* / — themed disclosure with a bigger chevron.
+ * Container is an invisible rounded "wrapper" — the visible card-
+ * shape is the summary header itself. This way if a model adds its
+ * own summary background/border, the result is still single-card,
+ * not nested. Chevron is sized to be clearly visible. */
+details:not([class]):not([style]) {
+ margin: 12px 0;
+ border: 0.5px solid var(--color-border-tertiary);
+ border-radius: var(--radius-md);
+ overflow: hidden;
+}
+details:not([class]):not([style]) > summary {
+ cursor: pointer; list-style: none; user-select: none;
+ font-weight: 500; color: var(--color-text-primary);
+ background: var(--color-bg-secondary);
+ padding: 10px 14px 10px 34px;
+ position: relative;
+ transition: background-color 0.15s ease;
+}
+details:not([class]):not([style]) > summary:hover {
+ background: var(--color-bg-tertiary);
+}
+details:not([class]):not([style]) > summary::-webkit-details-marker { display: none; }
+details:not([class]):not([style]) > summary::marker { content: ''; }
+details:not([class]):not([style]) > summary::before {
+ content: '\\25B8'; /* ▸ */
+ position: absolute; left: 12px; top: 50%;
+ transform: translateY(-50%);
+ transition: transform 0.15s ease;
+ color: var(--color-text-secondary);
+ font-size: 18px;
+ line-height: 1;
+}
+details[open]:not([class]):not([style]) > summary::before {
+ transform: translateY(-50%) rotate(90deg);
+}
+details[open]:not([class]):not([style]) > summary {
+ border-bottom: 0.5px solid var(--color-border-tertiary);
+}
+/* Margin (not padding) so children with their own bg inset properly. */
+details:not([class]):not([style]) > *:not(summary) {
+ margin: 12px 14px;
+}
+
+blockquote:not([class]):not([style]) {
+ border-left: 4px solid var(--accent);
+ background: var(--color-bg-secondary);
+ padding: 12px 18px;
+ margin: 16px 0;
+ color: var(--color-text-secondary);
+ border-radius: var(--radius-md);
+}
+blockquote:not([class]):not([style]) > :last-child { margin-bottom: 0; }
+blockquote:not([class]):not([style]) > :first-child { margin-top: 0; }
+
+/* — flat data table, theme-matched borders, header pill,
+ * row hover, last-row borderless, no zebra (kept calm). For numeric
+ * columns, add align="right" or class="num" to / . */
+table:not([class]):not([style]) {
+ width: 100%;
+ border-collapse: collapse;
+ margin: 12px 0;
+ font-size: 13px;
+ color: var(--color-text-primary);
+ font-family: var(--font-sans);
+}
+table:not([class]):not([style]) caption {
+ text-align: left;
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--color-text-secondary);
+ padding: 0 0 8px;
+ caption-side: top;
+}
+table:not([class]):not([style]) th {
+ text-align: left;
+ padding: 8px 12px;
+ /* Reset all sides so a model's `border:` shorthand can't leak through. */
+ border: none;
+ border-bottom: 0.5px solid var(--color-border-secondary);
+ font-weight: 500;
+ font-size: 11px;
+ color: var(--color-text-secondary);
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ background: var(--color-bg-secondary);
+ white-space: nowrap;
+}
+table:not([class]):not([style]) td {
+ padding: 10px 12px;
+ border: none;
+ border-bottom: 0.5px solid var(--color-border-tertiary);
+ vertical-align: top;
+}
+table:not([class]):not([style]) tr:last-child > td {
+ border-bottom: none;
+}
+table:not([class]):not([style]) tbody tr {
+ transition: background-color 0.1s ease;
+}
+table:not([class]):not([style]) tbody tr:hover {
+ background: var(--color-bg-secondary);
+}
+/* Numeric columns: opt-in via align="right" or class="num" on cells. */
+table:not([class]):not([style]) td[align="right"],
+table:not([class]):not([style]) th[align="right"],
+table:not([class]):not([style]) td.num,
+table:not([class]):not([style]) th.num {
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+}
+
+mark:not([class]):not([style]) {
+ background: var(--ramp-amber-fill);
+ color: var(--ramp-amber-th);
+ padding: 0 4px;
+ border-radius: 3px;
+}
+
+/* three modes — default stacked, data-layout="grid", data-layout="inline".
+ * data-layout is the explicit opt-in, so [data-layout] rules skip the class/style gate. */
+dl:not([class]):not([style]) { margin: 12px 0; }
+dl:not([class]):not([style]) > dt {
+ font-weight: 500;
+ color: var(--color-text-primary);
+ font-size: 14px;
+ margin-top: 12px;
+}
+dl:not([class]):not([style]) > dt:first-child { margin-top: 0; }
+dl:not([class]):not([style]) > dd {
+ margin: 4px 0 0;
+ font-size: 13px;
+ color: var(--color-text-secondary);
+}
+
+/* `display: contents` on the optional wrapping div + dual selectors below
+ * tolerates both flat … and
… markup. */
+dl[data-layout="grid"] {
+ display: grid;
+ grid-template-columns: max-content 1fr;
+ gap: 8px 16px;
+ align-items: baseline;
+ padding: 12px 16px;
+ border: 0.5px solid var(--color-border-tertiary);
+ border-radius: var(--radius-md);
+ background: var(--color-bg-secondary);
+ margin: 12px 0;
+}
+dl[data-layout="grid"] > div { display: contents; }
+dl[data-layout="grid"] > dt,
+dl[data-layout="grid"] > div > dt {
+ font-weight: 400;
+ color: var(--color-text-secondary);
+ font-size: 13px;
+ margin: 0;
+}
+dl[data-layout="grid"] > dd,
+dl[data-layout="grid"] > div > dd {
+ margin: 0;
+ text-align: right;
+ color: var(--color-text-primary);
+ font-weight: 500;
+ font-size: 13px;
+}
+
+/* data-layout="inline" — pill row. Each / pair wrapped in .
+ * Same opt-in-via-attribute logic as grid above — no :not() gate. */
+dl[data-layout="inline"] {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin: 12px 0;
+}
+dl[data-layout="inline"] > div {
+ display: inline-flex;
+ align-items: baseline;
+ gap: 4px;
+ padding: 4px 10px;
+ border: 0.5px solid var(--color-border-tertiary);
+ border-radius: 999px;
+ font-size: 12px;
+ background: var(--color-bg-secondary);
+}
+dl[data-layout="inline"] > div > dt {
+ margin: 0;
+ font-weight: 400;
+ color: var(--color-text-secondary);
+ font-size: 12px;
+}
+dl[data-layout="inline"] > div > dt::after {
+ content: ":";
+ margin-right: 2px;
+}
+dl[data-layout="inline"] > div > dd {
+ margin: 0;
+ font-weight: 500;
+ color: var(--color-text-primary);
+ font-size: 12px;
+}
+
+#iv-dl-wrap{position:fixed;top:4px;right:4px;z-index:9999}
+#iv-dl-btn{width:26px;height:26px;padding:0;display:flex;align-items:center;justify-content:center;
+ opacity:0.3;border-color:var(--color-border-tertiary);background:var(--color-bg-primary)}
+#iv-dl-btn:hover{opacity:0.9;background:var(--color-bg-secondary)}
+#iv-dl-btn svg{width:14px;height:14px;stroke:var(--color-text-secondary);fill:none;
+ stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}
+/* --- Print ---
+ * overflow:hidden on html/body clips content in print (needed on screen
+ * for iframe sizing). Chart.js canvas scaling is handled by JS beforeprint
+ * handler in BODY_SCRIPTS — it directly mutates inline styles that CSS
+ * cannot reliably override in Chrome's print engine.
+ */
+@media print {
+ @page { margin: 12mm; }
+ html, body { overflow: visible !important; height: auto !important;
+ background: #fff !important; }
+ body { padding: 4px !important; }
+ #iv-dl-wrap { display: none !important; }
+ * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
+}
+"""
+
+# ---------------------------------------------------------------------------
+# Injected JavaScript — theme detection (head), height reporting & bridges (body)
+# ---------------------------------------------------------------------------
+# Theme script runs in before user content so CSS vars are resolved
+# when model scripts read them at parse time.
+#
+# !! SRCDOC SAFETY !! Do NOT write the literal tokens ,
+# , ANYWHERE in this body —
+# not even inside JS comments. The iframe srcdoc's HTML5 tokenizer
+# treats them as parser state changes regardless of JS context, and
+# silently breaks the IIFE (see _assert_srcdoc_safe near the bottom
+# of this file for the runtime guard).
+THEME_DETECTION_SCRIPT = """
+
+"""
+
+# !! SRCDOC SAFETY !! Do NOT write the literal tokens ,
+# , ANYWHERE in this body —
+# not even inside JS comments. See THEME_DETECTION_SCRIPT for full rationale.
+BODY_SCRIPTS = """
+
+"""
+
+
+# ---------------------------------------------------------------------------
+# Happy chime on live-stream completion
+# ---------------------------------------------------------------------------
+# Injected into BODY_SCRIPTS via a /*__CHIME_BLOCK__*/ placeholder so the
+# ``chime`` valve can strip it out entirely when disabled — no bytes
+# shipped, not just a silent no-op. finalize() calls playDoneSound() inside
+# a ``typeof playDoneSound === 'function'`` guard, so omission is safe.
+# ---------------------------------------------------------------------------
+
+# !! SRCDOC SAFETY !! Do NOT write the literal tokens ,
+# , ANYWHERE in this body —
+# not even inside JS comments. See THEME_DETECTION_SCRIPT for full rationale.
+CHIME_SCRIPT = """
+// --- Happy chime ---
+// C-major arpeggio (C5 → E5 → G5) on sine oscillators with exponential
+// decay. ~300 ms, gentle volume. Silent no-op if AudioContext is still
+// suspended (no prior user gesture).
+var _ivAudioCtx = null;
+function playDoneSound() {
+ try {
+ var AudioCtx = window.AudioContext || window.webkitAudioContext;
+ if (!AudioCtx) return;
+ if (!_ivAudioCtx) _ivAudioCtx = new AudioCtx();
+ var ctx = _ivAudioCtx;
+ if (ctx.state === 'suspended') { try { ctx.resume(); } catch(e) {} }
+ var now = ctx.currentTime;
+ var notes = [523.25, 659.25, 783.99]; // C5, E5, G5
+ notes.forEach(function(freq, i) {
+ var osc = ctx.createOscillator();
+ var gain = ctx.createGain();
+ osc.type = 'sine';
+ osc.frequency.value = freq;
+ var start = now + i * 0.09;
+ var duration = 0.35;
+ gain.gain.setValueAtTime(0.0001, start);
+ gain.gain.exponentialRampToValueAtTime(0.16, start + 0.015);
+ gain.gain.exponentialRampToValueAtTime(0.0001, start + duration);
+ osc.connect(gain).connect(ctx.destination);
+ osc.start(start);
+ osc.stop(start + duration + 0.02);
+ });
+ } catch(e) {}
+}
+"""
+
+# ---------------------------------------------------------------------------
+# STRICT-mode script — strip query params from openLink / window.open /
+#
. Supplementary hygiene only; the real exfil blocker is the
+# CSP connect-src directive. Paths, fragments, and location.assign are
+# not intercepted.
+# ---------------------------------------------------------------------------
+
+# !! SRCDOC SAFETY !! Do NOT write the literal tokens ,
+# , ANYWHERE in this body —
+# not even inside JS comments. See THEME_DETECTION_SCRIPT for full rationale.
+STRICT_SECURITY_SCRIPT = """
+
+"""
+
+# ---------------------------------------------------------------------------
+# STREAMING mode — text-marker observer (CodeBlock-free)
+# ---------------------------------------------------------------------------
+# Model emits plain-text @@@VIZ-START … @@@VIZ-END markers (NOT a code
+# fence — that path routed through CodeMirror's virtualizer and lost
+# content on scroll / refresh). Markdown renders them as ordinary
+# paragraph/html tokens, so nothing we scan goes through CodeBlock.
+#
+# Observer loop:
+# 1. Find enclosing message via frame.closest('[id^="message-"]').
+# 2. Read msg.textContent (skipping etc).
+# 3. Regex-extract the idx-th @@@VIZ-START … @@@VIZ-END block.
+# 4. Safe-cut partial HTML, reconcile into #iv-render.
+# 5. Walk the message DOM to hide the raw markers + between-marker
+# content inline (display:none !important).
+#
+# idx comes from the embed container id "{messageId}-embeds-{N}", so
+# multiple visualizations in the same message claim in order.
+#
+# Requires iframe Sandbox Allow Same Origin.
+# ---------------------------------------------------------------------------
+
+# !! SRCDOC SAFETY !! Do NOT write the literal tokens ,
+# , ANYWHERE in this body —
+# not even inside JS comments. See THEME_DETECTION_SCRIPT for full rationale.
+# This is the script that broke in 2.1.0–2.1.2 when a comment cleanup
+# accidentally introduced literal exits "script data escaped"
+# same
+# ` tag stops terminating the
+# script. The IIFE then either never executes or executes incompletely,
+# producing the silent failure mode we hit in 2.1.0–2.1.2 (every
+# debugging path looks normal in isolation, but tick never runs).
+#
+# Always build these tokens via string concatenation in JS — never
+# write them as literals, not even inside comments. The guard below
+# raises at module load time so the plugin refuses to import if anyone
+# ever reintroduces one.
+_FORBIDDEN_SRCDOC_LITERALS = (
+ "",
+ "",
+ "` — the wrapping tags themselves. Anything beyond
+ that count is a reintroduction of the bug fixed in 2.1.3.
+ """
+ open_count = body.count(" literal (open={open_count}, close={close_count}). "
+ "These break HTML5 srcdoc parsing — build them via string "
+ "concatenation in JS instead."
+ )
+ for tok in ("", ""):
+ if tok in body:
+ raise RuntimeError(
+ f"Inline Visualizer: {name} contains a literal {tok!r}. "
+ "This puts the iframe srcdoc parser into script-data-escape "
+ "mode and silently breaks the IIFE. Concatenate it in JS "
+ "instead, even inside comments."
+ )
+
+
+_IFRAME_EMBEDDED_SCRIPTS = {
+ "THEME_DETECTION_SCRIPT": THEME_DETECTION_SCRIPT,
+ "BODY_SCRIPTS": BODY_SCRIPTS,
+ "CHIME_SCRIPT": CHIME_SCRIPT,
+ "STRICT_SECURITY_SCRIPT": STRICT_SECURITY_SCRIPT,
+ "STREAMING_OBSERVER_SCRIPT": STREAMING_OBSERVER_SCRIPT,
+}
+for _name, _body in _IFRAME_EMBEDDED_SCRIPTS.items():
+ _assert_srcdoc_safe(_name, _body)
+
+
+DOWNLOAD_BUTTON = (
+ '"
+)
+
+
+# ---------------------------------------------------------------------------
+# CSP generation per security level
+# ---------------------------------------------------------------------------
+
+_KNOWN_CDNS = (
+ "https://cdnjs.cloudflare.com" " https://cdn.jsdelivr.net" " https://unpkg.com"
+)
+
+# The strict and balanced tags interpolate the (constant) CDN allowlist, so
+# assemble them once at import instead of rebuilding the string on every render.
+_CSP_STRICT = (
+ ' '
+)
+_CSP_BALANCED = (
+ ' '
+)
+
+
+def _build_csp_tag(level: str) -> str:
+ """Return a CSP tag for the given security level, or empty string.
+
+ 'unsafe-eval' is included because runtime expression compilers like
+ Vega / Vega-Lite use new Function() internally and fail under
+ strict CSP. 'unsafe-inline' is already present (inline scripts can
+ execute arbitrary code), so adding 'unsafe-eval' does not
+ meaningfully widen the attack surface — the real exfil blockers
+ (connect-src, form-action, img-src, object-src) remain intact.
+ """
+ if level == "none":
+ return ""
+
+ if level == "offline":
+ # STRICT minus the public CDN allowlist: nothing loads from
+ # outside the Open WebUI origin. 'self' replaces the CDN hosts
+ # so admins can serve pinned libraries from the instance's own
+ # /static directory (srcdoc iframes inherit the parent page's
+ # origin and base URL, so 'self' == the Open WebUI host and
+ # paths like /static/iv-libs/chart.umd.min.js resolve locally).
+ return (
+ ' '
+ )
+
+ if level == "strict":
+ return _CSP_STRICT
+
+ # balanced: block outbound connections & forms, allow external images
+ return _CSP_BALANCED
+
+
+def _build_html(
+ security_level: str = "strict",
+ title: str = "Visualization",
+ lang: str = "en",
+ chime: bool = True,
+) -> str:
+ """Wrap the streaming visualization shell: empty render area + observer.
+
+ The observer tails the parent chat DOM for an ``@@@VIZ-START`` …
+ ``@@@VIZ-END`` plain-text block in the assistant message and renders
+ its contents live into #iv-render.
+ """
+ csp_tag = _build_csp_tag(security_level)
+ strict_script = (
+ STRICT_SECURITY_SCRIPT if security_level in ("strict", "offline") else ""
+ )
+ safe_title = (
+ title.replace("&", "&")
+ .replace("<", "<")
+ .replace(">", ">")
+ .replace('"', """)
+ )
+ # Sanitize lang to a simple lowercase BCP-47 primary subtag.
+ # Split on '-' first so "zh-CN" → "zh", not "zhcn".
+ safe_lang = re.sub(r"[^a-z]", "", lang.split("-")[0].lower()[:5]) or "en"
+
+ # Strip the chime script entirely when the valve is off — no bytes
+ # shipped, no defined playDoneSound in the iframe. finalize()'s
+ # typeof-function guard turns the missing definition into a no-op.
+ body_scripts = BODY_SCRIPTS.replace(
+ "/*__CHIME_BLOCK__*/", CHIME_SCRIPT if chime else ""
+ )
+
+ # Loader sits *below* the render area so content appears to flow
+ # downward toward the pulsing dots — like a cursor following a pen.
+ # The observer removes #iv-loader entirely on finalize().
+ body_inner = (
+ '
\n'
+ ''
+ '
'
+ '
Rendering visualization\u2026
'
+ "
\n"
+ f"{DOWNLOAD_BUTTON}\n"
+ f"{body_scripts}"
+ f"{STREAMING_OBSERVER_SCRIPT}"
+ f"{strict_script}"
+ )
+
+ return (
+ f''
+ f"{safe_title} "
+ f"{csp_tag}"
+ f""
+ f''
+ f"{THEME_DETECTION_SCRIPT}"
+ f"\n{body_inner}\n"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Valves (user-configurable settings)
+# ---------------------------------------------------------------------------
+
+# Developer reference for security levels:
+#
+# STRICT — Containment-oriented default. Blocks outbound fetch/XHR
+# (connect-src 'none'), form submissions, external images,
+# embedded objects, and base-URI hijacking. Injects a script
+# that strips URL query parameters from link navigation as
+# additional hygiene (query-only; does not cover path or
+# fragment, and does not intercept location.assign/replace).
+# Script execution within the visualization is intentionally
+# allowed ('unsafe-inline' + CDN allowlist) — this is
+# required for Chart.js, D3, and interactive visualizations.
+#
+# BALANCED — Same as STRICT but allows external image loading (img-src *).
+# No URL parameter stripping. Note: img-src * permits
+# tracking pixels — this is an accepted privacy tradeoff
+# for visualizations that need external images.
+#
+# NONE — No CSP applied. Visualization can make arbitrary network
+# requests. Use only for visualizations that fetch live API
+# data (CORS restrictions still apply).
+#
+# OFFLINE — Nothing leaves the Open WebUI host. Same as STRICT but
+# the public CDN hosts are dropped from script-src and
+# 'self' is allowed instead, so chart libraries must be
+# served by the Open WebUI instance itself (drop the pinned
+# files under its /static directory — see the README
+# section "Offline mode"). External scripts, images, fonts
+# and media are all blocked; only same-origin, data: and
+# blob: sources load. For air-gapped / privacy-hardened
+# deployments. URL parameter stripping is applied like in
+# STRICT.
+#
+# Limitations that apply to ALL levels:
+# - Script execution is always permitted (required for core features).
+# - When iframe Same-Origin is enabled at the platform level, JS inside
+# the visualization can access the parent Open WebUI page. No CSP
+# level can prevent this — it is controlled by the platform setting.
+
+
+class Tools:
+ """Inline Visualizer — renders interactive HTML/SVG in chat.
+
+ Security is controlled via the ``security_level`` valve, which applies
+ a Content Security Policy to the rendered iframe. Defaults to STRICT,
+ which blocks outbound network requests (fetch/XHR) and form submissions
+ while allowlisting three public script CDNs. OFFLINE additionally
+ drops the CDN allowlist for zero external connections (self-hosted
+ libraries under the instance's /static directory still load).
+ Script execution is always permitted — it is required for interactive
+ visualizations, Chart.js, and D3. See the developer reference above
+ for the full security model and its limitations.
+ """
+
+ class Valves(BaseModel):
+ security_level: Literal["strict", "balanced", "none", "offline"] = Field(
+ default="strict",
+ description="Strict (default): blocks outbound fetch/XHR, images, and forms; scripts always allowed (3 public CDNs allowlisted). Offline: like Strict but with ZERO external connections — even the CDNs are blocked; libraries self-hosted under Open WebUI's /static folder still load (see README). Balanced: like Strict but also allows external images. None: no restrictions.",
+ )
+ chime: bool = Field(
+ default=True,
+ description="Play a soft three-note chime when a live-streamed visualization finishes. When off, the chime script is omitted from the iframe entirely (not shipped as a no-op).",
+ )
+
+ def __init__(self):
+ self.valves = self.Valves()
+
+ async def visualize(
+ self,
+ title: str = "Visualization",
+ __event_call__=None,
+ __event_emitter__=None,
+ ):
+ """
+ You need to call this tool before EVERY visualization you want to render.
+ What this tool does: visualize() mounts an iframe sandbox directly in the chat.
+ After this tool is called, the assistant must stream exactly one HTML/SVG visualization fragment between the plain-text delimiters @@@VIZ-START and @@@VIZ-END.
+ The sandbox renders that fragment live for the user.
+
+ Use this tool ONLY for EXPLICIT visualization requests.
+ Do NOT use this tool proactively. Do NOT infer that a visualization would be helpful.
+ **If the user did not explicitly ask for a visual artifact, do not call visualize().**
+ Never use visualize() for ordinary assistant output.
+ The chat you are responding in has a full Markdown, LaTeX, KaTeX and Mermaid rendering engine.
+ Call visualize() ONLY when the user clearly and UNAMBIGUOUSLY, DIRECTLY, EXPLICITLY asked for a visual artifact (e.g. diagrams, charts, graphs, dashboards, illustrations, interactive explainers, etc.).
+
+ IMPORTANT:
+ BEFORE CALLING THIS TOOL, YOU MUST: Call view_skill("visualize") FIRST.
+ You MUST call view_skill("visualize") first.
+ The visualize skill contains a mandatory handbook/tutorial with important rules for rendering, layout, SVG setup, chart patterns, colors, interactivity, and common failure points.
+ Never generate a visualization without reading the skill first.
+
+ After calling this tool:
+ In the assistant message that follows, emit exactly one visualization block:
+
+ @@@VIZ-START
+
+ @@@VIZ-END
+
+ Hard output rules:
+ - Use the delimiters exactly: @@@VIZ-START and @@@VIZ-END.
+ - Put each delimiter on its own line, and leave one empty line after @@@VIZ-END before any follow-up text.
+ - Emit exactly one @@@VIZ-START / @@@VIZ-END pair per tool call.
+ - Do not wrap the visualization in Markdown code fences.
+ - Do not use ```html, ```svg, ~~~, :::, or any other fenced block.
+ - Emit a fragment only: no , no , no , no .
+ - Structure the fragment as:
+ …all focus rings, checkboxes, and var(--accent) consumers go teal…
+
+
+**To apply an accent color to a specific section**: set data-accent on any inner container to recolor just its subtree:
+
+
+ Save
+
+
+Cancel
+
+**To apply an accent color to a single element**: set directly on an element to recolor just it:
+
+Approve
+Reject
+
+Both light and dark themes are handled — accent values track per-theme ramp stops automatically, and foreground text color flips for legibility in dark mode.
+No manual override needed.
+
+Pick an accent that matches the topic: green for finance/positive, red for warnings/critical actions, blue for informational dashboards, amber for attention/caution, etc.
+Default to purple for neutral or multi-purpose visualizations.
+
+## Output rules
+
+These rules keep visuals clean, accessible, and consistent with the host UI:
+
+- **Flat design** — no gradients, drop shadows, blur, glow, or noise textures (the host UI is flat; matching it prevents visual jarring)
+- **Prefer no emojis**, instead use CSS shapes or SVG paths for icons (emoji render inconsistently across platforms)
+- **Sentence case** — all labels and headings
+- **Round displayed numbers** — use Math.round, toLocaleString, or Intl.NumberFormat
+- **Min font size 11px** — smaller becomes unreadable on most screens
+- **Text weights** — 400 regular, 500 for emphasis only
+- Keep long-form explanation in the prose response. Use concise labels, captions, legends, helper text, and short annotations inside the visual when they improve comprehension.
+- **Build ambitiously when the topic supports it.** Treat each visualization like a small product surface, not a single static graphic. Combine multiple elements: a chart paired with a metric strip, a diagram with collapsible deep-dives, a comparison card with sliders that let the user explore tradeoffs. Use animation, hover, and click interactions where they help the reader notice or explore something — not for decoration. If the user asked for "a chart" and the topic naturally extends into a small dashboard, build the dashboard. Restraint is for cases where extra structure would distract; default to richness, not minimalism.
+
+---
+
+## Design system
+
+### CSS variables (auto-injected — prefer these so light/dark mode just works)
+
+The tool injects theme-aware CSS variables that adapt to light/dark mode automatically. Use them by default for text, surface, and border colors; reach for a specific hex only when the design genuinely calls for a fixed color (a brand mark, a deliberate accent that shouldn't track the theme).
+
+| Token | Purpose |
+|-------|---------|
+| --color-text-primary | Main text |
+| --color-text-secondary | Labels, muted text |
+| --color-text-tertiary | Hints, placeholders |
+| --color-text-info/success/warning/danger | Semantic text |
+| --color-bg-primary | Main background |
+| --color-bg-secondary | Cards, surfaces |
+| --color-bg-tertiary | Page background |
+| --color-border-tertiary | Default borders (0.15 alpha) |
+| --color-border-secondary | Hover borders (0.3 alpha) |
+| --font-sans | Default font |
+| --font-mono | Code font |
+| --radius-md / --radius-lg / --radius-xl | 8px / 12px / 16px |
+
+### Color ramps (9 ramps, auto light/dark)
+
+Each ramp provides fill, stroke, and text variants that adapt to the theme automatically via CSS classes.
+
+| Ramp | 50 (light fill) | 200 | 400 | 600 (light stroke) | 800 (light title) |
+|------|------|------|------|------|------|
+| purple | #EEEDFE | #AFA9EC | #7F77DD | #534AB7 | #3C3489 |
+| teal | #E1F5EE | #5DCAA5 | #1D9E75 | #0F6E56 | #085041 |
+| coral | #FAECE7 | #F0997B | #D85A30 | #993C1D | #712B13 |
+| pink | #FBEAF0 | #ED93B1 | #D4537E | #993556 | #72243E |
+| gray | #F1EFE8 | #B4B2A9 | #888780 | #5F5E5A | #444441 |
+| blue | #E6F1FB | #85B7EB | #378ADD | #185FA5 | #0C447C |
+| green | #EAF3DE | #97C459 | #639922 | #3B6D11 | #27500A |
+| amber | #FAEEDA | #EF9F27 | #BA7517 | #854F0B | #633806 |
+| red | #FCEBEB | #F09595 | #E24B4A | #A32D2D | #791F1F |
+
+### Chart dataset colors (use 400 stops)
+
+| Series | Color | Hex |
+|--------|-------|-----|
+| 1 | teal-400 | #1D9E75 |
+| 2 | purple-400 | #7F77DD |
+| 3 | coral-400 | #D85A30 |
+| 4 | blue-400 | #378ADD |
+| 5 | amber-400 | #BA7517 |
+
+For area/line fills, use same color at 20% opacity.
+
+---
+
+## SVG setup
+
+If you want to build a beautiful SVG to be rendered inside the chat, follow these rules too:
+Always use this SVG boilerplate:
+
+
+
+
+
+
+
+
+
+- viewBox width **always 680** — set H to **tightly fit** content (last element bottom + 40px). **Never oversize** — calculate the actual bottom of your last SVG element and add 40px. An SVG with content ending at y=180 must use H=220, not 500
+- Safe area: x=40 to x=640
+- Background transparent — host provides container
+
+### SVG classes (auto-injected)
+
+Drop these on SVG elements instead of writing inline fill, stroke, or
+font-size. They track the theme automatically.
+
+| Class | What it is | When to use |
+|-------|------------|-------------|
+| .t | 14px primary-color text | Default for any visible label inside a node, axis tick, or callout. |
+| .ts | 12px secondary-color text | Subtitles, captions, units (e.g. "users", "ms"), supporting text under a .t label. |
+| .th | 14px primary text, 500 weight | Node titles, KPI numbers, anything that needs to read as "the headline" of a small region. |
+| .box | Neutral rect — secondary bg, tertiary border | Default container for a labeled region. Use whenever you need a neutral chip / panel and don't have a semantic color. |
+| .node | Cursor-pointer + hover opacity on a | Mark a as clickable. Pair with onclick="sendPrompt(...)" so a user can drill into the topic. |
+| .arr | 1.5px stroke matching theme borders | Arrow lines and connectors. Combine with marker-end="url(#arrow)". |
+| .leader | 0.5px dashed guide line | Pulling a label to a part of an illustration when the label can't sit on top of it. |
+| .c-{ramp} | Sets fill/stroke + text colors on a whole from one of the 9 color ramps | Color a node by category — apply .c-teal (etc.) to a and its direct children pick up the matching ramp (not deeper descendants). Un-classed, un-filled / children (pie wedges, areas) take the ramp's series color; on a classed or filled mark, fill="currentColor" opts back in. |
+
+### Sizing text inside boxes
+
+Browsers don't auto-size SVG boxes to text. To pick a width, estimate
+the rendered glyph width per character and size the box from the
+longest line.
+
+- 14px text (.t, .th) → ~8 px / character
+- 12px text (.ts) → ~7 px / character
+- box_width = max(title_chars × 8, subtitle_chars × 7) + 24 (12 px padding each side)
+
+### Centering text in boxes
+
+ defaults to dominant-baseline="alphabetic" — y is the text's
+baseline, not its center, so a label placed at the vertical midpoint of
+a box actually sits ~4 px too high. For text inside a node, callout, or
+any rounded rect, add dominant-baseline="central" and put y at the
+box midpoint.
+
+Keep the default (no dominant-baseline) for text that's *meant* to sit
+on a baseline: axis tick labels (resting on the axis line), legend labels
+(aligned to the swatch baseline), and anything where the bottom edge of
+the glyphs is the visual anchor. Setting central on those will make
+them look ~4 px low instead.
+
+---
+
+## Diagram types
+
+### Flowchart — sequential steps, decisions
+
+- Max **4–5 nodes** per diagram — 6+ → decompose into overview + sub-flows
+- Box spacing: 60px between boxes, 24px padding inside
+- Single-line node: height 44px, two-line: 56px
+- Arrows must not cross any box — use L-bends if needed
+- Use marker-end="url(#arrow)" on arrow paths
+
+Single-line node:
+
+
+
+ Label
+
+
+Two-line node:
+
+
+
+ Title
+ Subtitle
+
+
+### Architecture — nested regions, layered systems
+
+For diagrams that show **what contains what**: services inside zones,
+modules inside layers, components inside subsystems. The nesting itself
+is the information — outer regions are the system, inner regions are
+the parts.
+
+- Outermost container: rx=20–24, lightest ramp fill (the 50 stop), 0.5px stroke
+- Inner regions: rx=8–12, a darker stop of the same ramp — or a different ramp when the inner region is semantically distinct (e.g. external service inside an internal cluster)
+- 20px minimum padding between an inner region's bounds and its parent's edge
+- Max 2–3 nesting levels — beyond that, decompose into a top-level overview plus sub-diagrams
+
+### Illustrative — explain a mechanism by drawing it
+
+For "how does this actually work" topics where the answer is spatial:
+how light refracts through a prism, how a transformer attention head
+weighs tokens, how a heat pump moves heat against a gradient. **Draw
+the thing itself**, not a labeled diagram about it.
+
+- Shapes are freeform — paths, ellipses, polygons, curves — not just rounded rects
+- Color encodes intensity or state, not category: warm ramps for active / hot / energized, cool ramps for calm / cold / passive, gray for neutral / inert
+- Labels live outside the object connected via .leader lines — reserve a ~140px gutter on the side you'll label from
+- Strongly prefer **interactive** illustrative diagrams: if the real system has a knob, a slider, or a phase, expose it. A prism with a draggable angle slider teaches refraction better than five static frames.
+
+---
+
+## Charts (Chart.js)
+
+Load Chart.js in your HTML fragment:
+
+
+
+Setup pattern:
+
+
+
+
+
+
+**Chart rules:**
+- Wrap canvas in container with position: relative and explicit height — without it, maintainAspectRatio: false collapses the canvas to zero
+- Always pass responsive: true, maintainAspectRatio: false in options — without maintainAspectRatio: false, Chart.js locks the canvas to a 2:1 aspect and ignores the container height; without responsive: true, it won't redraw when the iframe re-measures. You have to set them explicitly on every new Chart(...) call (Chart.js reads options at construction time, so there's no global default we could pre-set for you).
+- Read CSS variables for text/border colors so the chart tracks the theme
+- borderRadius: 4 on bars
+- Line charts: tension: 0.3 for smooth curves
+- Doughnut: cutout: '60%' — never use pie
+
+**Chart type selection:**
+
+| Data shape | Type | Notes |
+|-----------|------|-------|
+| Categories + values (a few items, comparable magnitudes) | **Bar** | Default for "compare values across labels". Switch to a horizontal bar (indexAxis: 'y') when labels are long, when there are 8+ categories, or when ranking is the point. |
+| Time series, anything sampled at regular intervals | **Line** | tension: 0.3 for a natural curve. Stack multiple datasets when you're comparing trends, not when each line wanders independently — overlap gets unreadable past 4 lines. |
+| Parts of a whole, ≤5 slices | **Doughnut** | Use cutout: '60%' so the empty middle can hold a total or label. Skip if the segments are very uneven (one slice >70%) — the small slices vanish; show a stacked bar instead. |
+| Two continuous variables, looking for correlation | **Scatter** | Add a trend line if the relationship is the takeaway. For dense clouds, drop point opacity to 0.3–0.5 so density reads. |
+| Stacked / cumulative composition over time | **Stacked bar / stacked area** | Bar when the buckets are discrete (months, segments); area when the underlying signal is continuous. |
+| Single-value vs target / threshold | **Bar with reference line** or KPI card | A whole chart is overkill for one number — consider a metric card with a sparkline instead. |
+| Multi-dimensional comparison (3–6 axes) | **Radar** | Only when the axes are genuinely commensurate — otherwise a small-multiples bar grid is clearer. |
+
+### Inline SVG charts (no library)
+
+Reach for inline SVG when the data is small, the shape is simple, or
+you want the chart to share design with surrounding diagrams (matching
+corner radii, palette, type). No script, no CDN — just shapes and text.
+Reach for Chart.js when you need axes, tooltips, hover, animation, or
+many series.
+
+**Good fits for inline SVG:**
+- **Progress / completion bar** — a value rendered against a fixed track, often paired with a percentage label to its right
+- **Ranking strip** — a small number of horizontal bars stacked vertically, each bar a different category color, sized by value
+- **Sparkline** — a terse trend line with no axes that sits next to a number to give the number context
+- **KPI donut / ring** — a single percentage rendered as a circle arc, with the number in the middle of the ring
+- **Stacked composition row** — one horizontal bar split into colored segments to show parts of a whole, when a doughnut would feel heavy
+- **Custom-shape charts** — anything where the chart shape is part of the metaphor (a thermometer for temperature, a battery for charge, a fuel gauge, a tide-line)
+
+**Theme consistency for inline SVG:**
+- Use the .t / .ts / .th classes on for labels, captions, and headlines.
+ They pick up the theme's text colors and typography scale automatically.
+ Never set font-size or fill on label text manually unless you need a specific deviation.
+- For neutral backgrounds (track behind a progress bar, empty slot in a ring), use fill="var(--color-bg-secondary)" so it blends into the surrounding card.
+- For data colors, prefer the chart-dataset 400-stop hexes from the table above — they're calibrated to read on both light and dark backgrounds.
+ If you need a *whole group* recolored (rect + label + stroke together), wrap it in a (or any of the 9 ramp classes) and let the SVG class system handle fill + stroke + text in one shot.
+- Keep stroke-widths to 0.5 px for chrome (axis lines, grid) and 1.5 px for data (lines, sparklines) — matches the 0.5 px borders the rest of the host UI uses, so the chart doesn't feel chunkier than its neighbors.
+- Add opacity="0.85" on data fills — softens the color slightly so it sits comfortably next to text without overwhelming it.
+
+**Math hints for the less obvious shapes:**
+- Donut arc length: circumference = 2 × π × r. To draw v% of the ring, set stroke-dasharray="{v×circumference/100} {circumference}" on the foreground circle, and transform="rotate(-90 cx cy)" so the arc starts at 12 o'clock instead of 3 o'clock.
+- Bar widths in a viewBox="0 0 680 …": leave 40 px of margin on each side, giving a 600 px usable plot width.
+
+---
+
+## Component patterns
+
+### Metric cards — KPI strip
+
+
+
+
Revenue
+
$3,870
+
▲ 12.4%
+
+
+
+
+Pair with a chart below for a compact dashboard. Add a tiny inline-SVG
+sparkline under each value if the trend matters.
+
+### Comparison layout — two paths side by side
+
+
+
+
Monolith
+
+ Deploy unit 1 service
+ Latency Low (in-process)
+ Scaling Vertical
+
+
+
+
Microservices
+
+ Deploy unit N services
+ Latency Higher (network)
+ Scaling Horizontal per service
+
+
+
+
+### Interactive explainer — slider drives output
+
+
+ Interest
+
+ 5.0%
+
+
+
+
+
+The pattern generalises: every interactive element binds an input listener, recomputes a value, and writes it to a result node.
+Pair with an inline SVG that re-draws on every input change for a "live diagram".
+
+### Tabs — a piece of UI users already know
+
+
+
+ Overview
+ Details
+ Source
+
+…
+…
+…
+
+
+
+
+
+Persist the active tab with saveState/loadState so it survives reloads.
+
+**Charts in inactive tabs render at 0×0.** Plotly, ECharts, and vis-network all measure their container at init time.
+If that container is inside a hidden / display:none panel, they paint into a zero-size canvas and stay blank even after the tab becomes visible.
+Two workarounds, pick one:
+
+1. **Lazy-init**: only call Plotly.newPlot / echarts.init / new vis.Network the first time its tab is shown (track a tabInit[id] flag in the handler).
+2. **Resize on show**: init everything up front (so data is ready), then in showTab call the right resize hook for whichever lib is in that tab.
+ Note the API differs per library — c.resize() does not work for all of them:
+
+ // ECharts: instance.resize()
+ echartsInstance.resize();
+ // Plotly: pass the container element, no .resize() on the chart
+ Plotly.Plots.resize(document.getElementById('plotly-container'));
+ // vis-network: redraw + fit — the instance has no .resize()
+ networkInstance.redraw();
+ networkInstance.fit();
+ // Chart.js: instance.resize() — but Chart.js auto-resizes on
+ // container size change so usually nothing needed.
+
+ Skip the resize call for D3 / Vega-Lite / inline SVG — they paint declaratively into the SVG namespace and aren't bothered by hidden parents.
+
+### Step-through walkthrough — guided narrative
+A "Next ▶" button advances through a sequence of stages, each with its own caption and (optionally) a different highlighted region of the same diagram.
+Useful for explaining algorithms, processes, or any topic where the order matters more than the totals.
+
+
+Click Next to begin.
+Next ▶
+
+
+
+---
+
+## sendPrompt bridge — conversational diagrams
+
+sendPrompt(text) is the function that makes visualizations conversational. When called, it injects the given text into the chat input field and submits it — exactly as if the user had typed and sent it themselves. The model then receives that message and responds normally, creating a feedback loop between the visual and the conversation.
+
+This is what separates a static diagram from an **exploration interface**. A user sees a system architecture diagram, clicks on the "Load Balancer" node, and the model receives "Tell me more about the load balancer — how does it distribute traffic across the backend services?" as a user message. The model then responds with details, and could even generate a *new* sub-diagram showing the load balancer internals. The user never had to type anything — they just clicked.
+
+### Why this matters
+
+Without sendPrompt, interactive elements inside the iframe are isolated — they can toggle visibility, animate, or filter data, but they can never talk back to the model. The user sees a cool diagram but has to manually type follow-up questions. With sendPrompt, every clickable element becomes a conversation starter. The diagram itself becomes a navigation interface for the topic.
+
+### Writing good sendPrompt text
+
+The text you pass to sendPrompt becomes the user's message to the model. Write it as a natural follow-up question — conversational, specific, and referencing the context of the diagram:
+
+**Good prompt text** (specific, contextual, references the diagram):
+- "Explain the attention mechanism — how does it decide which tokens to focus on?"
+- "Break down the CI/CD pipeline stage. What tools are typically used here?"
+- "Show me a more detailed diagram of the data processing layer"
+- "What happens when the load balancer detects a failed backend node?"
+- "Compare the pros and cons of the monolith vs microservices approach shown here"
+
+### Usage patterns
+
+Simple patterns — single-click sendPrompt on a node or button:
+- **Drill-down**: onclick="sendPrompt('Explain the API gateway — what does it handle?')" on a diagram node
+- **Quiz answer**: onclick="sendPrompt('I chose B: O(n log n). Am I right? Explain why.')" on answer buttons
+- **Guided exploration**: onclick="sendPrompt('Show me a more advanced example with edge cases.')" on a "Go deeper →" button
+- **Comparison**: onclick="sendPrompt('Compare REST vs GraphQL — when should I use each?')" on one of two nodes
+
+**Form / preference collector** — gather multiple user selections, then send them all at once. Use local JS to track choices (button highlights, state object) and a submit button that composes a sendPrompt from the collected answers:
+
+
+
+What's your style?
+Pace
+Relaxed
+Moderate
+Intensive
+
+Focus
+Culture
+Nature
+Food
+
+Get my recommendation →
+
+This pattern is powerful because the model receives a structured summary of all user preferences in one message. Use local JS for the selection UI (instant feedback), then sendPrompt only on final submit.
+
+### When to use sendPrompt vs local JS:
+| User action | Use | Why |
+|------------|-----|-----|
+| Learn more about a component | sendPrompt | Model gives a contextual explanation |
+| Explore a stage / drill down | sendPrompt | Model can generate a sub-diagram |
+| Submit answers or preferences | sendPrompt | Model evaluates or personalizes |
+| Toggle views, adjust sliders | Local JS | Instant feedback, no reasoning needed |
+| Filter/sort data | Local JS | Instant response, no model needed |
+
+---
+
+## Interactivity by default
+
+Build dashboards, charts, graphs, interactive functions, animated sections, moving objects, expandable detail sections, cards, copyable text elements and more. If the topic allows and it makes sense for the topic, build complex and visually stunning elements.
+
+Visualizations should feel alive and polished — not static images dumped into chat. Build interfaces that invite interaction:
+
+- **Expandable sections** — use collapsible elements or JS-toggled sections so users can explore at their own pace without overwhelming them upfront
+- **Hover effects** — nodes, buttons, and cards should respond to hover (the .node class adds this for SVG elements; for HTML, use :hover styles)
+- **Smooth transitions** — add transition: all 0.2s ease to interactive elements for a polished feel
+- **Active states** — when a user selects an option or clicks a tab, make the selection visually clear with your own .active class or distinct styling
+- **Progressive disclosure** — show a clean overview first, let the user click to reveal detail (tabs, accordions, or sendPrompt for model-powered drill-down)
+
+**The goal is to build something that feels like a real app component embedded in chat with reactivity, sections and extra elements** — not a screenshot. If the visualization has multiple facets, give the user controls to explore them. If it has hierarchical information, let them expand and collapse. If it has data, let them sort or filter.
+
+---
+
+## openLink bridge — opening URLs from visualizations
+
+openLink(url) opens a URL in a new browser tab from within the visualization iframe. Normal links inside an iframe can behave unpredictably (opening inside the iframe, being blocked by sandbox restrictions, etc.). This function handles that by opening the link in the parent window instead.
+
+
+ Open API docs ↗
+
+
+Or in SVG:
+
+
+
+ View source ↗
+
+
+Use openLink for external references, documentation links, or source code links. Unlike sendPrompt, this navigates away from the chat — use it when the user needs to access an external resource, not when they need the model to explain something.
+
+---
+
+## copyText + toast bridges — feedback on user actions
+
+copyText(text) copies text to the system clipboard and automatically shows a localized "Copied" toast in the top-right corner of the iframe. Works from HTTPS and HTTP origins (falls back to execCommand('copy') if the async Clipboard API is blocked). Use this on "Copy" buttons inside interactive visualizations — data tables, code snippets, shareable values.
+
+Copy JSON
+
+toast(message, kind) shows a small auto-dismissing banner inside the iframe. kind is optional and controls the text color: 'success' (green, default), 'info' (blue), 'warn' (amber), 'error' (red). Use it for status notifications inside long-running interactive tools — "Calculation done", "Invalid input", etc.
+
+Recompute
+
+Toasts auto-dismiss after ~2.2 s and stack vertically if fired in quick succession.
+
+---
+
+## saveState + loadState bridges — persistent interactive state
+
+saveState(key, value) and loadState(key, fallback) proxy parent.localStorage with a key prefix scoped to **this assistant message**. State survives page reloads and tab switches, but two different chats (or different messages in the same chat) each get their own independent state — no cross-contamination.
+
+
+
+Use it for: selected tabs, picked chart range, hidden/shown layers, theme overrides, collapsed sections — anything the user would expect to be remembered when they re-open the chat.
+
+Values are JSON-serialized. If localStorage is blocked (private browsing, sandboxed), both functions silently no-op and loadState returns fallback.
+
+---
+
+## CDN libraries
+
+The CSP allowlists three CDN hosts for scripts only: any script served from them
+loads, CDN stylesheets and fonts are blocked, so inline any CSS a library needs.
+
+Allowed hosts:
+- cdnjs.cloudflare.com — widest coverage
+- cdn.jsdelivr.net — npm / GitHub backed, supports minor-version pinning
+- unpkg.com — npm mirror
+
+Common picks:
+
+| Library | Why reach for it | Example loader |
+|---------|------------------|----------------|
+| **Chart.js** | Bar / line / doughnut / scatter with animation out of the box | |
+| **D3.js** | Custom data-driven SVG (force graphs, arcs, maps, non-standard charts) | |
+| **Vega-Lite** | Declarative grammar of graphics — feed it a JSON spec, it draws the chart | |
+| **ECharts** | Rich interactive dashboards, advanced chart types | |
+| **Plotly** | Scientific / 3D plots, statistical charts | |
+| **vis-network** | Force-directed network / node-link graphs | (the **standalone** UMD bundle — exposes vis.Network *and* vis.DataSet. The bare vis-network.min.js on cdnjs is the *peer* build and requires vis-data loaded separately, otherwise new vis.DataSet(...) throws vis is not defined.) |
+| **Tone.js / Wavesurfer** | Audio synthesis, waveform visualisation | |
+
+Anything else on those three CDNs is fair game — apexcharts, d3-force,
+konva, flatpickr, etc. Pick whatever fits the topic.
+
+---
+
+## Library init
+
+Two patterns to follow when using a CDN library:
+
+### 1 · Wrap a Chart.js canvas in a fixed-height container
+
+maintainAspectRatio: false makes Chart.js use the container's height.
+If the canvas has no intrinsic height (e.g. inside a flex column without a height set), it collapses to zero and nothing draws:
+
+
+
+
+
+
+### 2 · Source order matters
+
+Put external
+
+