Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(docreader): handle Header object when stripping mhtml header (#2902)

ResistanceTo77245f0f4b89
diff --git a/docreader/parser/mhtml_parser.py b/docreader/parser/mhtml_parser.py
index 08aac048c..8103d11f7 100644
--- a/docreader/parser/mhtml_parser.py
+++ b/docreader/parser/mhtml_parser.py
@@ -8,6 +8,7 @@ import email
import html
import logging
import os
+from email.header import decode_header
from urllib.parse import unquote, urljoin, urlparse
import uuid
from typing import Dict
@@ -28,6 +29,52 @@ _AD_DOMAINS = (
"pixel",
)
+_UNKNOWN_8BIT = frozenset({"unknown-8bit", "unknown"})
+
+
+def _header_str(value) -> str:
+ """Normalize a MIME header to str, recovering 8-bit UTF-8 bytes.
+
+ ``email.message_from_bytes`` uses compat32 by default. Browser-saved
+ ``.mhtml`` files often store raw UTF-8 in headers such as Content-Location.
+ Those values come back as ``email.header.Header`` with charset
+ ``unknown-8bit``: ``.strip()`` / ``.lower()`` raise AttributeError, and
+ ``str(Header)`` replaces the bytes with U+FFFD so image aliases no longer
+ match the HTML body.
+ """
+ if value is None:
+ return ""
+ if isinstance(value, bytes):
+ return value.decode("utf-8", errors="replace")
+ if isinstance(value, str):
+ try:
+ return value.encode("ascii", "surrogateescape").decode("utf-8")
+ except UnicodeError:
+ return value
+ try:
+ chunks = decode_header(value)
+ except (TypeError, ValueError, LookupError, UnicodeError):
+ return str(value)
+
+ parts: list[str] = []
+ for chunk, charset in chunks:
+ if isinstance(chunk, bytes):
+ encoding = (charset or "utf-8").lower()
+ if encoding in _UNKNOWN_8BIT:
+ encoding = "utf-8"
+ try:
+ parts.append(chunk.decode(encoding, errors="replace"))
+ except LookupError:
+ parts.append(chunk.decode("utf-8", errors="replace"))
+ elif chunk:
+ try:
+ parts.append(
+ chunk.encode("ascii", "surrogateescape").decode("utf-8")
+ )
+ except UnicodeError:
+ parts.append(chunk)
+ return "".join(parts)
+
class MHTMLParser(BaseParser):
"""Parser for MHTML web archives."""
@@ -49,7 +96,7 @@ class MHTMLParser(BaseParser):
for part in msg.walk():
content_type = part.get_content_type()
- location = part.get("Content-Location", "")
+ location = _header_str(part.get("Content-Location", ""))
if content_type == "text/html":
payload = part.get_payload(decode=True)
@@ -103,9 +150,10 @@ class MHTMLParser(BaseParser):
return {}
def is_ad(location: str) -> bool:
- if not location:
+ loc = _header_str(location)
+ if not loc:
return False
- loc = location.lower()
+ loc = loc.lower()
return any(ad in loc for ad in _AD_DOMAINS)
non_ad = sorted(
@@ -133,7 +181,7 @@ class MHTMLParser(BaseParser):
part.get("Content-ID", ""),
part.get("X-Attachment-Id", ""),
):
- raw = raw.strip()
+ raw = _header_str(raw).strip()
if not raw:
continue
values = {raw, html.unescape(raw), unquote(html.unescape(raw))}
@@ -163,7 +211,7 @@ class MHTMLParser(BaseParser):
) -> str:
"""Choose a stable image path when the MHTML part exposes a filename."""
ext = cls._image_extension(content_type)
- location = (part.get("Content-Location", "") or "").strip()
+ location = _header_str(part.get("Content-Location", "")).strip()
filename = cls._filename_from_content_location(location)
if not filename:
return f"images/{uuid.uuid4().hex}{ext}"
@@ -185,7 +233,7 @@ class MHTMLParser(BaseParser):
@staticmethod
def _filename_from_content_location(location: str) -> str:
- decoded = unquote(html.unescape(location.strip()))
+ decoded = unquote(html.unescape(_header_str(location).strip()))
if not decoded or decoded.lower().startswith("cid:"):
return ""
path = urlparse(decoded).path or decoded
diff --git a/docreader/tests/test_mhtml_parser.py b/docreader/tests/test_mhtml_parser.py
index afd70773f..1d98fa761 100644
--- a/docreader/tests/test_mhtml_parser.py
+++ b/docreader/tests/test_mhtml_parser.py
@@ -1,10 +1,12 @@
import base64
+import email
import json
import unittest
+from email.header import Header
from email.message import EmailMessage
from pathlib import Path
-from docreader.parser.mhtml_parser import MHTMLParser
+from docreader.parser.mhtml_parser import MHTMLParser, _header_str
from docreader.parser.registry import registry
REPO_ROOT = Path(__file__).resolve().parents[2]
@@ -84,6 +86,60 @@ def _mhtml_with_table_image_and_caption() -> bytes:
return root.as_bytes()
+def _mhtml_with_8bit_utf8_headers() -> bytes:
+ """Browser-style MHTML: raw UTF-8 bytes in MIME headers, not RFC 2047."""
+ html_loc = "https://example.com/测试页面.html".encode("utf-8")
+ ad_loc = "https://googleads.example/广告.html".encode("utf-8")
+ image_loc = "https://example.com/图片.png".encode("utf-8")
+ content_id = "<图片@local>".encode("utf-8")
+ attachment_id = "图片".encode("utf-8")
+ main_html = (
+ "<html><body><h1>中文主文</h1>"
+ '<img alt="绝对" src="https://example.com/图片.png">'
+ '<img alt="相对" src="图片.png">'
+ '<img alt="cid" src="cid:图片@local">'
+ "</body></html>"
+ ).encode("utf-8")
+ ad_html = "<html><body><h1>广告正文</h1></body></html>".encode("utf-8")
+ png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR"
+ return b"".join(
+ [
+ b"MIME-Version: 1.0\r\n",
+ b'Content-Type: multipart/related; boundary="----=_Next"\r\n',
+ b"\r\n",
+ b"------=_Next\r\n",
+ b'Content-Type: text/html; charset="utf-8"\r\n',
+ b"Content-Transfer-Encoding: 8bit\r\n",
+ b"Content-Location: ",
+ html_loc,
+ b"\r\n\r\n",
+ main_html,
+ b"\r\n",
+ b"------=_Next\r\n",
+ b'Content-Type: text/html; charset="utf-8"\r\n',
+ b"Content-Transfer-Encoding: 8bit\r\n",
+ b"Content-Location: ",
+ ad_loc,
+ b"\r\n\r\n",
+ ad_html,
+ b"\r\n",
+ b"------=_Next\r\n",
+ b"Content-Type: image/png\r\n",
+ b"Content-Transfer-Encoding: base64\r\n",
+ b"Content-Location: ",
+ image_loc,
+ b"\r\nContent-ID: ",
+ content_id,
+ b"\r\nX-Attachment-Id: ",
+ attachment_id,
+ b"\r\n\r\n",
+ base64.b64encode(png),
+ b"\r\n",
+ b"------=_Next--\r\n",
+ ]
+ )
+
+
class MHTMLParserTest(unittest.TestCase):
def test_parse_selects_main_html_and_filters_noise(self):
document = MHTMLParser(
@@ -231,6 +287,34 @@ class MHTMLParserTest(unittest.TestCase):
self.assertIn("* parent\n + child", document.content)
self.assertIn("alpha \nbeta", document.content)
+ def test_header_str_recovers_unknown_8bit_utf8(self):
+ raw = (
+ b"Content-Type: text/plain\r\n"
+ b"Content-Location: https://example.com/"
+ + "图片.png".encode("utf-8")
+ + b"\r\n\r\nbody\r\n"
+ )
+ value = email.message_from_bytes(raw).get("Content-Location")
+ self.assertIsInstance(value, Header)
+ self.assertEqual(_header_str(value), "https://example.com/图片.png")
+ self.assertEqual(_header_str(None), "")
+ self.assertEqual(_header_str("ascii-location"), "ascii-location")
+ self.assertEqual(_header_str("已是unicode"), "已是unicode")
+
+ def test_parse_8bit_utf8_headers_rewrites_images_without_crashing(self):
+ document = MHTMLParser(
+ file_name="article.mhtml", file_type="mhtml"
+ ).parse_into_text(_mhtml_with_8bit_utf8_headers())
+
+ self.assertIn("中文主文", document.content)
+ self.assertNotIn("广告正文", document.content)
+ self.assertIn("images/图片.png", document.images)
+ self.assertIn("images/图片.png", document.content)
+ self.assertEqual(document.content.count("images/图片.png"), 3)
+ self.assertNotIn("cid:图片@local", document.content)
+ self.assertNotIn("\ufffd", document.content)
+ self.assertTrue(all("\ufffd" not in key for key in document.images))
+
def test_registry_resolves_mhtml(self):
self.assertIs(registry.get_parser_class("", "mhtml"), MHTMLParser)