返回 Social Auto Upload
article_content.py
根目录 / uploader / dayu_uploader / article_content.py
1 """大鱼号正文的能力与素材限制;文件读取和渲染由共用文章模块负责。"""
2 from __future__ import annotations
3
4 from pathlib import Path
5
6 import cv2
7 import numpy as np
8
9 from utils.article_content import ArticleDocument
10 from utils.article_render import load_article
11
12
13 DAYU_ARTICLE_TAGS = {"section", "div", "span", "figure", "p", "br", "h1", "h2", "h3", "h4", "h5", "h6", "strong", "blockquote", "ol", "ul", "li", "hr"}
14
15
16 def load_dayu_article(content_file: str | Path, theme: str | None = None) -> ArticleDocument:
17 """共用主题渲染,保留原稿样式供大鱼号兼容转换,并在上传前校验平台能力。"""
18 path = Path(content_file).expanduser().resolve()
19 if path.suffix.lower() not in {".md", ".markdown"} and theme is not None:
20 raise ValueError("--theme 仅适用于 Markdown")
21 document = load_article(path, theme)
22 unsupported = set(document.tags) - DAYU_ARTICLE_TAGS
23 if unsupported:
24 raise ValueError(f"大鱼号当前未支持这些格式: {', '.join(sorted(unsupported))};请调整原稿")
25 # figure 在导入时适配为 div;图片数量与位置仍严格校验,布局容器不计作必须保留的语义格式。
26 document.manifest["formats"].pop("figure", None)
27 text = "".join(document.text).strip()
28 if len(text) > 20000:
29 raise ValueError(f"大鱼号正文最多 20000 字,当前 {len(text)} 字")
30 for image in set(document.images):
31 validate_dayu_article_image(image)
32 return document
33
34
35 def validate_dayu_article_image(image: str | Path) -> Path:
36 """图文正文和封面共用页面观察到的单张 5M 限制,并拒绝无法解码的图片。"""
37 path = Path(image).expanduser().resolve()
38 if not path.is_file():
39 raise FileNotFoundError(f"图片不存在: {path}")
40 size = path.stat().st_size
41 if not size:
42 raise ValueError(f"图片文件为空: {path}")
43 if size > 5 * 1024 ** 2:
44 raise ValueError(f"图片不能超过 5 MB: {path}")
45 # Windows 的 imread 不能可靠打开中文路径;由 pathlib 读字节后解码,不改写用户文件。
46 if cv2.imdecode(np.frombuffer(path.read_bytes(), dtype=np.uint8), cv2.IMREAD_UNCHANGED) is None:
47 raise ValueError(f"图片无法解码: {path}")
48 return path
49
49 lines PYTHON