Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(knowledge): support local HTML uploads
xiaowangf3cd3d972412
diff --git a/docreader/parser/__init__.py b/docreader/parser/__init__.pyindex f37075d44..f55257d46 100644--- a/docreader/parser/__init__.py+++ b/docreader/parser/__init__.py@@ -16,6 +16,7 @@ meaningful chunks for further processing and indexing.from .doc_parser import DocParserfrom .docx2_parser import Docx2Parserfrom .excel_parser import ExcelParser+from .html_parser import HTMLParserfrom .image_parser import ImageParserfrom .markdown_parser import MarkdownParserfrom .parser import Parser@@ -33,6 +34,7 @@ __all__ = ["WebParser","Parser","ExcelParser",+ "HTMLParser","ParserEngineRegistry","registry",]diff --git a/docreader/parser/html_parser.py b/docreader/parser/html_parser.pynew file mode 100644index 000000000..79c69143b--- /dev/null+++ b/docreader/parser/html_parser.py@@ -0,0 +1,37 @@+"""Static HTML file parser."""++from bs4 import BeautifulSoup++from docreader.models.document import Document+from docreader.parser.base_parser import BaseParser+from docreader.parser.chain_parser import PipelineParser+from docreader.parser.markdown_parser import MarkdownParser+from docreader.parser.mhtml_parser import MHTMLParser+++class HTMLToMarkdownParser(BaseParser):+ """Convert uploaded HTML bytes to Markdown without browser or network access."""++ def parse_into_text(self, content: bytes) -> Document:+ if not content.strip():+ return Document()++ # Inspect the original bytes so BOMs and HTML charset declarations are+ # honored before the shared Markdown conversion runs.+ html = BeautifulSoup(content, "lxml").decode()+ markdown = MHTMLParser(+ file_name=self.file_name,+ file_type=self.file_type,+ extract_images=False,+ ).html_to_markdown(+ html,+ strip_internal_links=False,+ fallback_to_raw_html=False,+ )+ return Document(content=markdown or "")+++class HTMLParser(PipelineParser):+ """Extract static HTML content and normalize the resulting Markdown."""++ _parser_cls = (HTMLToMarkdownParser, MarkdownParser)diff --git a/docreader/parser/mhtml_parser.py b/docreader/parser/mhtml_parser.pyindex b5fded30d..08aac048c 100644--- a/docreader/parser/mhtml_parser.py+++ b/docreader/parser/mhtml_parser.py@@ -83,7 +83,7 @@ class MHTMLParser(BaseParser):html_content = main_html["content"]try:- markdown_text = self._html_to_markdown(+ markdown_text = self.html_to_markdown(html_content,image_aliases=image_aliases,base_location=main_html.get("location", ""),@@ -118,11 +118,15 @@ class MHTMLParser(BaseParser):return non_ad[0]largest = max(html_parts, key=lambda part: part["size"])- logger.warning("Only ad content found, using largest: %d bytes", largest["size"])+ logger.warning(+ "Only ad content found, using largest: %d bytes", largest["size"]+ )return largest@staticmethod- def _add_image_aliases(image_aliases: Dict[str, str], part, image_path: str) -> None:+ def _add_image_aliases(+ image_aliases: Dict[str, str], part, image_path: str+ ) -> None:"""Register the refs an MHTML document may use for an image part."""for raw in (part.get("Content-Location", ""),@@ -192,19 +196,30 @@ class MHTMLParser(BaseParser):return ""return filename- def _html_to_markdown(+ def html_to_markdown(self,html_content: str,image_aliases: Dict[str, str] | None = None,base_location: str = "",+ *,+ strip_internal_links: bool = True,+ fallback_to_raw_html: bool = True,) -> str:+ """Convert HTML to Markdown with explicit link and fallback policies."""++ def raw_html_fallback() -> str:+ if not fallback_to_raw_html:+ return ""+ return f"```html\n{html_content[:50000]}\n```"+try:from markdownify import markdownify as mdsoup = BeautifulSoup(html_content, "lxml")for tag in soup(["script", "style", "noscript", "iframe"]):tag.decompose()- self._strip_internal_links(soup)+ if strip_internal_links:+ self._strip_internal_links(soup)if image_aliases:self._rewrite_image_sources(soup, image_aliases, base_location)text_fallback = soup.get_text(separator="\n", strip=True)@@ -214,14 +229,23 @@ class MHTMLParser(BaseParser):logger.warning("Markdown empty, falling back to text extraction")return text_fallbackif not result:- return f"```html\n{html_content[:50000]}\n```"+ return raw_html_fallback()return resultexcept ImportError:logger.warning("markdownify not available, returning raw HTML")- return f"```html\n{html_content}\n```"+ return raw_html_fallback()except Exception as e:logger.error("HTML to Markdown conversion failed: %s", e)- return f"```html\n{html_content}\n```"+ return raw_html_fallback()++ def _html_to_markdown(+ self,+ html_content: str,+ image_aliases: Dict[str, str] | None = None,+ base_location: str = "",+ ) -> str:+ """Backward-compatible wrapper for existing internal callers and tests."""+ return self.html_to_markdown(html_content, image_aliases, base_location)@staticmethoddef _normalize_markdown(markdown_text: str) -> str:diff --git a/docreader/parser/registry.py b/docreader/parser/registry.pyindex 7a5cccb59..30825b12f 100644--- a/docreader/parser/registry.py+++ b/docreader/parser/registry.py@@ -1,11 +1,12 @@import logging-from typing import Any, Callable, Dict, List, Optional, Tuple, Type+from typing import Callable, Dict, List, Optional, Tuple, Typefrom docreader.parser.base_parser import BaseParserfrom docreader.parser.doc_parser import DocParserfrom docreader.parser.docx2_parser import Docx2Parserfrom docreader.parser.epub_parser import EPUBParserfrom docreader.parser.excel_parser import ExcelParser+from docreader.parser.html_parser import HTMLParserfrom docreader.parser.image_parser import ImageParserfrom docreader.parser.markdown_parser import MarkdownParserfrom docreader.parser.markitdown_parser import MarkitdownParser@@ -134,6 +135,8 @@ def _build_default_registry() -> ParserEngineRegistry:"xlsx": ExcelParser,"xls": ExcelParser,"epub": EPUBParser,+ "html": HTMLParser,+ "htm": HTMLParser,"mhtml": MHTMLParser,**_image_types,},@@ -161,7 +164,9 @@ def _build_default_registry() -> ParserEngineRegistry:"opendataloader",{"pdf": OpenDataLoaderParser},description="OpenDataLoader PDF(版面分析,需 Java 11+)",- check_available=lambda overrides: opendataloader_available(overrides, quick=True),+ check_available=lambda overrides: opendataloader_available(+ overrides, quick=True+ ),unavailable_hint="请安装 opendataloader-pdf 与 Java 11+",)diff --git a/docreader/tests/test_html_parser.py b/docreader/tests/test_html_parser.pynew file mode 100644index 000000000..0694f7da0--- /dev/null+++ b/docreader/tests/test_html_parser.py@@ -0,0 +1,71 @@+import unittest+from pathlib import Path++from docreader.parser.html_parser import HTMLParser+from docreader.parser.registry import BUILTIN_ENGINE, registry++REPO_ROOT = Path(__file__).resolve().parents[2]+++class HTMLParserTest(unittest.TestCase):+ def test_parse_static_html_fixture_into_markdown(self):+ content = (REPO_ROOT / "docreader" / "testdata" / "test.html").read_bytes()++ document = HTMLParser(file_name="test.html", file_type="html").parse(content)++ self.assertIn("# 测试 HTML 文档", document.content)+ self.assertIn("[测试链接](https://example.com)", document.content)+ self.assertIn("| 表头1 | 表头2 |", document.content)+ self.assertIn("内容4", document.content)++ def test_parse_empty_html_returns_empty_document(self):+ document = HTMLParser(file_name="empty.htm", file_type="htm").parse(b"")++ self.assertEqual("", document.content)++ def test_parse_honors_declared_windows_1252_charset(self):+ html = (+ '<meta charset="windows-1252">'+ "<h1>R\u00e9sum\u00e9 \u201cquoted\u201d \u20ac</h1>"+ ).encode("windows-1252")++ document = HTMLParser(file_name="legacy.html", file_type="html").parse(html)++ self.assertIn("# R\u00e9sum\u00e9 \u201cquoted\u201d \u20ac", document.content)++ def test_parse_honors_utf16_bom(self):+ html = "<html><body><h1>UTF-16 title</h1></body></html>".encode("utf-16")++ document = HTMLParser(file_name="utf16.html", file_type="html").parse(html)++ self.assertIn("# UTF-16 title", document.content)+ self.assertNotIn("\x00", document.content)++ def test_parse_script_only_html_returns_empty_document(self):+ html = (+ b"<html><body><script>alert('x')</script><style>p{}</style></body></html>"+ )++ document = HTMLParser(file_name="script.html", file_type="html").parse(html)++ self.assertEqual("", document.content)++ def test_parse_preserves_relative_and_fragment_links(self):+ html = b'<a href="./guide.html">Guide</a><a href="#section">Section</a>'++ document = HTMLParser(file_name="links.html", file_type="html").parse(html)++ self.assertIn("[Guide](./guide.html)", document.content)+ self.assertIn("[Section](#section)", document.content)++ def test_registry_routes_html_extensions_to_html_parser(self):+ self.assertIs(registry.get_parser_class("", "html"), HTMLParser)+ self.assertIs(registry.get_parser_class("", "htm"), HTMLParser)++ builtin_types = registry._engines[BUILTIN_ENGINE]+ self.assertIn("html", builtin_types)+ self.assertIn("htm", builtin_types)+++if __name__ == "__main__":+ unittest.main()diff --git a/frontend/src/utils/fileTypeVerification.test.ts b/frontend/src/utils/fileTypeVerification.test.tsnew file mode 100644index 000000000..338f9ef60--- /dev/null+++ b/frontend/src/utils/fileTypeVerification.test.ts@@ -0,0 +1,16 @@+import assert from 'node:assert/strict'+import test from 'node:test'++import { shouldRejectKnowledgeFileType } from './fileTypeVerification.ts'++test('shouldRejectKnowledgeFileType accepts HTML in the fallback whitelist', () => {+ assert.equal(shouldRejectKnowledgeFileType('page.html'), false)+ assert.equal(shouldRejectKnowledgeFileType('legacy.HTM'), false)+ assert.equal(shouldRejectKnowledgeFileType('payload.exe'), true)+})++test('shouldRejectKnowledgeFileType preserves dynamic whitelist behavior', () => {+ assert.equal(shouldRejectKnowledgeFileType('custom.xyz', ['xyz']), false)+ assert.equal(shouldRejectKnowledgeFileType('page.html', ['pdf']), true)+ assert.equal(shouldRejectKnowledgeFileType('page.html', []), false)+})diff --git a/frontend/src/utils/fileTypeVerification.ts b/frontend/src/utils/fileTypeVerification.tsnew file mode 100644index 000000000..24d46ddde--- /dev/null+++ b/frontend/src/utils/fileTypeVerification.ts@@ -0,0 +1,39 @@+const DEFAULT_VALID_TYPES = new Set([+ "pdf",+ "txt",+ "md",+ "docx",+ "doc",+ "pptx",+ "ppt",+ "epub",+ "html",+ "htm",+ "mhtml",+ "jpg",+ "jpeg",+ "png",+ "csv",+ "xlsx",+ "xls",+ "mp3",+ "wav",+ "m4a",+ "flac",+ "ogg",+]);++export function shouldRejectKnowledgeFileType(+ filename: string,+ validTypes?: Set<string> | string[],+) {+ const provided = validTypes+ ? validTypes instanceof Set+ ? validTypes+ : new Set(validTypes)+ : undefined;+ const allowed = provided && provided.size > 0 ? provided : DEFAULT_VALID_TYPES;+ const type = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();++ return !allowed.has(type);+}diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.tsindex 2cbca4acd..235afda69 100644--- a/frontend/src/utils/index.ts+++ b/frontend/src/utils/index.ts@@ -1,5 +1,6 @@import { MessagePlugin } from "tdesign-vue-next";import i18n from '@/i18n';+import { shouldRejectKnowledgeFileType } from "./fileTypeVerification";// 声明全局运行时配置类型declare global {@@ -40,8 +41,6 @@ export function formatStringDate(date: any) {year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second);}-const DEFAULT_VALID_TYPES = new Set(["pdf", "txt", "md", "docx", "doc", "pptx", "ppt", "epub", "mhtml", "jpg", "jpeg", "png", "csv", "xlsx", "xls", "mp3", "wav", "m4a", "flac", "ogg"]);-/** Returns true when the file exceeds the deploy-time upload limit. */export function fileSizeVerification(file: Pick<File, 'size'>, silent = false) {if (file.size <= MAX_FILE_SIZE_BYTES) return false;@@ -56,15 +55,7 @@ export function fileSizeVerification(file: Pick<File, 'size'>, silent = false) {* @param validTypes - override the default extension whitelist with a dynamic set (e.g. from engine registry).*/export function kbFileTypeVerification(file: any, silent = false, validTypes?: Set<string> | string[]) {- const provided = validTypes- ? (validTypes instanceof Set ? validTypes : new Set(validTypes))- : undefined;- // An empty whitelist means the engine registry hasn't loaded yet; fall back to- // the default set rather than rejecting every file.- const allowed = provided && provided.size > 0 ? provided : DEFAULT_VALID_TYPES;-- const type = file.name.substring(file.name.lastIndexOf(".") + 1).toLowerCase();- if (!allowed.has(type)) {+ if (shouldRejectKnowledgeFileType(file.name, validTypes)) {if (!silent) {MessagePlugin.error(i18n.global.t('error.unsupportedFileType'));}diff --git a/internal/application/service/knowledge_util.go b/internal/application/service/knowledge_util.goindex da4639861..080ae4540 100644--- a/internal/application/service/knowledge_util.go+++ b/internal/application/service/knowledge_util.go@@ -22,7 +22,7 @@ import (// isValidFileType checks if a file type is supportedfunc isValidFileType(filename string) bool {switch strings.ToLower(getFileType(filename)) {- case "pdf", "txt", "docx", "doc", "epub", "mhtml", "md", "markdown", "png", "jpg", "jpeg", "gif", "csv", "xlsx", "xls", "pptx", "ppt", "json",+ case "pdf", "txt", "docx", "doc", "epub", "html", "htm", "mhtml", "md", "markdown", "png", "jpg", "jpeg", "gif", "csv", "xlsx", "xls", "pptx", "ppt", "json","mp3", "wav", "m4a", "flac", "ogg":return truedefault:diff --git a/internal/application/service/knowledge_util_filetype_test.go b/internal/application/service/knowledge_util_filetype_test.gonew file mode 100644index 000000000..e86a2da36--- /dev/null+++ b/internal/application/service/knowledge_util_filetype_test.go@@ -0,0 +1,24 @@+package service++import "testing"++func TestIsValidFileTypeHTML(t *testing.T) {+ tests := []struct {+ name string+ filename string+ want bool+ }{+ {name: "html", filename: "index.html", want: true},+ {name: "uppercase html", filename: "INDEX.HTML", want: true},+ {name: "htm", filename: "legacy.htm", want: true},+ {name: "unsupported", filename: "payload.exe", want: false},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := isValidFileType(tt.filename); got != tt.want {+ t.Fatalf("isValidFileType(%q) = %v, want %v", tt.filename, got, tt.want)+ }+ })+ }+}diff --git a/internal/infrastructure/docparser/engine_registry.go b/internal/infrastructure/docparser/engine_registry.goindex 8fed0e3af..4d59f9660 100644--- a/internal/infrastructure/docparser/engine_registry.go+++ b/internal/infrastructure/docparser/engine_registry.go@@ -45,7 +45,7 @@ func (e *builtinEngine) Description() string {return "DocReader built-in parser engine"}func (e *builtinEngine) FileTypes(_ bool) []string {- return []string{"docx", "doc", "pdf", "md", "markdown", "xlsx", "xls", "epub", "mhtml", "jpg", "jpeg", "png", "gif", "bmp", "tiff", "webp", "mp3", "wav", "m4a", "flac", "ogg"}+ return []string{"docx", "doc", "pdf", "md", "markdown", "xlsx", "xls", "epub", "html", "htm", "mhtml", "jpg", "jpeg", "png", "gif", "bmp", "tiff", "webp", "mp3", "wav", "m4a", "flac", "ogg"}}func (e *builtinEngine) CheckAvailable(docreaderConnected bool, _ map[string]string) (bool, string) {if docreaderConnected {diff --git a/internal/infrastructure/docparser/engine_registry_test.go b/internal/infrastructure/docparser/engine_registry_test.gonew file mode 100644index 000000000..f2a9b07bc--- /dev/null+++ b/internal/infrastructure/docparser/engine_registry_test.go@@ -0,0 +1,28 @@+package docparser++import "testing"++func TestListAllEnginesBuiltinIncludesHTML(t *testing.T) {+ engines := ListAllEngines(true, nil, nil)+ for _, engine := range engines {+ if engine.Name != "builtin" {+ continue+ }+ if !engine.Available {+ t.Fatalf("builtin engine is unavailable: %s", engine.UnavailableReason)+ }++ fileTypes := make(map[string]bool, len(engine.FileTypes))+ for _, fileType := range engine.FileTypes {+ fileTypes[fileType] = true+ }+ for _, want := range []string{"html", "htm"} {+ if !fileTypes[want] {+ t.Errorf("builtin engine file types do not include %q: %v", want, engine.FileTypes)+ }+ }+ return+ }++ t.Fatal("builtin engine not found")+}