fix(knowledge): support local HTML uploads
English: Accept .html and .htm knowledge uploads across frontend, Go, and DocReader. Parse static HTML with charset-aware decoding, preserve document structure and local links, and keep scripts/network execution disabled. Add regression coverage for validation, engine registration, encoding, and parser behavior. 中文:打通知识库本地 .html 与 .htm 文件从前端、Go 服务到 DocReader 的完整上传链路。使用可识别字符编码的静态解析,保留文档结构和本地链接,不执行脚本或发起网络请求,并补充文件校验、引擎注册、编码及解析行为的回归测试。main
parent
55840b1a02
commit
f3cd3d9724
|
|
@ -16,6 +16,7 @@ meaningful chunks for further processing and indexing.
|
|||
from .doc_parser import DocParser
|
||||
from .docx2_parser import Docx2Parser
|
||||
from .excel_parser import ExcelParser
|
||||
from .html_parser import HTMLParser
|
||||
from .image_parser import ImageParser
|
||||
from .markdown_parser import MarkdownParser
|
||||
from .parser import Parser
|
||||
|
|
@ -33,6 +34,7 @@ __all__ = [
|
|||
"WebParser",
|
||||
"Parser",
|
||||
"ExcelParser",
|
||||
"HTMLParser",
|
||||
"ParserEngineRegistry",
|
||||
"registry",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
@ -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 md
|
||||
|
||||
soup = 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_fallback
|
||||
if not result:
|
||||
return f"```html\n{html_content[:50000]}\n```"
|
||||
return raw_html_fallback()
|
||||
return result
|
||||
except 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)
|
||||
|
||||
@staticmethod
|
||||
def _normalize_markdown(markdown_text: str) -> str:
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
import logging
|
||||
from typing import Any, Callable, Dict, List, Optional, Tuple, Type
|
||||
from typing import Callable, Dict, List, Optional, Tuple, Type
|
||||
|
||||
from docreader.parser.base_parser import BaseParser
|
||||
from docreader.parser.doc_parser import DocParser
|
||||
from docreader.parser.docx2_parser import Docx2Parser
|
||||
from docreader.parser.epub_parser import EPUBParser
|
||||
from docreader.parser.excel_parser import ExcelParser
|
||||
from docreader.parser.html_parser import HTMLParser
|
||||
from docreader.parser.image_parser import ImageParser
|
||||
from docreader.parser.markdown_parser import MarkdownParser
|
||||
from 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+",
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
@ -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)
|
||||
})
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
|
@ -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'));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ import (
|
|||
// isValidFileType checks if a file type is supported
|
||||
func 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 true
|
||||
default:
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
}
|
||||
Loading…
Reference in New Issue