feat: 新增报告协作页,并强化 Deep Research 运行诊断与报告兜底
支持浏览器侧素材快照撰写、拒绝报告读时修复、Mermaid PNG 导出与 Word 导出加固。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
65d6b61d5d
commit
f109a95535
65 files changed
+10342
-245
No files matched your search
@@ -9,6 +9,8 @@ recipient's computer does not need the font installed.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
@@ -82,7 +84,23 @@ class TableBlock:
|
||||
rows: list[list[str]]
|
||||
|
||||
|
||||
Block = ParagraphBlock | TableBlock
|
||||
@dataclass(slots=True)
|
||||
class ImageBlock:
|
||||
alt: str
|
||||
data: bytes
|
||||
media_name: str
|
||||
width_px: int
|
||||
height_px: int
|
||||
|
||||
|
||||
Block = ParagraphBlock | TableBlock | ImageBlock
|
||||
|
||||
_EMU_PER_TWIP = 635
|
||||
_PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
_MAX_EMBEDDED_IMAGES = 40
|
||||
_MAX_EMBEDDED_IMAGE_BYTES = 8 * 1024 * 1024
|
||||
_EMBEDDED_IMAGE_ID = re.compile(r"^embedded:([A-Za-z0-9_-]{1,80})$")
|
||||
_DATA_PNG_URI = re.compile(r"^data:image/png;base64,([A-Za-z0-9+/=\s]+)$", re.IGNORECASE)
|
||||
|
||||
|
||||
def _safe_xml_text(value: str) -> str:
|
||||
@@ -260,11 +278,67 @@ def _extract_title(markdown: str, explicit_title: str | None) -> tuple[str | Non
|
||||
return (explicit_title or "").strip() or None, lines
|
||||
|
||||
|
||||
def _parse_markdown(markdown: str, explicit_title: str | None) -> tuple[str | None, list[Block]]:
|
||||
def _png_size(data: bytes) -> tuple[int, int]:
|
||||
if len(data) < 24 or data[:8] != _PNG_SIGNATURE:
|
||||
raise WordExportError("嵌入的流程图不是有效的 PNG 图片。")
|
||||
width, height = struct.unpack(">II", data[16:24])
|
||||
if width < 1 or height < 1 or width > 20_000 or height > 20_000:
|
||||
raise WordExportError("嵌入图片尺寸无效。")
|
||||
return width, height
|
||||
|
||||
|
||||
def _decode_png_base64(payload: str) -> bytes:
|
||||
try:
|
||||
data = base64.b64decode(re.sub(r"\s+", "", payload), validate=False)
|
||||
except (ValueError, binascii.Error) as exc:
|
||||
raise WordExportError("嵌入图片编码无效。") from exc
|
||||
if not data or len(data) > _MAX_EMBEDDED_IMAGE_BYTES:
|
||||
raise WordExportError("嵌入图片为空或超过 8 MB 限制。")
|
||||
_png_size(data)
|
||||
return data
|
||||
|
||||
|
||||
def _resolve_markdown_image(
|
||||
alt: str,
|
||||
target: str,
|
||||
embedded_images: dict[str, str],
|
||||
image_index: int,
|
||||
) -> Block:
|
||||
payload: str | None = None
|
||||
embedded = _EMBEDDED_IMAGE_ID.match(target.strip())
|
||||
if embedded:
|
||||
payload = embedded_images.get(embedded.group(1))
|
||||
else:
|
||||
data_uri = _DATA_PNG_URI.match(target.strip())
|
||||
if data_uri:
|
||||
payload = data_uri.group(1)
|
||||
if not payload:
|
||||
return ParagraphBlock("image", f"图片:{alt}|{target}")
|
||||
try:
|
||||
data = _decode_png_base64(payload)
|
||||
width, height = _png_size(data)
|
||||
except WordExportError:
|
||||
return ParagraphBlock("image", f"图片:{alt}|{target}")
|
||||
return ImageBlock(
|
||||
alt=alt,
|
||||
data=data,
|
||||
media_name=f"image{image_index}.png",
|
||||
width_px=width,
|
||||
height_px=height,
|
||||
)
|
||||
|
||||
|
||||
def _parse_markdown(
|
||||
markdown: str,
|
||||
explicit_title: str | None,
|
||||
embedded_images: dict[str, str] | None = None,
|
||||
) -> tuple[str | None, list[Block]]:
|
||||
title, lines = _extract_title(markdown, explicit_title)
|
||||
blocks: list[Block] = []
|
||||
paragraph_buffer: list[str] = []
|
||||
in_fence = False
|
||||
images = embedded_images or {}
|
||||
image_count = 0
|
||||
|
||||
def flush_paragraph() -> None:
|
||||
if paragraph_buffer:
|
||||
@@ -313,11 +387,20 @@ def _parse_markdown(markdown: str, explicit_title: str | None) -> tuple[str | No
|
||||
blocks.append(TableBlock(header, rows))
|
||||
continue
|
||||
|
||||
image = re.match(r'^\s*!\[([^\]]*)\]\(([^)\s]+)(?:\s+["\'][^"\']*["\'])?\)\s*$', raw)
|
||||
image = re.match(r'^\s*!\[([^\]]*)\]\(([^)]+)(?:\s+["\'][^"\']*["\'])?\)\s*$', raw)
|
||||
if image:
|
||||
flush_paragraph()
|
||||
alt = image.group(1).strip() or "未命名图片"
|
||||
blocks.append(ParagraphBlock("image", f"图片:{alt}|{image.group(2)}"))
|
||||
target = image.group(2).strip()
|
||||
if image_count >= _MAX_EMBEDDED_IMAGES and (
|
||||
_EMBEDDED_IMAGE_ID.match(target) or _DATA_PNG_URI.match(target)
|
||||
):
|
||||
blocks.append(ParagraphBlock("image", f"图片:{alt}|{target}"))
|
||||
else:
|
||||
resolved = _resolve_markdown_image(alt, target, images, image_count + 1)
|
||||
if isinstance(resolved, ImageBlock):
|
||||
image_count += 1
|
||||
blocks.append(resolved)
|
||||
index += 1
|
||||
continue
|
||||
|
||||
@@ -357,12 +440,20 @@ def _parse_markdown(markdown: str, explicit_title: str | None) -> tuple[str | No
|
||||
class _DocumentRelationships:
|
||||
def __init__(self) -> None:
|
||||
self._hyperlinks: list[tuple[str, str]] = []
|
||||
self._images: list[tuple[str, str]] = []
|
||||
self._drawing_id = 0
|
||||
|
||||
def add_hyperlink(self, target: str) -> str:
|
||||
relation_id = f"rId{100 + len(self._hyperlinks)}"
|
||||
self._hyperlinks.append((relation_id, target))
|
||||
return relation_id
|
||||
|
||||
def add_image(self, target: str) -> tuple[str, int]:
|
||||
self._drawing_id += 1
|
||||
relation_id = f"rId{200 + len(self._images)}"
|
||||
self._images.append((relation_id, target))
|
||||
return relation_id, self._drawing_id
|
||||
|
||||
def xml(self) -> str:
|
||||
fixed = [
|
||||
("rId1", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles", "styles.xml"),
|
||||
@@ -380,6 +471,10 @@ class _DocumentRelationships:
|
||||
f'<Relationship Id="{relation_id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="{_xml_attr(target)}" TargetMode="External"/>'
|
||||
for relation_id, target in self._hyperlinks
|
||||
)
|
||||
relationships += "".join(
|
||||
f'<Relationship Id="{relation_id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="{_xml_attr(target)}"/>'
|
||||
for relation_id, target in self._images
|
||||
)
|
||||
return f'{_XML_DECL}<Relationships xmlns="{_PACKAGE_REL_NS}">{relationships}</Relationships>'
|
||||
|
||||
|
||||
@@ -471,6 +566,45 @@ def _paragraph_xml(
|
||||
return f"<w:p><w:pPr>{properties}</w:pPr>{children}</w:p>"
|
||||
|
||||
|
||||
def _image_extent_emu(width_px: int, height_px: int) -> tuple[int, int]:
|
||||
max_width_emu = CONTENT_WIDTH_TWIPS * _EMU_PER_TWIP
|
||||
width_emu = max(1, int(width_px * 9525))
|
||||
height_emu = max(1, int(height_px * 9525))
|
||||
if width_emu > max_width_emu:
|
||||
scale = max_width_emu / width_emu
|
||||
width_emu = max_width_emu
|
||||
height_emu = max(1, int(height_emu * scale))
|
||||
return width_emu, height_emu
|
||||
|
||||
|
||||
def _embedded_image_xml(block: ImageBlock, relationships: _DocumentRelationships) -> str:
|
||||
relation_id, drawing_id = relationships.add_image(f"media/{block.media_name}")
|
||||
cx, cy = _image_extent_emu(block.width_px, block.height_px)
|
||||
name = _xml_attr(block.alt or block.media_name)
|
||||
drawing = (
|
||||
'<w:r><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0">'
|
||||
f'<wp:extent cx="{cx}" cy="{cy}"/>'
|
||||
f'<wp:docPr id="{drawing_id}" name="{name}"/>'
|
||||
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">'
|
||||
'<a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">'
|
||||
'<pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">'
|
||||
f'<pic:nvPicPr><pic:cNvPr id="0" name="{name}"/><pic:cNvPicPr/></pic:nvPicPr>'
|
||||
f'<pic:blipFill><a:blip r:embed="{relation_id}"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>'
|
||||
"<pic:spPr>"
|
||||
f'<a:xfrm><a:off x="0" y="0"/><a:ext cx="{cx}" cy="{cy}"/></a:xfrm>'
|
||||
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>'
|
||||
"</pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"
|
||||
)
|
||||
return (
|
||||
"<w:p><w:pPr>"
|
||||
'<w:pStyle w:val="ImageCaption"/>'
|
||||
'<w:jc w:val="center"/>'
|
||||
'<w:spacing w:before="160" w:after="160" w:line="240" w:lineRule="auto"/>'
|
||||
'<w:ind w:left="0" w:hanging="0" w:firstLineChars="0"/>'
|
||||
f"</w:pPr>{drawing}</w:p>"
|
||||
)
|
||||
|
||||
|
||||
def _image_paragraph_xml(text: str, relationships: _DocumentRelationships) -> str:
|
||||
label, _, target = text.partition("|")
|
||||
children = _run_xml(label)
|
||||
@@ -536,6 +670,9 @@ def _table_xml(block: TableBlock, relationships: _DocumentRelationships) -> str:
|
||||
def _blocks_xml(blocks: list[Block], relationships: _DocumentRelationships) -> str:
|
||||
output: list[str] = []
|
||||
for block in blocks:
|
||||
if isinstance(block, ImageBlock):
|
||||
output.append(_embedded_image_xml(block, relationships))
|
||||
continue
|
||||
if isinstance(block, TableBlock):
|
||||
output.append(_table_xml(block, relationships))
|
||||
continue
|
||||
@@ -897,7 +1034,8 @@ def _document_xml(title: str | None, blocks: list[Block], relationships: _Docume
|
||||
'<w:pgNumType w:start="1" w:fmt="decimal"/><w:cols w:space="720"/></w:sectPr>'
|
||||
)
|
||||
return (
|
||||
f'{_XML_DECL}<w:document xmlns:w="{_W_NS}" xmlns:r="{_R_NS}">'
|
||||
f'{_XML_DECL}<w:document xmlns:w="{_W_NS}" xmlns:r="{_R_NS}" '
|
||||
'xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing">'
|
||||
f"<w:body>{''.join(body)}{section}</w:body></w:document>"
|
||||
)
|
||||
|
||||
@@ -908,6 +1046,7 @@ def _content_types_xml() -> str:
|
||||
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
|
||||
'<Default Extension="xml" ContentType="application/xml"/>'
|
||||
'<Default Extension="odttf" ContentType="application/vnd.openxmlformats-officedocument.obfuscatedFont"/>'
|
||||
'<Default Extension="png" ContentType="image/png"/>'
|
||||
'<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>'
|
||||
'<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>'
|
||||
'<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>'
|
||||
@@ -952,18 +1091,29 @@ def _app_properties_xml() -> str:
|
||||
)
|
||||
|
||||
|
||||
def build_markdown_docx(markdown: str, title: str | None = None, *, font_path: Path | None = None) -> bytes:
|
||||
def build_markdown_docx(
|
||||
markdown: str,
|
||||
title: str | None = None,
|
||||
*,
|
||||
font_path: Path | None = None,
|
||||
embedded_images: dict[str, str] | None = None,
|
||||
) -> bytes:
|
||||
"""Build a formal DOCX and embed the validated server-side title font."""
|
||||
if not markdown or not markdown.strip():
|
||||
raise WordExportError("文档内容为空。")
|
||||
if len(markdown) > 2_000_000:
|
||||
raise WordExportError("文档内容超过 200 万字符,无法导出。")
|
||||
if embedded_images and len(embedded_images) > _MAX_EMBEDDED_IMAGES:
|
||||
raise WordExportError("嵌入图片数量超过限制。")
|
||||
|
||||
font = load_title_font(font_path)
|
||||
resolved_title, blocks = _parse_markdown(markdown, title)
|
||||
resolved_title, blocks = _parse_markdown(markdown, title, embedded_images)
|
||||
relationships = _DocumentRelationships()
|
||||
document_xml = _document_xml(resolved_title, blocks, relationships)
|
||||
font_key = str(uuid.uuid4()).upper()
|
||||
media_files = {
|
||||
f"word/media/{block.media_name}": block.data for block in blocks if isinstance(block, ImageBlock)
|
||||
}
|
||||
|
||||
output = io.BytesIO()
|
||||
with zipfile.ZipFile(output, mode="w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
|
||||
@@ -984,6 +1134,7 @@ def build_markdown_docx(markdown: str, title: str | None = None, *, font_path: P
|
||||
"word/footer1.xml": _footer_xml("left"),
|
||||
"word/footer2.xml": _footer_xml("right"),
|
||||
"word/fonts/font1.odttf": _obfuscate_font(font.data, font_key),
|
||||
**media_files,
|
||||
}
|
||||
for name, value in parts.items():
|
||||
archive.writestr(name, value.encode("utf-8") if isinstance(value, str) else value)
|
||||
|
||||
Reference in new issue
Block a user