This commit is contained in:
Rumio
2025-08-14 14:09:13 +00:00
committed by GitHub
78 changed files with 3130 additions and 2222 deletions
-191
View File
@@ -3,12 +3,9 @@ from io import BytesIO
from pathlib import Path
import random
from nonebot_plugin_htmlrender import md_to_pic, template_to_pic
from PIL.ImageFont import FreeTypeFont
from pydantic import BaseModel
from zhenxun.configs.path_config import TEMPLATE_PATH
from ._build_image import BuildImage
@@ -286,191 +283,3 @@ class ImageTemplate:
width = max(width, w)
height += h
return width, height
class MarkdownTable:
def __init__(self, headers: list[str], rows: list[list[str]]):
self.headers = headers
self.rows = rows
def to_markdown(self) -> str:
"""将表格转换为Markdown格式"""
header_row = "| " + " | ".join(self.headers) + " |"
separator_row = "| " + " | ".join(["---"] * len(self.headers)) + " |"
data_rows = "\n".join(
"| " + " | ".join(map(str, row)) + " |" for row in self.rows
)
return f"{header_row}\n{separator_row}\n{data_rows}"
class Markdown:
def __init__(self, data: list[str] | None = None):
if data is None:
data = []
self._data = data
def text(self, text: str) -> "Markdown":
"""添加Markdown文本"""
self._data.append(text)
return self
def head(self, text: str, level: int = 1) -> "Markdown":
"""添加Markdown标题"""
if level < 1 or level > 6:
raise ValueError("标题级别必须在1到6之间")
self._data.append(f"{'#' * level} {text}")
return self
def image(self, content: str | Path, add_empty_line: bool = True) -> "Markdown":
"""添加Markdown图片
参数:
content: 图片内容,可以是url地址,图片路径或base64字符串.
add_empty_line: 默认添加换行.
返回:
Markdown: Markdown
"""
if isinstance(content, Path):
content = str(content.absolute())
if content.startswith("base64"):
content = f"data:image/png;base64,{content.split('base64://', 1)[-1]}"
self._data.append(f"![image]({content})")
if add_empty_line:
self._add_empty_line()
return self
def quote(self, text: str | list[str]) -> "Markdown":
"""添加Markdown引用文本
参数:
text: 引用文本内容,可以是字符串或字符串列表.
如果是列表,则每个元素都会被单独引用。
返回:
Markdown: Markdown
"""
if isinstance(text, str):
self._data.append(f"> {text}")
elif isinstance(text, list):
for t in text:
self._data.append(f"> {t}")
self._add_empty_line()
return self
def code(self, code: str, language: str = "python") -> "Markdown":
"""添加Markdown代码块"""
self._data.append(f"```{language}\n{code}\n```")
return self
def table(self, headers: list[str], rows: list[list[str]]) -> "Markdown":
"""添加Markdown表格"""
table = MarkdownTable(headers, rows)
self._data.append(table.to_markdown())
return self
def list(self, items: list[str | list[str]]) -> "Markdown":
"""添加Markdown列表"""
self._add_empty_line()
_text = "\n".join(
f"- {item}"
if isinstance(item, str)
else "\n".join(f"- {sub_item}" for sub_item in item)
for item in items
)
self._data.append(_text)
return self
def _add_empty_line(self):
"""添加空行"""
self._data.append("")
async def build(self, width: int = 800, css_path: Path | None = None) -> bytes:
"""构建Markdown文本"""
if css_path is not None:
return await md_to_pic(
md="\n".join(self._data), width=width, css_path=str(css_path.absolute())
)
return await md_to_pic(md="\n".join(self._data), width=width)
class Notebook:
def __init__(self, data: list[dict] | None = None):
self._data = data if data is not None else []
def text(self, text: str) -> "Notebook":
"""添加Notebook文本"""
self._data.append({"type": "paragraph", "text": text})
return self
def head(self, text: str, level: int = 1) -> "Notebook":
"""添加Notebook标题"""
if not 1 <= level <= 4:
raise ValueError("标题级别必须在1-4之间")
self._data.append({"type": "heading", "text": text, "level": level})
return self
def image(
self,
content: str | Path,
caption: str | None = None,
) -> "Notebook":
"""添加Notebook图片
参数:
content: 图片内容,可以是url地址,图片路径或base64字符串.
caption: 图片说明.
返回:
Notebook: Notebook
"""
if isinstance(content, Path):
content = str(content.absolute())
if content.startswith("base64"):
content = f"data:image/png;base64,{content.split('base64://', 1)[-1]}"
self._data.append({"type": "image", "src": content, "caption": caption})
return self
def quote(self, text: str | list[str]) -> "Notebook":
"""添加Notebook引用文本
参数:
text: 引用文本内容,可以是字符串或字符串列表.
如果是列表,则每个元素都会被单独引用。
返回:
Notebook: Notebook
"""
if isinstance(text, str):
self._data.append({"type": "blockquote", "text": text})
elif isinstance(text, list):
for t in text:
self._data.append({"type": "blockquote", "text": text})
return self
def code(self, code: str, language: str = "python") -> "Notebook":
"""添加Notebook代码块"""
self._data.append({"type": "code", "code": code, "language": language})
return self
def list(self, items: list[str], ordered: bool = False) -> "Notebook":
"""添加Notebook列表"""
self._data.append({"type": "list", "data": items, "ordered": ordered})
return self
def add_divider(self) -> None:
"""添加分隔线"""
self._data.append({"type": "divider"})
async def build(self) -> bytes:
"""构建Notebook"""
return await template_to_pic(
template_path=str((TEMPLATE_PATH / "notebook").absolute()),
template_name="main.html",
templates={"elements": self._data},
pages={
"viewport": {"width": 700, "height": 10},
"base_url": f"file://{TEMPLATE_PATH}",
},
wait=2,
)
+15
View File
@@ -1,3 +1,4 @@
import re
from typing import overload
from nonebot.adapters import Bot
@@ -120,3 +121,17 @@ class SqlUtils:
if not_null:
sql += " NOT NULL"
return sql
def format_usage_for_markdown(text: str) -> str:
"""
智能地将Python多行字符串转换为适合Markdown渲染的格式。
- 将单个换行符替换为Markdown的硬换行(行尾加两个空格)。
- 保留两个或更多的连续换行符,使其成为Markdown的段落分隔。
"""
if not text:
return ""
text = re.sub(r"\n{2,}", "<<PARAGRAPH_BREAK>>", text)
text = text.replace("\n", " \n")
text = text.replace("<<PARAGRAPH_BREAK>>", "\n\n")
return text
+17 -18
View File
@@ -1,32 +1,31 @@
import os
from pathlib import Path
import random
from nonebot_plugin_htmlrender import template_to_pic
from zhenxun.configs.path_config import TEMPLATE_PATH
from zhenxun.services import renderer_service
from zhenxun.utils._build_image import BuildImage
from .models import Barh
BACKGROUND_PATH = TEMPLATE_PATH / "bar_chart" / "background"
BACKGROUND_PATH = (
Path() / "resources" / "themes" / "default" / "assets" / "bar_chart" / "background"
)
class ChartUtils:
@classmethod
async def barh(cls, data: Barh) -> BuildImage:
"""横向统计图"""
to_json = data.to_dict()
to_json["background_image"] = (
f"./background/{random.choice(os.listdir(BACKGROUND_PATH))}"
background_image_name = random.choice(os.listdir(BACKGROUND_PATH))
render_data = {
"title": data.title,
"category_data": data.category_data,
"data": data.data,
"background_image": background_image_name,
"direction": "horizontal",
}
image_bytes = await renderer_service.render(
"components/charts/bar_chart", data=render_data
)
pic = await template_to_pic(
template_path=str((TEMPLATE_PATH / "bar_chart").absolute()),
template_name="main.html",
templates={"data": to_json},
pages={
"viewport": {"width": 1000, "height": 1000},
"base_url": f"file://{TEMPLATE_PATH}",
},
wait=2,
)
return BuildImage.open(pic)
return BuildImage.open(image_bytes)
+8
View File
@@ -98,3 +98,11 @@ class AllURIsFailedError(Exception):
for url, exc in zip(self.urls, self.exceptions)
)
return f"All {len(self.urls)} URIs failed:\n{exc_info}"
class RenderingError(Exception):
"""
在渲染服务无法生成图片时抛出。
"""
pass
+20 -42
View File
@@ -1,31 +1,26 @@
import asyncio
import os
from pathlib import Path
from typing import ClassVar
import aiofiles
import nonebot
from nonebot.compat import model_dump
from nonebot_plugin_htmlrender import template_to_pic
from pydantic import BaseModel
from zhenxun.configs.config import BotConfig, Config
from zhenxun.configs.path_config import DATA_PATH, TEMPLATE_PATH
from zhenxun.configs.path_config import DATA_PATH
from zhenxun.configs.utils.models import PluginExtraData
from zhenxun.models.statistics import Statistics
from zhenxun.models.user_console import UserConsole
from zhenxun.services import renderer_service
from zhenxun.services.log import logger
from zhenxun.utils._build_image import BuildImage
from zhenxun.utils.platform import PlatformUtils
from zhenxun.utils.pydantic_compat import model_dump
DIR_PATH = DATA_PATH / "bot_profile"
PROFILE_PATH = DIR_PATH / "profile"
PROFILE_PATH.mkdir(parents=True, exist_ok=True)
PROFILE_IMAGE_PATH = DIR_PATH / "image"
PROFILE_IMAGE_PATH.mkdir(parents=True, exist_ok=True)
Config.add_plugin_config(
"bot_profile",
@@ -66,17 +61,12 @@ class BotProfileManager:
@classmethod
def clear_profile_image(cls, bot_id: str | None = None):
"""清除BOT自我介绍图片"""
"""清除BOT自我介绍的内存缓存"""
if bot_id:
file_path = PROFILE_IMAGE_PATH / f"{bot_id}.png"
if file_path.exists():
file_path.unlink()
if bot_id in cls._bot_data:
del cls._bot_data[bot_id]
else:
for f in os.listdir(PROFILE_IMAGE_PATH):
_f = PROFILE_IMAGE_PATH / f
if _f.is_file():
_f.unlink()
cls._bot_data.clear()
cls._bot_data.clear()
@classmethod
async def _read_profile(cls, bot_id: str):
@@ -147,11 +137,8 @@ class BotProfileManager:
@classmethod
async def build_bot_profile_image(
cls, bot_id: str, tags: list[dict[str, str]] | None = None
) -> Path | None:
) -> bytes | None:
"""构建BOT自我介绍图片"""
file_path = PROFILE_IMAGE_PATH / f"{bot_id}.png"
if file_path.exists():
return file_path
profile, service_count, call_count = await asyncio.gather(
cls.get_bot_profile(bot_id),
UserConsole.get_new_uid(),
@@ -164,28 +151,19 @@ class BotProfileManager:
{"text": f"服务人数: {service_count}", "color": "#5e92e0"},
{"text": f"调用次数: {call_count}", "color": "#31e074"},
]
image_bytes = await template_to_pic(
template_path=str((TEMPLATE_PATH / "bot_profile").absolute()),
template_name="main.html",
templates={
"avatar": str(profile.avatar.absolute()) if profile.avatar else None,
"bot_name": profile.name,
"bot_description": profile.introduction,
"service_count": service_count,
"call_count": call_count,
"plugin_list": cls.get_plugin_profile(),
"tags": tags,
"title": f"{BotConfig.self_nickname}简介",
},
pages={
"viewport": {"width": 1077, "height": 1000},
"base_url": f"file://{TEMPLATE_PATH}",
},
wait=2,
profile_data = {
"avatar": profile.avatar.absolute().as_uri() if profile.avatar else None,
"bot_name": profile.name,
"bot_description": profile.introduction,
"service_count": service_count,
"call_count": call_count,
"plugin_list": cls.get_plugin_profile(),
"tags": tags,
"title": f"{BotConfig.self_nickname}简介",
}
return await renderer_service.render(
"pages/builtin/bot_profile", data=profile_data
)
image = BuildImage.open(image_bytes)
await image.save(file_path)
return file_path
BotProfileManager.clear_profile_image()