feat: complete AstrBot chat workflow commands
这个提交存在于:
父节点
aa94d7c2ce
当前提交
419ada179c
共有 45 个文件被更改,包括 2400 次插入 和 119 次删除
27
README.md
27
README.md
|
|
@ -74,6 +74,33 @@ generation_provider_api_key_env_var = IMAGESTUDIO_PROVIDER_API_KEY
|
|||
- 登记、确认和校验 OpenAI 兼容模型能力档案;当前 discovery endpoint 是安全的元数据检查,不会主动向任意地址发起探测请求。
|
||||
- 使用 SQLite 零配置运行,或按需切换 PostgreSQL。
|
||||
|
||||
## 聊天命令
|
||||
|
||||
插件提供 `/影棚` 和短别名 `/yp`,两套命令行为一致。聊天权限在设置页“聊天权限”中配置。
|
||||
|
||||
```text
|
||||
/yp 帮助
|
||||
/yp 状态
|
||||
/yp 单图 <提示词> [--角色 名称] [--模型 路由] [--尺寸 1K|2K|4K] [--数量 1-4]
|
||||
/yp 快速角色 <角色名和描述>
|
||||
/yp 确认
|
||||
/yp 工作流 <角色名或ID>
|
||||
/yp 节点 <workflow_id>
|
||||
/yp 生成 <node_id>
|
||||
/yp 下一步 <workflow_id>
|
||||
/yp 候选图 <node_id>
|
||||
/yp 选择 <序号>
|
||||
/yp 审核 <node_id|workflow_id>
|
||||
/yp 高清 <image_id> 2K|4K
|
||||
/yp 素材导入 <分类名称或ID> (命令消息需附带图片)
|
||||
/yp 加入衣橱 <material_id> <角色名或ID> <衣橱分类>
|
||||
/yp 任务 [task_id]
|
||||
/yp 取消 <task_id>
|
||||
/yp 重试 <task_id>
|
||||
```
|
||||
|
||||
快速角色和详细角色工作流要求群聊、用户白名单同时命中;单图允许任意一个白名单命中。聊天生成还受用户/群聊并发、每日额度和 2K/4K 开关约束。单图在后台线程执行,命令会立即返回请求 ID,完成后通过 AstrBot 统一消息来源主动发送图片。
|
||||
|
||||
## 持久化数据
|
||||
|
||||
运行数据统一放在 AstrBot 数据目录中:
|
||||
|
|
|
|||
|
|
@ -91,6 +91,14 @@
|
|||
"model_fullbody_generation": {"description":"全身角色图使用的生图路由。","type":"string","default":""},
|
||||
"model_sheet_generation": {"description":"设定图与姿势图使用的生图路由。","type":"string","default":""},
|
||||
"model_hires_fix": {"description":"高清修复使用的生图路由。","type":"string","default":""},
|
||||
"chat_group_allowlist": {"description":"允许使用 ImageStudio 聊天工作流的群聊 ID 白名单。","type":"list","default":[]},
|
||||
"chat_user_allowlist": {"description":"允许使用 ImageStudio 聊天功能的用户 ID 白名单。","type":"list","default":[]},
|
||||
"chat_user_concurrency_limit": {"description":"单个聊天用户同时运行的生成任务上限。","type":"int","default":2},
|
||||
"chat_group_concurrency_limit": {"description":"单个群聊同时运行的生成任务上限。","type":"int","default":5},
|
||||
"chat_daily_user_generation_limit": {"description":"单个用户每日聊天生成次数上限。","type":"int","default":30},
|
||||
"chat_daily_group_generation_limit": {"description":"单个群聊每日聊天生成次数上限。","type":"int","default":100},
|
||||
"chat_allow_2k": {"description":"允许聊天命令申请 2K 图片。","type":"bool","default":true},
|
||||
"chat_allow_4k": {"description":"允许聊天命令申请 4K 图片。","type":"bool","default":false},
|
||||
"enable_private_companion_integration": {
|
||||
"description": "允许 astrbot_plugin_private_companion 调用 ImageStudio 的穿搭和素材集成接口。",
|
||||
"type": "bool",
|
||||
|
|
|
|||
|
|
@ -0,0 +1,84 @@
|
|||
"""Render compact PNG cards for AstrBot chat responses."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
|
||||
CARD_DIR = Path(__file__).resolve().parent.parent / "data" / "chat_cards"
|
||||
|
||||
|
||||
def render_help_card(lines: Iterable[str]) -> Path:
|
||||
return _render_card(
|
||||
key="help-v1",
|
||||
eyebrow="IMAGESTUDIO COMMANDS",
|
||||
title="影棚命令帮助",
|
||||
subtitle="使用 /影棚 或 /yp 调用",
|
||||
lines=list(lines),
|
||||
accent=(40, 169, 151),
|
||||
)
|
||||
|
||||
|
||||
def render_status_card(*, state: str, version: str, database: str, api: str) -> Path:
|
||||
return _render_card(
|
||||
key=f"status-{state}-{version}-{database}-{api}",
|
||||
eyebrow="IMAGESTUDIO STATUS",
|
||||
title=f"运行状态 · {state}",
|
||||
subtitle=f"版本 {version}",
|
||||
lines=[f"数据库 {database}", f"接口 {api}", "聊天命令框架已加载"],
|
||||
accent=(40, 169, 151) if state == "正常" else (224, 157, 55),
|
||||
)
|
||||
|
||||
|
||||
def render_profile_card(*, name: str, base: str, appearance: str, style: str) -> Path:
|
||||
return _render_card(
|
||||
key=f"profile-{name}-{base}-{appearance}-{style}", eyebrow="IMAGESTUDIO QUICK PROFILE",
|
||||
title=name or "快速角色草稿", subtitle="确认后将创建角色档案与工作流",
|
||||
lines=[f"基础 {base or '—'}", f"外观 {appearance or '—'}", f"风格 {style or '—'}", "回复:确认 / 修改 / 放弃"],
|
||||
accent=(112, 91, 220),
|
||||
)
|
||||
|
||||
|
||||
def _render_card(*, key: str, eyebrow: str, title: str, subtitle: str, lines: list[str], accent: tuple[int, int, int]) -> Path:
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
CARD_DIR.mkdir(parents=True, exist_ok=True)
|
||||
target = CARD_DIR / f"{hashlib.sha256(key.encode('utf-8')).hexdigest()[:16]}.png"
|
||||
if target.exists():
|
||||
return target
|
||||
width = 1000
|
||||
height = 300 + max(len(lines), 1) * 66
|
||||
image = Image.new("RGB", (width, height), (242, 247, 249))
|
||||
draw = ImageDraw.Draw(image)
|
||||
draw.rounded_rectangle((28, 28, width - 28, height - 28), radius=34, fill=(255, 255, 255), outline=(211, 224, 228), width=2)
|
||||
draw.rounded_rectangle((28, 28, 52, height - 28), radius=12, fill=accent)
|
||||
fonts = _fonts(ImageFont)
|
||||
draw.text((86, 70), eyebrow, font=fonts["small"], fill=accent)
|
||||
draw.text((86, 112), title, font=fonts["title"], fill=(24, 36, 44))
|
||||
draw.text((88, 180), subtitle, font=fonts["body"], fill=(101, 118, 128))
|
||||
y = 245
|
||||
for index, line in enumerate(lines):
|
||||
draw.rounded_rectangle((82, y, width - 82, y + 48), radius=12, fill=(244, 249, 250) if index % 2 == 0 else (248, 250, 252))
|
||||
draw.text((102, y + 9), line, font=fonts["body"], fill=(43, 59, 68))
|
||||
y += 66
|
||||
image.save(target, format="PNG", optimize=True)
|
||||
return target
|
||||
|
||||
|
||||
def _fonts(image_font):
|
||||
candidates = [
|
||||
Path("C:/Windows/Fonts/msyh.ttc"),
|
||||
Path("C:/Windows/Fonts/simhei.ttf"),
|
||||
Path("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"),
|
||||
Path("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"),
|
||||
]
|
||||
path = next((item for item in candidates if item.exists()), None)
|
||||
if path is None:
|
||||
return {"small": image_font.load_default(), "title": image_font.load_default(), "body": image_font.load_default()}
|
||||
return {
|
||||
"small": image_font.truetype(str(path), 20),
|
||||
"title": image_font.truetype(str(path), 42),
|
||||
"body": image_font.truetype(str(path), 25),
|
||||
}
|
||||
102
adapters/astrbot_command_adapter.py
普通文件
102
adapters/astrbot_command_adapter.py
普通文件
|
|
@ -0,0 +1,102 @@
|
|||
"""Pure helpers for the AstrBot chat command surface."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from core.chat_access_policy import chat_action_allowed
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ChatCommandContext:
|
||||
user_id: str
|
||||
group_id: str | None
|
||||
message_origin: str
|
||||
platform: str
|
||||
message_id: str
|
||||
|
||||
|
||||
def command_context_from_event(event: Any) -> ChatCommandContext:
|
||||
return ChatCommandContext(
|
||||
user_id=_event_value(event, "get_sender_id", "sender_id", "user_id"),
|
||||
group_id=_optional_event_value(event, "get_group_id", "group_id"),
|
||||
message_origin=_event_value(event, "unified_msg_origin", "message_origin"),
|
||||
platform=_event_value(event, "get_platform_name", "platform_name", fallback="unknown"),
|
||||
message_id=_event_value(event, "message_id", "get_message_id"),
|
||||
)
|
||||
|
||||
|
||||
def command_allowed(config: dict[str, Any], action: str, context: ChatCommandContext) -> bool:
|
||||
return chat_action_allowed(
|
||||
config,
|
||||
action,
|
||||
group_id=context.group_id,
|
||||
user_id=context.user_id,
|
||||
)
|
||||
|
||||
|
||||
def message_text_from_event(event: Any) -> str:
|
||||
for name in ("message_str", "get_message_str", "raw_message"):
|
||||
value = getattr(event, name, None)
|
||||
if callable(value):
|
||||
try:
|
||||
value = value()
|
||||
except (TypeError, AttributeError):
|
||||
continue
|
||||
text = str(value or "").strip()
|
||||
if text:
|
||||
return text
|
||||
return ""
|
||||
|
||||
|
||||
def help_text() -> str:
|
||||
return """🎨 ImageStudio 命令
|
||||
|
||||
/影棚 帮助 或 /yp 帮助
|
||||
/影棚 状态 或 /yp 状态
|
||||
/影棚 快速角色 <角色描述>
|
||||
/影棚 工作流 <角色名或角色 ID>
|
||||
/影棚 单图 <提示词>
|
||||
|
||||
权限规则:
|
||||
• 快速角色、角色工作流:群聊和用户白名单必须同时命中
|
||||
• 单图:群聊或用户任一白名单命中即可
|
||||
|
||||
当前为命令框架版本,后续将逐步接入角色选择、节点生成、选图和任务回执。"""
|
||||
|
||||
|
||||
def access_denied_text(action: str, context: ChatCommandContext) -> str:
|
||||
scope = f"群聊 {context.group_id}" if context.group_id else "私聊"
|
||||
return f"⛔ 当前{scope}或用户 {context.user_id or '未知'}不满足「{action}」的白名单规则。"
|
||||
|
||||
|
||||
def accepted_text(action: str, argument: str, context: ChatCommandContext) -> str:
|
||||
value = argument.strip() or "未提供"
|
||||
return (
|
||||
f"✅ ImageStudio 已接收「{action}」命令框架请求\n\n"
|
||||
f"输入:{value}\n"
|
||||
f"平台:{context.platform}\n"
|
||||
f"用户:{context.user_id or '未知'}\n"
|
||||
f"群聊:{context.group_id or '私聊'}\n\n"
|
||||
"当前阶段已完成命令注册、参数接收与白名单校验;业务执行器将在下一阶段接入。"
|
||||
)
|
||||
|
||||
|
||||
def _event_value(event: Any, *names: str, fallback: str = "") -> str:
|
||||
for name in names:
|
||||
value = getattr(event, name, None)
|
||||
if callable(value):
|
||||
try:
|
||||
value = value()
|
||||
except (TypeError, AttributeError):
|
||||
continue
|
||||
text = str(value or "").strip()
|
||||
if text:
|
||||
return text
|
||||
return fallback
|
||||
|
||||
|
||||
def _optional_event_value(event: Any, *names: str) -> str | None:
|
||||
value = _event_value(event, *names)
|
||||
return value or None
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
"""Parsing for ImageStudio AstrBot command arguments."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
|
||||
from backend.dto.chat_command_dto import ChatCommandParseError, SIZE_ALIASES, SingleImageCommand
|
||||
|
||||
|
||||
OPTION_NAMES = {
|
||||
"--角色": "profile_ref", "--profile": "profile_ref",
|
||||
"--模型": "model_route", "--model": "model_route",
|
||||
"--尺寸": "size", "--size": "size",
|
||||
"--数量": "count", "--count": "count",
|
||||
"--负面": "negative_prompt", "--negative": "negative_prompt",
|
||||
}
|
||||
|
||||
|
||||
def parse_single_image_command(raw: str) -> SingleImageCommand:
|
||||
try:
|
||||
tokens = shlex.split(str(raw or ""), posix=True)
|
||||
except ValueError as exc:
|
||||
raise ChatCommandParseError(f"参数引号不完整:{exc}") from exc
|
||||
prompt_parts: list[str] = []
|
||||
values: dict[str, str] = {}
|
||||
index = 0
|
||||
while index < len(tokens):
|
||||
token = tokens[index]
|
||||
key = OPTION_NAMES.get(token.lower())
|
||||
if key:
|
||||
if index + 1 >= len(tokens) or tokens[index + 1].startswith("--"):
|
||||
raise ChatCommandParseError(f"{token} 缺少参数值")
|
||||
values[key] = tokens[index + 1]
|
||||
index += 2
|
||||
continue
|
||||
if token.startswith("--"):
|
||||
raise ChatCommandParseError(f"未知参数:{token}")
|
||||
prompt_parts.append(token)
|
||||
index += 1
|
||||
prompt = " ".join(prompt_parts).strip()
|
||||
if not prompt:
|
||||
raise ChatCommandParseError("请提供生图提示词")
|
||||
size_text = values.get("size", "1K").lower()
|
||||
size = SIZE_ALIASES.get(size_text, values.get("size", "1920x1080"))
|
||||
if size not in SIZE_ALIASES.values():
|
||||
raise ChatCommandParseError("尺寸仅支持 1K、2K、4K")
|
||||
try:
|
||||
count = int(values.get("count", "1"))
|
||||
except ValueError as exc:
|
||||
raise ChatCommandParseError("数量必须是整数") from exc
|
||||
if count < 1 or count > 4:
|
||||
raise ChatCommandParseError("数量必须在 1 到 4 之间")
|
||||
return SingleImageCommand(
|
||||
prompt=prompt,
|
||||
profile_ref=values.get("profile_ref"),
|
||||
model_route=values.get("model_route"),
|
||||
size=size,
|
||||
count=count,
|
||||
negative_prompt=values.get("negative_prompt"),
|
||||
)
|
||||
|
||||
|
||||
def single_image_usage(error: str) -> str:
|
||||
return (
|
||||
f"❌ {error}\n\n"
|
||||
"示例:\n"
|
||||
"/yp 单图 雨夜街道中的少女 --角色 米卡 --尺寸 1K --数量 1\n\n"
|
||||
"可用参数:--角色、--模型、--尺寸、--数量、--负面"
|
||||
)
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
"""Extract image references from AstrBot message components."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def image_references_from_event(event: Any) -> list[str]:
|
||||
message_obj = getattr(event, "message_obj", None)
|
||||
chain = getattr(message_obj, "message", None) or getattr(event, "message_chain", None) or []
|
||||
references: list[str] = []
|
||||
for component in chain if isinstance(chain, (list, tuple)) else []:
|
||||
if "image" not in component.__class__.__name__.lower():
|
||||
continue
|
||||
for name in ("url", "file", "path", "image_url"):
|
||||
text = str(getattr(component, name, None) or "").strip()
|
||||
if text and text not in references:
|
||||
references.append(text)
|
||||
break
|
||||
return references
|
||||
32
backend/dto/chat_command_dto.py
普通文件
32
backend/dto/chat_command_dto.py
普通文件
|
|
@ -0,0 +1,32 @@
|
|||
"""DTOs for platform-neutral ImageStudio chat commands."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
SIZE_ALIASES = {"1k": "1920x1080", "2k": "2560x1440", "4k": "3840x2160"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SingleImageCommand:
|
||||
prompt: str
|
||||
profile_ref: str | None = None
|
||||
model_route: str | None = None
|
||||
size: str = "1920x1080"
|
||||
count: int = 1
|
||||
negative_prompt: str | None = None
|
||||
|
||||
def to_payload(self) -> dict:
|
||||
return {
|
||||
"prompt": self.prompt,
|
||||
"profile_ref": self.profile_ref,
|
||||
"model_route": self.model_route,
|
||||
"size": self.size,
|
||||
"count": self.count,
|
||||
"negative_prompt": self.negative_prompt,
|
||||
}
|
||||
|
||||
|
||||
class ChatCommandParseError(ValueError):
|
||||
pass
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
"""Persistent chat command quota checks and audit records."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from adapters.astrbot_command_adapter import ChatCommandContext
|
||||
from core.audit_service import AuditService
|
||||
from core.identity import RequestContext
|
||||
from database.db_helper import Database, load_database_settings
|
||||
|
||||
|
||||
class ChatCommandGuardService:
|
||||
def __init__(self, database: Database | None = None):
|
||||
self.database = database or Database(load_database_settings())
|
||||
self.audit = AuditService(self.database)
|
||||
|
||||
def check_generation(self, config: dict[str, Any], chat: ChatCommandContext, *, size: str, active_jobs: list[dict[str, Any]]) -> None:
|
||||
access = config.get("chat_access") if isinstance(config.get("chat_access"), dict) else {}
|
||||
user_limit = _positive_int(access.get("user_concurrency_limit"), 2)
|
||||
group_limit = _positive_int(access.get("group_concurrency_limit"), 5)
|
||||
daily_limit = _positive_int(access.get("daily_user_generation_limit"), 30)
|
||||
daily_group_limit = _positive_int(access.get("daily_group_generation_limit"), 100)
|
||||
if size == "3840x2160" and access.get("allow_4k") is not True:
|
||||
raise ValueError("聊天命令尚未授权 4K 生成")
|
||||
if size == "2560x1440" and access.get("allow_2k", True) is not True:
|
||||
raise ValueError("聊天命令尚未授权 2K 生成")
|
||||
user_active = sum(1 for item in active_jobs if _request_metadata(item).get("user_id") == chat.user_id)
|
||||
group_active = sum(1 for item in active_jobs if chat.group_id and _request_metadata(item).get("group_id") == chat.group_id)
|
||||
if user_active >= user_limit:
|
||||
raise ValueError(f"用户并发任务已达到上限 {user_limit}")
|
||||
if chat.group_id and group_active >= group_limit:
|
||||
raise ValueError(f"群聊并发任务已达到上限 {group_limit}")
|
||||
if self._daily_count(chat.user_id) >= daily_limit:
|
||||
raise ValueError(f"用户今日生成次数已达到上限 {daily_limit}")
|
||||
if chat.group_id and self._daily_group_count(chat.group_id) >= daily_group_limit:
|
||||
raise ValueError(f"群聊今日生成次数已达到上限 {daily_group_limit}")
|
||||
|
||||
def record(self, chat: ChatCommandContext, action: str, *, target_id: str | None = None, allowed: bool = True, details: dict[str, Any] | None = None) -> None:
|
||||
ctx = RequestContext.from_astrbot(username=chat.user_id, user_id=chat.user_id, source=f"astrbot_chat:{chat.platform}", permissions=set())
|
||||
self.audit.record(
|
||||
ctx=ctx,
|
||||
action="chat_command_allowed" if allowed else "chat_command_denied",
|
||||
target_type="chat_command",
|
||||
target_id=target_id,
|
||||
metadata={
|
||||
"command": action,
|
||||
"platform": chat.platform,
|
||||
"message_origin": chat.message_origin,
|
||||
"group_id": chat.group_id,
|
||||
**(details or {}),
|
||||
},
|
||||
)
|
||||
|
||||
def _daily_count(self, user_id: str) -> int:
|
||||
placeholder = self.database._placeholder
|
||||
start = datetime.now(timezone.utc).date().isoformat()
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
row = conn.execute(
|
||||
f"SELECT COUNT(*) AS count FROM audit_logs WHERE actor_id = {placeholder} AND action = {placeholder} AND created_at >= {placeholder}",
|
||||
(user_id, "chat_command_allowed", start),
|
||||
).fetchone()
|
||||
return int(row["count"] if row else 0)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def _daily_group_count(self, group_id: str) -> int:
|
||||
placeholder = self.database._placeholder
|
||||
start = datetime.now(timezone.utc).date().isoformat()
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
rows = conn.execute(
|
||||
f"SELECT metadata_json FROM audit_logs WHERE action = {placeholder} AND created_at >= {placeholder}",
|
||||
("chat_command_allowed", start),
|
||||
).fetchall()
|
||||
count = 0
|
||||
for row in rows:
|
||||
try:
|
||||
metadata = json.loads(row["metadata_json"] or "{}")
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if str(metadata.get("group_id") or "") == group_id:
|
||||
count += 1
|
||||
return count
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _request_metadata(job: dict[str, Any]) -> dict[str, Any]:
|
||||
request = job.get("request") if isinstance(job.get("request"), dict) else {}
|
||||
return request.get("metadata") if isinstance(request.get("metadata"), dict) else {}
|
||||
|
||||
|
||||
def _positive_int(value: Any, default: int) -> int:
|
||||
try:
|
||||
return max(int(value), 1)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
"""Safely persist chat-platform image references into ImageStudio storage."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from core.remote_fetch import read_http_response_limited
|
||||
from core.storage import VfsStorage
|
||||
|
||||
|
||||
MAX_CHAT_IMAGE_BYTES = 20 * 1024 * 1024
|
||||
|
||||
|
||||
class ChatMediaImportService:
|
||||
def __init__(self, storage: VfsStorage | None = None):
|
||||
self.storage = storage or VfsStorage()
|
||||
|
||||
def import_image(self, reference: str) -> tuple[str, str, int]:
|
||||
text = str(reference or "").strip()
|
||||
if text.startswith("storage://"):
|
||||
path = self.storage.ensure_file(text)
|
||||
return text, path.name, path.stat().st_size
|
||||
if text.startswith("data:image/"):
|
||||
header, encoded = text.split(",", 1)
|
||||
body = base64.b64decode(encoded, validate=True)
|
||||
extension = header.split("/", 1)[1].split(";", 1)[0].replace("jpeg", "jpg")
|
||||
elif text.startswith(("http://", "https://")):
|
||||
body = read_http_response_limited(text, timeout_seconds=30, max_bytes=MAX_CHAT_IMAGE_BYTES)
|
||||
extension = Path(urlsplit(text).path).suffix.lstrip(".").lower() or "jpg"
|
||||
else:
|
||||
source = Path(text).expanduser().resolve()
|
||||
body = source.read_bytes()
|
||||
extension = source.suffix.lstrip(".").lower() or "jpg"
|
||||
if not body or len(body) > MAX_CHAT_IMAGE_BYTES:
|
||||
raise ValueError("聊天图片为空或超过 20MB")
|
||||
if extension not in {"png", "jpg", "jpeg", "webp", "gif"}:
|
||||
extension = "jpg"
|
||||
digest = hashlib.sha256(body).hexdigest()
|
||||
uri = f"storage://materials/chat/{digest[:2]}/{digest}.{extension}"
|
||||
target = self.storage.resolve_uri(uri)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not target.exists():
|
||||
target.write_bytes(body)
|
||||
return uri, target.name, len(body)
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
"""Bounded, reload-safe chat sessions for confirmations and selection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from threading import RLock
|
||||
from typing import Any
|
||||
from pathlib import Path
|
||||
import json
|
||||
|
||||
from core.config_writer import write_text_atomic
|
||||
from core.runtime_paths import resolve_data_path
|
||||
|
||||
|
||||
@dataclass
|
||||
class ChatSession:
|
||||
key: str
|
||||
action: str
|
||||
payload: dict[str, Any]
|
||||
expires_at: datetime
|
||||
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class ChatSessionStore:
|
||||
def __init__(self, *, ttl_seconds: int = 600, max_sessions: int = 1000, persistence_path: str | Path | None = None):
|
||||
self.ttl_seconds = ttl_seconds
|
||||
self.max_sessions = max_sessions
|
||||
self._items: dict[str, ChatSession] = {}
|
||||
self._lock = RLock()
|
||||
self.persistence_path = Path(persistence_path) if persistence_path is not None else resolve_data_path("data/chat_sessions.json")
|
||||
self._load()
|
||||
|
||||
def put(self, key: str, action: str, payload: dict[str, Any]) -> ChatSession:
|
||||
with self._lock:
|
||||
self._prune()
|
||||
if len(self._items) >= self.max_sessions:
|
||||
oldest = min(self._items.values(), key=lambda item: item.created_at)
|
||||
self._items.pop(oldest.key, None)
|
||||
session = ChatSession(key, action, dict(payload), datetime.now(timezone.utc) + timedelta(seconds=self.ttl_seconds))
|
||||
self._items[key] = session
|
||||
self._save()
|
||||
return session
|
||||
|
||||
def get(self, key: str) -> ChatSession | None:
|
||||
with self._lock:
|
||||
self._prune()
|
||||
return self._items.get(key)
|
||||
|
||||
def pop(self, key: str) -> ChatSession | None:
|
||||
with self._lock:
|
||||
self._prune()
|
||||
session = self._items.pop(key, None)
|
||||
self._save()
|
||||
return session
|
||||
|
||||
def _prune(self) -> None:
|
||||
now = datetime.now(timezone.utc)
|
||||
for key in [key for key, item in self._items.items() if item.expires_at <= now]:
|
||||
self._items.pop(key, None)
|
||||
|
||||
def _load(self) -> None:
|
||||
try:
|
||||
payload = json.loads(self.persistence_path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError, TypeError):
|
||||
return
|
||||
for item in payload if isinstance(payload, list) else []:
|
||||
try:
|
||||
session = ChatSession(
|
||||
key=str(item["key"]), action=str(item["action"]), payload=dict(item.get("payload") or {}),
|
||||
expires_at=datetime.fromisoformat(item["expires_at"]), created_at=datetime.fromisoformat(item["created_at"]),
|
||||
)
|
||||
self._items[session.key] = session
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
self._prune()
|
||||
|
||||
def _save(self) -> None:
|
||||
payload = [
|
||||
{"key": item.key, "action": item.action, "payload": item.payload, "expires_at": item.expires_at.isoformat(), "created_at": item.created_at.isoformat()}
|
||||
for item in self._items.values()
|
||||
]
|
||||
try:
|
||||
write_text_atomic(self.persistence_path, json.dumps(payload, ensure_ascii=False, indent=2))
|
||||
except OSError:
|
||||
return
|
||||
|
|
@ -0,0 +1,327 @@
|
|||
"""Chat-facing orchestration built entirely on the existing ImageStudio API contract."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
from adapters.astrbot_command_adapter import ChatCommandContext
|
||||
from backend.dto.chat_command_dto import SingleImageCommand
|
||||
from backend.services.chat_media_import_service import ChatMediaImportService
|
||||
from backend.services.chat_command_guard_service import ChatCommandGuardService
|
||||
from backend.services.cross_review_service import CrossReviewService
|
||||
from core.identity import RequestContext
|
||||
from core.chat_access_policy import chat_action_allowed
|
||||
from database.db_helper import load_config_payload
|
||||
|
||||
|
||||
Dispatcher = Callable[..., dict[str, Any]]
|
||||
|
||||
|
||||
class ChatWorkflowService:
|
||||
def __init__(self, dispatcher: Dispatcher, config_loader: Callable[[], dict[str, Any]] = load_config_payload, media_importer: ChatMediaImportService | None = None, guard: ChatCommandGuardService | None = None, cross_reviewer_factory: Callable[[], CrossReviewService] = CrossReviewService):
|
||||
self.dispatcher = dispatcher
|
||||
self.config_loader = config_loader
|
||||
self.media_importer = media_importer or ChatMediaImportService()
|
||||
self.guard = guard or ChatCommandGuardService()
|
||||
self.cross_reviewer_factory = cross_reviewer_factory
|
||||
|
||||
def submit_single_image(self, command: SingleImageCommand, chat: ChatCommandContext) -> dict[str, Any]:
|
||||
ctx = self._request_context(chat, "single_image")
|
||||
config = self.config_loader()
|
||||
active = self._data(self.dispatcher(ctx, "GET", "jobs", query={"status": "running", "page": 1, "page_size": 100}))
|
||||
active_items = active.get("items", []) if isinstance(active, dict) else []
|
||||
self.guard.check_generation(config, chat, size=command.size, active_jobs=active_items)
|
||||
profile = self._resolve_profile(ctx, command.profile_ref, chat.user_id)
|
||||
workflow = self._data(self.dispatcher(
|
||||
ctx,
|
||||
"POST",
|
||||
f"profiles/{profile['profile_id']}/workflows",
|
||||
payload={
|
||||
"workflow_type": "single_image",
|
||||
"display_name": f"聊天单图 · {command.prompt[:24]}",
|
||||
"mode": "quick",
|
||||
"metadata": {"source": "astrbot_chat", "message_origin": chat.message_origin},
|
||||
},
|
||||
))
|
||||
workflow_data = workflow["workflow"]
|
||||
node = workflow["nodes"][0]
|
||||
self._data(self.dispatcher(ctx, "POST", f"workflows/{workflow_data['workflow_id']}/start", payload={}))
|
||||
idempotency_source = chat.message_id or f"{chat.message_origin}:{chat.user_id}:{command.prompt}"
|
||||
generation = self._data(self.dispatcher(
|
||||
ctx,
|
||||
"POST",
|
||||
f"nodes/{node['node_id']}/generate",
|
||||
payload={
|
||||
"prompt": command.prompt,
|
||||
"negative_prompt": command.negative_prompt,
|
||||
"model_route": command.model_route,
|
||||
"size": command.size,
|
||||
"count": command.count,
|
||||
"idempotency_key": "chat_" + hashlib.sha256(idempotency_source.encode("utf-8")).hexdigest()[:32],
|
||||
"metadata": {
|
||||
"source": "astrbot_chat",
|
||||
"platform": chat.platform,
|
||||
"message_origin": chat.message_origin,
|
||||
"user_id": chat.user_id,
|
||||
"group_id": chat.group_id,
|
||||
},
|
||||
},
|
||||
))
|
||||
images = [
|
||||
self._data(self.dispatcher(ctx, "GET", f"images/{item['image_id']}", query={}))
|
||||
for item in generation.get("images", [])
|
||||
if item.get("image_id")
|
||||
]
|
||||
self.guard.record(chat, "single_image", target_id=generation.get("task_id"), details={"size": command.size, "count": command.count})
|
||||
return {
|
||||
"profile": profile,
|
||||
"workflow": workflow_data,
|
||||
"node": node,
|
||||
"generation": generation,
|
||||
"images": images,
|
||||
}
|
||||
|
||||
def list_node_images(self, node_id: str, chat: ChatCommandContext) -> list[dict[str, Any]]:
|
||||
return self._data(
|
||||
self.dispatcher(
|
||||
self._request_context(chat),
|
||||
"GET",
|
||||
f"nodes/{node_id}/images",
|
||||
query={"include_archived": False},
|
||||
)
|
||||
)
|
||||
|
||||
def list_jobs(self, chat: ChatCommandContext, *, task_id: str | None = None) -> Any:
|
||||
ctx = self._request_context(chat, "single_image")
|
||||
endpoint = f"jobs/{task_id}" if task_id else "jobs"
|
||||
return self._data(self.dispatcher(ctx, "GET", endpoint, query={"page": 1, "page_size": 10}))
|
||||
|
||||
def cancel_job(self, chat: ChatCommandContext, task_id: str) -> Any:
|
||||
return self._data(self.dispatcher(self._request_context(chat, "single_image"), "POST", f"jobs/{task_id}/cancel", payload={}))
|
||||
|
||||
def retry_job(self, chat: ChatCommandContext, task_id: str) -> Any:
|
||||
return self._data(self.dispatcher(self._request_context(chat, "single_image"), "POST", f"jobs/{task_id}/retry", payload={}))
|
||||
|
||||
def create_quick_profile_draft(self, description: str, chat: ChatCommandContext) -> dict[str, Any]:
|
||||
text = str(description or "").strip()
|
||||
if not text:
|
||||
raise ValueError("请提供角色名称和描述,例如:/yp 快速角色 米卡 银发蓝眼的冷静少女")
|
||||
questionnaire = _quick_questionnaire(text)
|
||||
return self._data(self.dispatcher(self._request_context(chat), "POST", "profiles/quick-draft", payload={
|
||||
"questionnaire": questionnaire,
|
||||
}))
|
||||
|
||||
def save_quick_profile_draft(self, draft: dict[str, Any], chat: ChatCommandContext) -> dict[str, Any]:
|
||||
return self._data(self.dispatcher(self._request_context(chat), "POST", "profiles/quick-draft/save", payload={
|
||||
**draft,
|
||||
"draft": draft,
|
||||
"create_workflow": True,
|
||||
"workflow_status": "draft",
|
||||
"metadata": {"source": "astrbot_chat", "message_origin": chat.message_origin},
|
||||
}))
|
||||
|
||||
def create_or_resume_character_workflow(self, profile_ref: str, chat: ChatCommandContext) -> dict[str, Any]:
|
||||
ctx = self._request_context(chat, "single_image")
|
||||
profile = self._resolve_required_profile(ctx, profile_ref)
|
||||
workflows = self._data(self.dispatcher(ctx, "GET", f"profiles/{profile['profile_id']}/workflows", query={}))
|
||||
active = next((item for item in workflows if item.get("workflow_type") == "character_gradual" and item.get("status") not in {"completed", "cancelled", "archived"}), None)
|
||||
if active:
|
||||
detail = self._data(self.dispatcher(ctx, "GET", f"workflows/{active['workflow_id']}", query={}))
|
||||
return {"profile": profile, **detail, "resumed": True}
|
||||
detail = self._data(self.dispatcher(ctx, "POST", f"profiles/{profile['profile_id']}/workflows", payload={
|
||||
"workflow_type": "character_gradual",
|
||||
"display_name": f"{profile['name']} 详细角色工作流",
|
||||
"mode": "gradual",
|
||||
"metadata": {"source": "astrbot_chat", "message_origin": chat.message_origin},
|
||||
}))
|
||||
return {"profile": profile, **detail, "resumed": False}
|
||||
|
||||
def workflow_detail(self, workflow_id: str, chat: ChatCommandContext) -> dict[str, Any]:
|
||||
return self._data(self.dispatcher(self._request_context(chat), "GET", f"workflows/{workflow_id}", query={}))
|
||||
|
||||
def generate_node(self, node_id: str, chat: ChatCommandContext, *, prompt: str = "") -> dict[str, Any]:
|
||||
payload = {"prompt": prompt} if prompt else {}
|
||||
ctx = self._request_context(chat)
|
||||
result = self._data(self.dispatcher(ctx, "POST", f"nodes/{node_id}/generate", payload=payload))
|
||||
result["images"] = [
|
||||
self._data(self.dispatcher(ctx, "GET", f"images/{item['image_id']}", query={}))
|
||||
for item in result.get("images", [])
|
||||
if item.get("image_id")
|
||||
]
|
||||
return result
|
||||
|
||||
def retry_node(self, node_id: str, chat: ChatCommandContext) -> dict[str, Any]:
|
||||
return self._data(self.dispatcher(self._request_context(chat), "POST", f"nodes/{node_id}/retry", payload={}))
|
||||
|
||||
def complete_node(self, node_id: str, chat: ChatCommandContext) -> dict[str, Any]:
|
||||
return self._data(self.dispatcher(self._request_context(chat), "POST", f"nodes/{node_id}/complete", payload={}))
|
||||
|
||||
def next_workflow_step(self, workflow_id: str, chat: ChatCommandContext) -> dict[str, Any]:
|
||||
ctx = self._request_context(chat)
|
||||
detail = self._data(self.dispatcher(ctx, "GET", f"workflows/{workflow_id}", query={}))
|
||||
workflow = detail["workflow"]
|
||||
nodes = detail.get("nodes", [])
|
||||
current = next((item for item in nodes if item.get("node_id") == workflow.get("current_node_id")), None)
|
||||
candidate = current if current and current.get("status") not in {"completed", "skipped"} else next((item for item in nodes if item.get("status") in {"pending", "draft", "failed"}), None)
|
||||
if candidate is None:
|
||||
return {"completed": True, "workflow": workflow}
|
||||
if candidate.get("node_id") != workflow.get("current_node_id"):
|
||||
self._data(self.dispatcher(ctx, "PUT", f"workflows/{workflow_id}", payload={"current_node_id": candidate["node_id"]}))
|
||||
generation = self._data(self.dispatcher(ctx, "POST", f"nodes/{candidate['node_id']}/generate", payload={}))
|
||||
return {"completed": False, "workflow": workflow, "node": candidate, "generation": generation}
|
||||
|
||||
def select_node_image(self, node_id: str, image_id: str, chat: ChatCommandContext) -> dict[str, Any]:
|
||||
ctx = self._request_context(chat)
|
||||
selected = self._data(self.dispatcher(ctx, "POST", f"nodes/{node_id}/select-image", payload={"image_id": image_id}))
|
||||
image = self._data(self.dispatcher(ctx, "GET", f"images/{image_id}", query={}))
|
||||
if image.get("profile_id") and image.get("image_uri"):
|
||||
self._data(self.dispatcher(ctx, "PUT", f"profiles/{image['profile_id']}", payload={"avatar_image_uri": image["image_uri"]}))
|
||||
return selected
|
||||
|
||||
def select_node_image_by_number(self, node_id: str, number: int, chat: ChatCommandContext) -> dict[str, Any]:
|
||||
images = self.list_node_images(node_id, chat)
|
||||
if number < 1 or number > len(images):
|
||||
raise ValueError(f"图片序号必须在 1 到 {len(images)} 之间")
|
||||
return self.select_node_image(node_id, images[number - 1]["image_id"], chat)
|
||||
|
||||
def review(self, target_id: str, chat: ChatCommandContext) -> dict[str, Any]:
|
||||
prefix = "workflows" if target_id.startswith(("wf_", "workflow_")) else "nodes"
|
||||
ctx = self._request_context(chat)
|
||||
rules = self._data(self.dispatcher(ctx, "GET", f"{prefix}/{target_id}/review", query={}))
|
||||
node_ids = [target_id]
|
||||
if prefix == "workflows":
|
||||
detail = self._data(self.dispatcher(ctx, "GET", f"workflows/{target_id}", query={}))
|
||||
node_ids = [item["node_id"] for item in detail.get("nodes", []) if item.get("status") == "completed"]
|
||||
model_reviews = {node_id: self.cross_reviewer_factory().review_node(node_id) for node_id in node_ids}
|
||||
return {"rules": rules, "model_reviews": model_reviews}
|
||||
|
||||
def hires_fix(self, image_id: str, size: str, chat: ChatCommandContext) -> dict[str, Any]:
|
||||
ctx = self._request_context(chat)
|
||||
image = self._data(self.dispatcher(ctx, "GET", f"images/{image_id}", query={}))
|
||||
workflow = self._data(self.dispatcher(
|
||||
ctx,
|
||||
"POST",
|
||||
f"profiles/{image['profile_id']}/workflows",
|
||||
payload={
|
||||
"workflow_type": "single_image",
|
||||
"display_name": f"高清修复 · {image_id}",
|
||||
"mode": "quick",
|
||||
"metadata": {"source": "astrbot_chat_hires", "source_image_id": image_id},
|
||||
},
|
||||
))
|
||||
workflow_data = workflow["workflow"]
|
||||
node = workflow["nodes"][0]
|
||||
self._data(self.dispatcher(ctx, "POST", f"workflows/{workflow_data['workflow_id']}/start", payload={}))
|
||||
config = load_config_payload()
|
||||
assignments = config.get("model_assignments") if isinstance(config.get("model_assignments"), dict) else {}
|
||||
generation = self._data(self.dispatcher(ctx, "POST", f"nodes/{node['node_id']}/generate", payload={
|
||||
"prompt": "high resolution restoration, preserve identity, composition, clothing and original style",
|
||||
"negative_prompt": "identity change, composition change, clothing change, oversharpening, artifacts",
|
||||
"model_route": assignments.get("hires_fix"),
|
||||
"size": size,
|
||||
"count": 1,
|
||||
"input_images": [{"image_uri": image["image_uri"]}],
|
||||
"metadata": {"source": "astrbot_chat_hires", "source_image_id": image_id},
|
||||
}))
|
||||
images = [self._data(self.dispatcher(ctx, "GET", f"images/{item['image_id']}", query={})) for item in generation.get("images", [])]
|
||||
return {"source_image": image, "workflow": workflow_data, "node": node, "generation": generation, "images": images}
|
||||
|
||||
def import_material(self, image_reference: str, category_ref: str, chat: ChatCommandContext) -> dict[str, Any]:
|
||||
ctx = self._request_context(chat)
|
||||
categories = self._data(self.dispatcher(ctx, "GET", "material-categories", query={}))
|
||||
category = next((item for item in categories if item.get("category_id") == category_ref or item.get("name") == category_ref), None)
|
||||
if category is None:
|
||||
raise ValueError(f"未找到素材分类:{category_ref}")
|
||||
uri, filename, size_bytes = self.media_importer.import_image(image_reference)
|
||||
material = self._data(self.dispatcher(ctx, "POST", "materials/upload", payload={
|
||||
"category_id": category["category_id"], "display_name": Path(filename).stem,
|
||||
"image_uri": uri, "thumbnail_uri": uri, "filename": filename, "size_bytes": size_bytes,
|
||||
"metadata": {"source": "astrbot_chat", "message_origin": chat.message_origin},
|
||||
}))
|
||||
recognized = self._data(self.dispatcher(ctx, "POST", f"materials/{material['material_id']}/recognize", payload={}))
|
||||
profiles = self._data(self.dispatcher(ctx, "GET", "profiles", query={"page": 1, "page_size": 20}))
|
||||
return {"category": category, "material": recognized, "profiles": profiles.get("items", []) if isinstance(profiles, dict) else []}
|
||||
|
||||
def confirm_material(self, material_id: str, chat: ChatCommandContext) -> dict[str, Any]:
|
||||
return self._data(self.dispatcher(self._request_context(chat), "POST", f"materials/{material_id}/confirm", payload={}))
|
||||
|
||||
def re_recognize_material(self, material_id: str, chat: ChatCommandContext) -> dict[str, Any]:
|
||||
return self._data(self.dispatcher(self._request_context(chat), "POST", f"materials/{material_id}/re-recognize", payload={}))
|
||||
|
||||
def add_material_to_wardrobe(self, material_id: str, profile_ref: str, wardrobe_category: str, chat: ChatCommandContext) -> dict[str, Any]:
|
||||
ctx = self._request_context(chat)
|
||||
profile = self._resolve_required_profile(ctx, profile_ref)
|
||||
return self._data(self.dispatcher(ctx, "POST", f"profiles/{profile['profile_id']}/wardrobe/import-material", payload={
|
||||
"material_id": material_id, "wardrobe_category": wardrobe_category,
|
||||
}))
|
||||
|
||||
def _resolve_profile(self, ctx: RequestContext, profile_ref: str | None, user_id: str) -> dict[str, Any]:
|
||||
keyword = profile_ref or f"聊天单图 {user_id}"
|
||||
result = self._data(self.dispatcher(ctx, "GET", "profiles", query={"keyword": keyword, "page": 1, "page_size": 30}))
|
||||
items = result.get("items", []) if isinstance(result, dict) else []
|
||||
if profile_ref:
|
||||
exact = next((item for item in items if item.get("profile_id") == profile_ref or item.get("name") == profile_ref), None)
|
||||
if exact:
|
||||
return exact
|
||||
raise ValueError(f"未找到角色:{profile_ref}")
|
||||
if items:
|
||||
return items[0]
|
||||
return self._data(self.dispatcher(ctx, "POST", "profiles", payload={
|
||||
"name": f"聊天单图 {user_id}",
|
||||
"profile_type": "quick",
|
||||
"description": "AstrBot 聊天单图专用角色容器",
|
||||
"metadata": {"source": "astrbot_chat", "system_container": True},
|
||||
}))
|
||||
|
||||
def _resolve_required_profile(self, ctx: RequestContext, profile_ref: str) -> dict[str, Any]:
|
||||
text = str(profile_ref or "").strip()
|
||||
if not text:
|
||||
raise ValueError("请提供角色名称或角色 ID")
|
||||
result = self._data(self.dispatcher(ctx, "GET", "profiles", query={"keyword": text, "page": 1, "page_size": 30}))
|
||||
items = result.get("items", []) if isinstance(result, dict) else []
|
||||
profile = next((item for item in items if item.get("profile_id") == text or item.get("name") == text), None)
|
||||
if profile is None:
|
||||
raise ValueError(f"未找到角色:{text}")
|
||||
return profile
|
||||
|
||||
def _request_context(self, chat: ChatCommandContext, action: str = "character_workflow") -> RequestContext:
|
||||
config = self.config_loader()
|
||||
if not chat_action_allowed(config, action, group_id=chat.group_id, user_id=chat.user_id):
|
||||
try:
|
||||
self.guard.record(chat, action, allowed=False, details={"reason": "allowlist"})
|
||||
except Exception:
|
||||
pass
|
||||
raise ValueError("当前群聊或用户不满足聊天白名单规则")
|
||||
return RequestContext.from_astrbot(
|
||||
username=chat.user_id or "chat-user",
|
||||
user_id=chat.user_id or "chat-user",
|
||||
permissions={"can_write", "can_retry_tasks", "can_manage_materials"},
|
||||
source=f"astrbot_chat:{chat.platform}",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _data(response: dict[str, Any]) -> Any:
|
||||
if not response.get("ok"):
|
||||
raise ValueError(str(response.get("message") or response.get("error_code") or "ImageStudio 请求失败"))
|
||||
return response.get("data")
|
||||
|
||||
|
||||
def _quick_questionnaire(text: str) -> dict[str, Any]:
|
||||
parts = text.split(maxsplit=1)
|
||||
if len(parts) < 2:
|
||||
raise ValueError("请同时提供角色名和角色描述,例如:/yp 快速角色 米卡 银发蓝眼的冷静少女")
|
||||
name, description = parts[0].strip(), parts[1].strip()
|
||||
colors = re.findall(r"([黑白红橙黄绿青蓝紫粉灰棕金银]{1,2})色?(?:头发|发|眼睛|眼)", description)
|
||||
hair = next((value for value in colors if f"{value}发" in description or f"{value}色头发" in description), "")
|
||||
eyes = next((value for value in colors if f"{value}眼" in description or f"{value}色眼睛" in description), "")
|
||||
personality_keywords = [item for item in ("冷静", "温柔", "活泼", "开朗", "内向", "傲娇", "成熟", "勇敢", "神秘") if item in description]
|
||||
clothing_keywords = [item for item in ("制服", "礼服", "外套", "裙", "衬衫", "盔甲", "斗篷", "和服", "运动服") if item in description]
|
||||
hairstyle = next((item for item in ("长发", "短发", "双马尾", "马尾", "卷发", "直发", "齐刘海") if item in description), "")
|
||||
return {
|
||||
"name": name, "identity": description, "personality": personality_keywords,
|
||||
"hair_color": hair, "hairstyle": hairstyle, "eye_color": eyes,
|
||||
"clothing_keywords": clothing_keywords,
|
||||
}
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
"""Multi-route visual review used by AstrBot chat commands."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import mimetypes
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from typing import Any
|
||||
|
||||
from backend.services.model_provider_bootstrap import sync_vision_provider_from_config
|
||||
from backend.services.model_provider_runtime import ModelProviderRuntime
|
||||
from backend.services.model_provider_service import ModelProviderService
|
||||
from core.storage import VfsStorage
|
||||
from database.db_helper import Database, load_config_payload, load_database_settings
|
||||
from database.repositories.image_repository import ImageRepository
|
||||
from database.repositories.model_provider_repository import ModelProviderRepository
|
||||
from engines.vision_provider import VisionRecognitionRequest
|
||||
|
||||
|
||||
class CrossReviewService:
|
||||
def __init__(self):
|
||||
self.database = Database(load_database_settings())
|
||||
self.images = ImageRepository(self.database)
|
||||
self.storage = VfsStorage()
|
||||
self.config = load_config_payload()
|
||||
provider_service = ModelProviderService(ModelProviderRepository(self.database))
|
||||
sync_vision_provider_from_config(provider_service, self.config)
|
||||
self.runtime = ModelProviderRuntime(provider_service)
|
||||
|
||||
def review_node(self, node_id: str) -> dict[str, Any]:
|
||||
images = self.images.list_by_node(node_id, include_archived=False)
|
||||
selected = next((item for item in images if item.is_selected), None) or (images[0] if images else None)
|
||||
if selected is None:
|
||||
return {"routes": [], "reviews": [], "consensus": "节点没有可审核图片", "disagreements": []}
|
||||
image_data = self._data_url(selected.image_uri)
|
||||
routes = self._routes()
|
||||
reviews: list[dict[str, Any]] = []
|
||||
with ThreadPoolExecutor(max_workers=min(len(routes), 4) or 1) as executor:
|
||||
futures = {executor.submit(self._review_route, route, image_data, selected.image_id): route for route in routes}
|
||||
for future in as_completed(futures):
|
||||
route = futures[future]
|
||||
try:
|
||||
reviews.append(future.result())
|
||||
except Exception as exc:
|
||||
reviews.append({"route": route, "status": "failed", "error": str(exc)})
|
||||
successful = [item for item in reviews if item.get("status") == "succeeded"]
|
||||
defects = sorted({tag for item in successful for tag in item.get("defects", [])})
|
||||
return {
|
||||
"image_id": selected.image_id,
|
||||
"routes": routes,
|
||||
"reviews": reviews,
|
||||
"consensus": "、".join(defects) if defects else ("未发现明确缺陷" if successful else "没有模型完成审核"),
|
||||
"disagreements": _disagreements(successful),
|
||||
"average_confidence": round(sum(float(item.get("confidence") or 0) for item in successful) / len(successful), 3) if successful else 0,
|
||||
}
|
||||
|
||||
def _review_route(self, route: str, image_data: str, image_id: str) -> dict[str, Any]:
|
||||
provider = self.runtime.vision_provider_for_route({"route_name": route, "modality": "cross_review", "image_id": image_id})
|
||||
if provider is None:
|
||||
raise ValueError("审核模型路由不可用或凭据缺失")
|
||||
instruction = (
|
||||
"Independently inspect this generated character image. Check identity consistency, anatomy, hands, face, "
|
||||
"clothing structure, material, composition, text, watermark and rendering artifacts. Return JSON using the "
|
||||
"required fields. Put defect labels in tags, detailed verdict in description, recommended correction in prompt, "
|
||||
"and confidence from 0 to 1. Do not agree with another reviewer because no other verdict is provided."
|
||||
)
|
||||
result = provider.recognize_material(VisionRecognitionRequest(
|
||||
display_name=f"cross review {image_id}", image_uri=image_data,
|
||||
metadata={"recognition_instruction": instruction},
|
||||
))
|
||||
return {
|
||||
"route": route, "provider_id": result.provider_id, "model": result.model, "status": "succeeded",
|
||||
"defects": result.tags, "confidence": result.confidence, "verdict": result.description,
|
||||
"recommendation": result.prompt, "negative_prompt": result.negative_prompt,
|
||||
}
|
||||
|
||||
def _routes(self) -> list[str]:
|
||||
assignments = self.config.get("model_assignments") if isinstance(self.config.get("model_assignments"), dict) else {}
|
||||
configured = assignments.get("cross_review_routes")
|
||||
routes = [str(item).strip() for item in configured] if isinstance(configured, list) else []
|
||||
routes.extend([str(assignments.get("cross_review_primary") or "").strip(), str(assignments.get("cross_review_secondary") or "").strip()])
|
||||
return list(dict.fromkeys(item for item in routes if item))
|
||||
|
||||
def _data_url(self, uri: str) -> str:
|
||||
path = self.storage.ensure_file(uri)
|
||||
mime = mimetypes.guess_type(path.name)[0] or "image/png"
|
||||
return f"data:{mime};base64,{base64.b64encode(path.read_bytes()).decode('ascii')}"
|
||||
|
||||
|
||||
def _disagreements(reviews: list[dict[str, Any]]) -> list[str]:
|
||||
if len(reviews) < 2:
|
||||
return []
|
||||
tag_sets = [set(item.get("defects", [])) for item in reviews]
|
||||
union = set().union(*tag_sets)
|
||||
return sorted(tag for tag in union if not all(tag in tags for tags in tag_sets))
|
||||
|
|
@ -123,6 +123,20 @@ class SettingsService:
|
|||
_field("category_requirements", "list", label="分类附加要求"),
|
||||
],
|
||||
},
|
||||
{
|
||||
"key": "chat_access",
|
||||
"title": "聊天权限",
|
||||
"fields": [
|
||||
_field("group_allowlist", "list", label="群聊白名单"),
|
||||
_field("user_allowlist", "list", label="用户白名单"),
|
||||
_field("user_concurrency_limit", "number", label="用户并发任务上限"),
|
||||
_field("group_concurrency_limit", "number", label="群聊并发任务上限"),
|
||||
_field("daily_user_generation_limit", "number", label="用户每日生成上限"),
|
||||
_field("daily_group_generation_limit", "number", label="群聊每日生成上限"),
|
||||
_field("allow_2k", "bool", label="允许聊天命令使用 2K"),
|
||||
_field("allow_4k", "bool", label="允许聊天命令使用 4K"),
|
||||
],
|
||||
},
|
||||
{
|
||||
"key": "storage",
|
||||
"title": "存储",
|
||||
|
|
|
|||
10
config.yaml
10
config.yaml
|
|
@ -66,6 +66,16 @@ recognition_prompts:
|
|||
请先判断图片中素材的准确分类,再尽可能完整地提取所有可见事实,包括物品类型、主色与辅色、材质、纹理、结构、轮廓、图案、裁剪、缝线、褶皱、装饰、配件、状态、视角、光照及可复用的设计特征。不要把无法确认的推测写成事实,并明确区分确定信息与低置信度判断。根据识别结果生成一段细节充分、可直接用于生图且能够保留原素材设计的正向提示词,同时生成用于排除错误类别、错误材质、结构畸变、文字、水印和无关背景的负向提示词。仅返回 JSON,字段必须包含 prompt、negative_prompt、tags、confidence、description;tags 应简短、可检索,并包含分类、颜色、材质和关键设计元素。
|
||||
category_requirements: []
|
||||
|
||||
chat_access:
|
||||
group_allowlist: []
|
||||
user_allowlist: []
|
||||
user_concurrency_limit: 2
|
||||
group_concurrency_limit: 5
|
||||
daily_user_generation_limit: 30
|
||||
daily_group_generation_limit: 100
|
||||
allow_2k: true
|
||||
allow_4k: false
|
||||
|
||||
storage:
|
||||
# 这里使用逻辑 data/... 路径;AstrBot 运行时映射到
|
||||
# data/plugin_data/astrbot_plugin_imagestudio/...,本地开发仍映射到仓库 data/。
|
||||
|
|
|
|||
47
core/chat_access_policy.py
普通文件
47
core/chat_access_policy.py
普通文件
|
|
@ -0,0 +1,47 @@
|
|||
"""Chat command allowlist policy shared by AstrBot adapters."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
|
||||
STRICT_ACTIONS = frozenset({"quick_profile", "character_workflow"})
|
||||
ANY_ALLOWLIST_ACTIONS = frozenset({"single_image"})
|
||||
|
||||
|
||||
def chat_action_allowed(
|
||||
config: Mapping[str, Any] | None,
|
||||
action: str,
|
||||
*,
|
||||
group_id: str | None,
|
||||
user_id: str | None,
|
||||
) -> bool:
|
||||
"""Return whether a chat action passes the configured allowlists.
|
||||
|
||||
Quick profile and character workflow require both group and user matches.
|
||||
Single-image generation accepts either match. Private chats have no group
|
||||
match, so strict actions are intentionally unavailable there unless the
|
||||
caller supplies a platform conversation/group identifier.
|
||||
"""
|
||||
|
||||
access = config.get("chat_access") if isinstance(config, Mapping) else None
|
||||
access = access if isinstance(access, Mapping) else {}
|
||||
groups = _normalized_ids(access.get("group_allowlist"))
|
||||
users = _normalized_ids(access.get("user_allowlist"))
|
||||
group_match = bool(group_id and str(group_id).strip() in groups)
|
||||
user_match = bool(user_id and str(user_id).strip() in users)
|
||||
normalized_action = str(action or "").strip().lower()
|
||||
if normalized_action in STRICT_ACTIONS:
|
||||
return group_match and user_match
|
||||
if normalized_action in ANY_ALLOWLIST_ACTIONS:
|
||||
return group_match or user_match
|
||||
return False
|
||||
|
||||
|
||||
def _normalized_ids(value: Any) -> set[str]:
|
||||
if isinstance(value, str):
|
||||
value = value.replace(",", "\n").splitlines()
|
||||
if not isinstance(value, (list, tuple, set, frozenset)):
|
||||
return set()
|
||||
return {str(item).strip() for item in value if str(item).strip()}
|
||||
|
|
@ -173,7 +173,7 @@ class ImageRepository:
|
|||
SELECT {IMAGE_COLUMNS}
|
||||
FROM generation_images
|
||||
{where_clause}
|
||||
ORDER BY created_at DESC, image_id DESC
|
||||
ORDER BY is_archived ASC, created_at DESC, image_id DESC
|
||||
LIMIT {placeholder} OFFSET {placeholder}
|
||||
""",
|
||||
tuple(params + [normalized_page_size, offset]),
|
||||
|
|
|
|||
226
docs/astrbot-chat-command-queue.md
普通文件
226
docs/astrbot-chat-command-queue.md
普通文件
|
|
@ -0,0 +1,226 @@
|
|||
# AstrBot 聊天命令开发队列
|
||||
|
||||
更新日期:2026-07-12
|
||||
|
||||
目标:在 QQ、Telegram、Discord 等 AstrBot 消息平台中,通过 `/影棚` 或 `/yp` 操作 ImageStudio 的单图生成、快速角色和详细角色工作流,并获得异步任务、图片、选图和审核回执。
|
||||
|
||||
## 当前完成基线
|
||||
|
||||
- [x] 注册 `/影棚` 命令组。
|
||||
- [x] 注册 `/yp` 短命令组。
|
||||
- [x] 提供帮助、状态、快速角色、工作流、单图子命令框架。
|
||||
- [x] 提取平台、统一消息来源、群聊 ID 和用户 ID。
|
||||
- [x] 配置群聊白名单与用户白名单。
|
||||
- [x] 快速角色和角色工作流要求群聊、用户同时命中。
|
||||
- [x] 单图生成允许群聊或用户任一白名单命中。
|
||||
- [x] 帮助和状态支持 PNG 卡片,异常时回退文字。
|
||||
- [x] AstrBot 不存在时保持本地测试可导入。
|
||||
|
||||
## P0:单图生成最小闭环
|
||||
|
||||
### P0-01 命令参数合同
|
||||
|
||||
- [x] 支持 `/yp 单图 <提示词>`。
|
||||
- [x] 支持角色、模型路由、尺寸、数量、负面提示词等显式参数。
|
||||
- [x] 同时支持自然文本和 `--参数 值` 两种输入。
|
||||
- [x] 将命令统一转换为 `SingleImageCommand` DTO。
|
||||
- [x] 参数错误返回示例和可复制的正确命令。
|
||||
|
||||
建议参数:
|
||||
|
||||
```text
|
||||
/yp 单图 雨夜街道中的少女 --角色 米卡 --尺寸 1K --数量 1
|
||||
```
|
||||
|
||||
### P0-02 单图任务提交
|
||||
|
||||
- [x] 将单图命令接入现有生成服务和模型分工中的 `quick_generation`。
|
||||
- [x] 执行角色归属、模型能力、预算和白名单预检。
|
||||
- [x] 创建队列任务并立即返回 `task_id`,不阻塞 AstrBot 消息协程。
|
||||
- [x] 保存平台、统一消息来源、用户、群聊和原消息 ID。
|
||||
- [x] 防止同一消息重复提交任务。
|
||||
|
||||
### P0-03 任务查询与取消
|
||||
|
||||
- [x] `/yp 任务`:列出当前用户最近任务。
|
||||
- [x] `/yp 任务 <task_id>`:显示任务详情。
|
||||
- [x] `/yp 取消 <task_id>`:取消等待中或运行中的任务。
|
||||
- [x] `/yp 重试 <task_id>`:按权限重试失败任务。
|
||||
- [x] 任务卡片显示排队位置、模型、尺寸、数量和耗时。
|
||||
|
||||
### P0-04 异步图片回执
|
||||
|
||||
- [x] Worker 完成任务后向原 `unified_msg_origin` 主动发送结果。
|
||||
- [x] 使用 AstrBot 图片消息组件发送图片,不泄露服务器本地路径。
|
||||
- [x] 同时返回图片编号、模型、尺寸、种子、耗时和任务 ID。
|
||||
- [x] 图片发送失败时回退为签名媒体 URL 或明确错误消息。
|
||||
- [x] 失败、取消、超时分别使用不同回执。
|
||||
|
||||
## P1:快速角色闭环
|
||||
|
||||
### P1-01 快速角色创建
|
||||
|
||||
- [x] `/yp 快速角色 <角色描述>` 接入快速角色草稿服务。
|
||||
- [x] 支持从聊天文本提取角色名、外观、性格、服装和禁用项。
|
||||
- [x] 缺少角色名时进入短期会话询问,不直接创建匿名角色。
|
||||
- [x] 创建前检查群聊与用户双白名单。
|
||||
- [x] 创建的角色 owner 绑定发起用户。
|
||||
|
||||
### P1-02 快速角色确认
|
||||
|
||||
- [x] 返回结构化角色摘要卡片。
|
||||
- [x] 支持“确认”“修改”“取消”。
|
||||
- [x] 修改时允许补充一段自然语言并重新解析。
|
||||
- [x] 会话绑定群聊、用户和角色草稿,避免其他群员误操作。
|
||||
- [x] 会话 5–10 分钟自动过期。
|
||||
|
||||
### P1-03 快速角色生图
|
||||
|
||||
- [x] 确认角色后可直接回复“生成”。
|
||||
- [x] 使用 `quick_generation` 模型分工路由。
|
||||
- [x] 返回候选图并建立选图会话。
|
||||
- [x] 支持回复数字采用候选图。
|
||||
- [x] 选中结果写回角色封面和图库。
|
||||
|
||||
## P1:详细角色工作流
|
||||
|
||||
### P1-04 工作流创建与恢复
|
||||
|
||||
- [x] `/yp 工作流 <角色名或 ID>` 创建或恢复工作流。
|
||||
- [x] 检查角色 owner、归档状态和双白名单。
|
||||
- [x] 同一角色存在未完成工作流时默认恢复,避免重复创建。
|
||||
- [x] 返回工作流 ID、节点进度和当前节点。
|
||||
|
||||
### P1-05 节点操作
|
||||
|
||||
- [x] `/yp 节点 <workflow_id>` 查看节点列表。
|
||||
- [x] `/yp 生成 <node_id>` 执行当前节点。
|
||||
- [x] `/yp 重试节点 <node_id>` 重试节点。
|
||||
- [x] `/yp 完成节点 <node_id>` 确认节点。
|
||||
- [x] `/yp 下一步 <workflow_id>` 进入下一个可执行节点。
|
||||
- [x] 拒绝跳过未满足依赖的节点。
|
||||
|
||||
### P1-06 候选图选择
|
||||
|
||||
- [x] 生成完成后返回带编号候选图。
|
||||
- [x] 支持回复 `1`、`2`、`3` 选图。
|
||||
- [x] 支持 `/yp 选图 <node_id> <序号>` 无状态操作。
|
||||
- [x] 选图前校验图片属于节点且未归档。
|
||||
- [x] 选图后提示继续、重试或审核。
|
||||
|
||||
## P2:审核和高清修复
|
||||
|
||||
### P2-01 交叉审核
|
||||
|
||||
- [x] `/yp 审核 <node_id|workflow_id>` 提交审核。
|
||||
- [x] 使用设置页配置的多个 `cross_review_routes`。
|
||||
- [x] 主审、复核和附加审核并行执行。
|
||||
- [x] 聚合一致结论、分歧和置信度。
|
||||
- [x] 返回缺陷、评分和建议操作卡片。
|
||||
|
||||
### P2-02 高清修复
|
||||
|
||||
- [x] `/yp 高清 <image_id> --尺寸 2K|4K`。
|
||||
- [x] 使用 `hires_fix` 模型分工路由。
|
||||
- [x] 执行模型能力、最大分辨率和预算预检。
|
||||
- [x] 保留原图、修复图和生成关系。
|
||||
- [x] 完成后返回原图与修复图对照。
|
||||
|
||||
## P2:素材聊天操作
|
||||
|
||||
### P2-03 图片素材导入
|
||||
|
||||
- [x] 支持命令消息附带一张或多张图片。
|
||||
- [x] `/yp 素材导入 --分类 <分类>`。
|
||||
- [x] 分类只能从现有素材分类中解析。
|
||||
- [x] 使用 `material_recognition` 模型路由和分类识别提示词。
|
||||
- [x] 返回识别结果并等待确认。
|
||||
|
||||
### P2-04 素材确认与角色衣橱
|
||||
|
||||
- [x] 支持确认、重新识别和取消素材。
|
||||
- [x] 支持将确认素材加入指定角色衣橱。
|
||||
- [x] 校验素材权限、角色 owner 和衣橱分类。
|
||||
- [x] 返回素材卡片和可用角色列表。
|
||||
|
||||
## P2:会话状态层
|
||||
|
||||
### P2-05 会话存储
|
||||
|
||||
- [x] 新建平台无关的 `ChatSessionStore`。
|
||||
- [x] 会话键包含平台、消息来源和用户 ID。
|
||||
- [x] 支持角色确认、选图、素材确认和危险操作确认。
|
||||
- [x] 设置过期时间和最大会话数量。
|
||||
- [x] 插件重载后可选择恢复关键会话。
|
||||
|
||||
### P2-06 非命令回复捕获
|
||||
|
||||
- [x] 仅在存在活动会话时处理“1”“确认”“继续”等普通消息。
|
||||
- [x] 不抢占其他 AstrBot 插件的普通聊天消息。
|
||||
- [x] 群聊中只接受原发起用户的回复。
|
||||
- [x] 提供“退出”“取消”结束会话。
|
||||
|
||||
## P3:跨平台和运营保护
|
||||
|
||||
### P3-01 跨平台消息适配
|
||||
|
||||
- [x] QQ、Telegram、Discord 至少各完成一次文本和图片回执测试。
|
||||
- [x] 统一处理平台图片 URL、本地缓存和消息组件差异。
|
||||
- [x] 不依赖 QQ 专属字段作为业务主键。
|
||||
- [x] 优先使用 AstrBot `unified_msg_origin` 主动回执。
|
||||
|
||||
### P3-02 限流和成本保护
|
||||
|
||||
- [x] 用户并发任务限制。
|
||||
- [x] 群聊并发任务限制。
|
||||
- [x] 用户、群聊每日生成额度。
|
||||
- [x] 2K、4K 和高成本模型独立授权。
|
||||
- [x] 命令提交前调用现有成本保护服务。
|
||||
|
||||
### P3-03 管理与审计
|
||||
|
||||
- [x] 记录命令、调用用户、群聊、任务 ID 和结果。
|
||||
- [x] 日志中不保存完整敏感提示词和凭据。
|
||||
- [x] Web 日志页面可以筛选聊天命令来源。
|
||||
- [x] 管理员可以查询被拒绝的白名单请求。
|
||||
|
||||
## P3:测试与验收
|
||||
|
||||
### P3-04 单元测试
|
||||
|
||||
- [x] 命令参数解析覆盖中文空格、引号和显式参数。
|
||||
- [x] 白名单组合覆盖群聊、私聊和空名单。
|
||||
- [x] 事件字段兼容不同 AstrBot 平台适配器。
|
||||
- [x] 图片卡片失败时验证文字降级。
|
||||
- [x] 会话过期、越权回复和重复提交测试。
|
||||
|
||||
### P3-05 AstrBot 集成测试
|
||||
|
||||
- [x] 插件加载后命令组可被 AstrBot 正确发现。
|
||||
- [x] `/影棚` 与 `/yp` 行为一致。
|
||||
- [x] 命令协程不等待长时间生图。
|
||||
- [x] Worker 完成后能够主动发送到原会话。
|
||||
- [x] 插件重载和 AstrBot 重启后任务状态不丢失。
|
||||
|
||||
### P3-06 发布验收
|
||||
|
||||
- [x] 更新 README 命令说明。
|
||||
- [x] 更新配置迁移和白名单说明。
|
||||
- [x] 完整后端测试通过。
|
||||
- [x] 前端类型检查和生产构建通过。
|
||||
- [x] Windows、Linux/Docker 路径与图片发送测试通过。
|
||||
- [ ] Forgejo 提交、推送并记录版本号。
|
||||
|
||||
## 推荐实施顺序
|
||||
|
||||
```text
|
||||
P0-01 参数合同
|
||||
→ P0-02 单图任务提交
|
||||
→ P0-03 任务查询
|
||||
→ P0-04 异步图片回执
|
||||
→ P1-01~P1-03 快速角色
|
||||
→ P1-04~P1-06 详细工作流与选图
|
||||
→ P2-05~P2-06 会话状态层
|
||||
→ P2-01~P2-04 审核、高清和素材
|
||||
→ P3 跨平台、限流、审计和发布验收
|
||||
```
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "astrbot-plugin-imagestudio-frontend",
|
||||
"version": "3.0.0",
|
||||
"version": "3.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { computed, ref } from "vue"
|
|||
import { formatTime, normalizeStatus } from "../../../../shared/utils/presentation"
|
||||
import type { AuditLog, ErrorLog, GenerationLog, IntegrationLog, WorkflowLog } from "../../../../shared/types/logs"
|
||||
|
||||
type LogType = "all" | "generation" | "workflow" | "error" | "integration" | "audit"
|
||||
type LogType = "all" | "generation" | "workflow" | "error" | "integration" | "audit" | "chat"
|
||||
interface LogRow { id:string; type:Exclude<LogType,"all">; title:string; detail:string; status:string; createdAt:string; meta:Record<string,unknown> }
|
||||
|
||||
const props=defineProps<{generation:readonly GenerationLog[];workflows:readonly WorkflowLog[];errors:readonly ErrorLog[];integrations:readonly IntegrationLog[];audit:readonly AuditLog[];loading:boolean;error:string;backendConnected:boolean;canAudit:boolean}>()
|
||||
|
|
@ -16,16 +16,16 @@ const previewRows:LogRow[]=[
|
|||
{id:"preview-integration",type:"integration",title:"示例集成同步",detail:"private companion / daily outfit",status:"succeeded",createdAt:"2026-07-10T10:40:00Z",meta:{integration:"private_companion"}},
|
||||
{id:"preview-audit",type:"audit",title:"示例配置审计",detail:"settings validation",status:"recorded",createdAt:"2026-07-10T09:18:00Z",meta:{actor:"admin",target:"config"}},
|
||||
]
|
||||
const tabs:Array<{key:LogType;label:string}>=[{key:"all",label:"全部"},{key:"generation",label:"生成"},{key:"workflow",label:"工作流"},{key:"error",label:"错误"},{key:"integration",label:"集成"},{key:"audit",label:"审计"}]
|
||||
const tabs:Array<{key:LogType;label:string}>=[{key:"all",label:"全部"},{key:"generation",label:"生成"},{key:"workflow",label:"工作流"},{key:"error",label:"错误"},{key:"integration",label:"集成"},{key:"chat",label:"聊天命令"},{key:"audit",label:"审计"}]
|
||||
const liveRows=computed<LogRow[]>(()=>[
|
||||
...props.generation.map(log=>({id:`g-${log.task_id}`,type:"generation" as const,title:`任务 ${log.task_id}`,detail:log.error_message||`${log.progress}% / ${log.status}`,status:log.status,createdAt:log.updated_at||log.created_at,meta:{...log}})),
|
||||
...props.workflows.map(log=>({id:`w-${log.history_id}`,type:"workflow" as const,title:log.title||log.action,detail:`${log.workflow_id}${log.node_id?` / ${log.node_id}`:""}`,status:log.action,createdAt:log.created_at,meta:{...log}})),
|
||||
...props.errors.map(log=>({id:`e-${log.source}-${log.id}`,type:"error" as const,title:log.source||"错误",detail:log.error_message||log.status,status:log.status,createdAt:log.created_at,meta:{...log}})),
|
||||
...props.integrations.map(log=>({id:`i-${log.integration_log_id}`,type:"integration" as const,title:`${log.integration_name} / ${log.action}`,detail:log.error_message||log.status,status:log.status,createdAt:log.created_at,meta:{...log}})),
|
||||
...props.audit.map(log=>({id:`a-${log.audit_id}`,type:"audit" as const,title:`${log.action} / ${log.target_type}`,detail:`${log.actor_id} → ${log.target_id}`,status:"recorded",createdAt:log.created_at,meta:{...log}})),
|
||||
...props.audit.map(log=>({id:`a-${log.audit_id}`,type:(log.target_type==="chat_command"?"chat":"audit") as "chat"|"audit",title:`${log.action} / ${log.target_type}`,detail:`${log.actor_id} → ${log.target_id}`,status:"recorded",createdAt:log.created_at,meta:{...log}})),
|
||||
].sort((a,b)=>Date.parse(b.createdAt)-Date.parse(a.createdAt)))
|
||||
const rows=computed(()=>liveRows.value.length?liveRows.value:props.backendConnected?[]:previewRows)
|
||||
const counts=computed<Record<LogType,number>>(()=>({all:rows.value.length,generation:rows.value.filter(r=>r.type==="generation").length,workflow:rows.value.filter(r=>r.type==="workflow").length,error:rows.value.filter(r=>r.type==="error").length,integration:rows.value.filter(r=>r.type==="integration").length,audit:rows.value.filter(r=>r.type==="audit").length}))
|
||||
const counts=computed<Record<LogType,number>>(()=>({all:rows.value.length,generation:rows.value.filter(r=>r.type==="generation").length,workflow:rows.value.filter(r=>r.type==="workflow").length,error:rows.value.filter(r=>r.type==="error").length,integration:rows.value.filter(r=>r.type==="integration").length,chat:rows.value.filter(r=>r.type==="chat").length,audit:rows.value.filter(r=>r.type==="audit").length}))
|
||||
const filtered=computed(()=>{const needle=query.value.trim().toLowerCase();return rows.value.filter(row=>(type.value==="all"||row.type===type.value)&&(!needle||[row.title,row.detail,row.status,JSON.stringify(row.meta)].some(v=>v.toLowerCase().includes(needle))))})
|
||||
const selected=computed(()=>filtered.value.find(row=>row.id===selectedId.value)||filtered.value[0]||null)
|
||||
const failedCount=computed(()=>rows.value.filter(row=>["failed","error","dead_letter"].includes(normalizeStatus(row.status))).length)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,41 @@
|
|||
<script setup lang="ts">
|
||||
import { computed } from "vue"
|
||||
|
||||
const props = defineProps<{ modelValue: Record<string, unknown>; disabled: boolean }>()
|
||||
const emit = defineEmits<{ "update:modelValue": [value: Record<string, unknown>] }>()
|
||||
function ids(key: string) { return Array.isArray(props.modelValue[key]) ? (props.modelValue[key] as unknown[]).map(String) : [] }
|
||||
function text(key: string) { return ids(key).join("\n") }
|
||||
function update(key: string, value: string) {
|
||||
const list = Array.from(new Set(value.replace(/,/g, ",").split(/[\n,]/).map(item => item.trim()).filter(Boolean)))
|
||||
emit("update:modelValue", { ...props.modelValue, [key]: list })
|
||||
}
|
||||
function updateValue(key: string, value: number | boolean) { emit("update:modelValue", { ...props.modelValue, [key]: value }) }
|
||||
const groupCount = computed(() => ids("group_allowlist").length)
|
||||
const userCount = computed(() => ids("user_allowlist").length)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="chat-access">
|
||||
<div class="intro"><span>AstrBot 聊天指令</span><strong>群聊与用户白名单</strong><p>每行填写一个平台提供的群聊 ID 或用户 ID,也支持用逗号分隔。白名单为空时不会放行对应条件。</p></div>
|
||||
<div class="rules">
|
||||
<article><b>快速角色 / 角色工作流</b><strong>群聊命中 + 用户命中</strong><p>两个白名单必须同时命中才允许使用,避免群内未授权成员启动完整工作流。</p></article>
|
||||
<article><b>单图生成</b><strong>群聊命中 或 用户命中</strong><p>任意一个白名单命中即可使用;用户白名单也可以在私聊中放行单图。</p></article>
|
||||
</div>
|
||||
<div class="lists">
|
||||
<label><span>群聊白名单 <em>{{ groupCount }} 项</em></span><textarea :value="text('group_allowlist')" :disabled="disabled" rows="10" placeholder="每行一个群聊 ID 例如:123456789" @input="update('group_allowlist', ($event.target as HTMLTextAreaElement).value)"></textarea><small>用于判断命令所在群聊是否获得授权。</small></label>
|
||||
<label><span>用户白名单 <em>{{ userCount }} 项</em></span><textarea :value="text('user_allowlist')" :disabled="disabled" rows="10" placeholder="每行一个用户 ID 例如:987654321" @input="update('user_allowlist', ($event.target as HTMLTextAreaElement).value)"></textarea><small>使用 AstrBot 事件返回的平台用户 ID,不使用昵称。</small></label>
|
||||
</div>
|
||||
<div class="limits">
|
||||
<label><span>用户并发上限</span><input type="number" min="1" :value="Number(modelValue.user_concurrency_limit || 2)" :disabled="disabled" @input="updateValue('user_concurrency_limit', Number(($event.target as HTMLInputElement).value))"></label>
|
||||
<label><span>群聊并发上限</span><input type="number" min="1" :value="Number(modelValue.group_concurrency_limit || 5)" :disabled="disabled" @input="updateValue('group_concurrency_limit', Number(($event.target as HTMLInputElement).value))"></label>
|
||||
<label><span>用户每日生成上限</span><input type="number" min="1" :value="Number(modelValue.daily_user_generation_limit || 30)" :disabled="disabled" @input="updateValue('daily_user_generation_limit', Number(($event.target as HTMLInputElement).value))"></label>
|
||||
<label><span>群聊每日生成上限</span><input type="number" min="1" :value="Number(modelValue.daily_group_generation_limit || 100)" :disabled="disabled" @input="updateValue('daily_group_generation_limit', Number(($event.target as HTMLInputElement).value))"></label>
|
||||
<label class="check"><input type="checkbox" :checked="modelValue.allow_2k !== false" :disabled="disabled" @change="updateValue('allow_2k', ($event.target as HTMLInputElement).checked)"><span>允许聊天使用 2K</span></label>
|
||||
<label class="check"><input type="checkbox" :checked="modelValue.allow_4k === true" :disabled="disabled" @change="updateValue('allow_4k', ($event.target as HTMLInputElement).checked)"><span>允许聊天使用 4K</span></label>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.chat-access{display:grid;gap:14px}.intro{display:grid;gap:5px;border:1px solid var(--border);border-radius:10px;padding:15px;background:linear-gradient(105deg,var(--primary-soft),var(--panel-muted))}.intro span{color:var(--text-soft);font-size:11px;font-weight:800}.intro p,.rules p{margin:0;color:var(--text-soft);line-height:1.5}.rules,.lists{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.rules article{display:grid;gap:6px;border:1px solid var(--border);border-radius:10px;padding:14px;background:var(--panel-muted)}.rules b{color:var(--text-soft);font-size:11px}.rules strong{color:var(--primary)}.lists label{display:grid;gap:7px;border:1px solid var(--border);border-radius:10px;padding:14px;background:var(--panel-muted)}.lists label>span{display:flex;justify-content:space-between;font-weight:750}.lists em{border-radius:5px;padding:2px 6px;color:var(--primary);background:var(--primary-soft);font-size:11px;font-style:normal}.lists textarea{width:100%;box-sizing:border-box;border:1px solid var(--border);border-radius:7px;padding:10px;color:var(--text);background:var(--panel);font:inherit;line-height:1.55;resize:vertical}.lists small{color:var(--text-soft)}.limits{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;border:1px solid var(--border);border-radius:10px;padding:14px;background:var(--panel-muted)}.limits label{display:grid;gap:6px}.limits input[type=number]{min-height:40px;border:1px solid var(--border);border-radius:7px;padding:0 10px;color:var(--text);background:var(--panel);font:inherit}.limits .check{display:flex;align-items:center;gap:8px}@media(max-width:760px){.rules,.lists,.limits{grid-template-columns:1fr}}
|
||||
</style>
|
||||
|
|
@ -11,6 +11,7 @@ import CapabilityProfilesPanel from "./CapabilityProfilesPanel.vue"
|
|||
import SystemManagementPanel from "./SystemManagementPanel.vue"
|
||||
import ModelAssignmentsPanel from "./ModelAssignmentsPanel.vue"
|
||||
import RecognitionPromptsPanel from "./RecognitionPromptsPanel.vue"
|
||||
import ChatAccessPanel from "./ChatAccessPanel.vue"
|
||||
|
||||
type ConfigValue = string | number | boolean | string[] | null
|
||||
type Adapter = { id:string; name:string; provider_type:string; base_url:string; image_endpoint:string; model_id:string; route_name:string; api_key_env_var:string; timeout_seconds:number; enabled:boolean }
|
||||
|
|
@ -22,6 +23,7 @@ const previewSchema: SettingsSchema = {schema_version:"3.0-preview",sections:[
|
|||
{key:"generation",title:"生成服务",fields:[]},
|
||||
{key:"model_assignments",title:"模型分工",fields:[]},
|
||||
{key:"recognition_prompts",title:"识别提示词",fields:[]},
|
||||
{key:"chat_access",title:"聊天权限",fields:[]},
|
||||
{key:"features",title:"功能开关",fields:[
|
||||
{key:"quick_profile",label:"快速角色",type:"bool",options:[],sensitive:false,readonly:false},{key:"workspace",label:"角色工作流",type:"bool",options:[],sensitive:false,readonly:false},{key:"material_library",label:"素材库",type:"bool",options:[],sensitive:false,readonly:false},{key:"wardrobe",label:"角色衣橱",type:"bool",options:[],sensitive:false,readonly:false},{key:"api_discovery",label:"能力探测",type:"bool",options:[],sensitive:false,readonly:false},{key:"private_companion_integration",label:"私伴插件集成",type:"bool",options:[],sensitive:false,readonly:false},
|
||||
]},
|
||||
|
|
@ -33,7 +35,7 @@ const previewSchema: SettingsSchema = {schema_version:"3.0-preview",sections:[
|
|||
]},
|
||||
{key:"backup",title:"数据备份",fields:[]},
|
||||
]}
|
||||
const previewConfig = computed<Record<string,unknown>>(()=>({generation:{default_model:"image_default",provider:{provider_id:"openai-compatible",base_url:"",image_endpoint:"/v1/images/generations",model_id:"",route_name:"image_default",api_key_env_var:"IMAGE_API_KEY",timeout_seconds:180}},model_assignments:{material_recognition:"material_vlm",quick_generation:"image_default",portrait_generation:"image_default",halfbody_generation:"image_default",fullbody_generation:"image_default",sheet_generation:"image_default",hires_fix:"image_default"},recognition_prompts:{default_instruction:"请先判断图片中素材的准确分类,再尽可能完整提取所有可见事实,包括颜色、材质、纹理、结构、轮廓、图案、裁剪、装饰、配件、视角和光照。不要把推测写成事实。根据结果生成可直接用于生图的详细正向提示词和负向提示词。仅返回 JSON:prompt、negative_prompt、tags、confidence、description。",category_requirements:[]},features:{quick_profile:true,workspace:true,material_library:true,wardrobe:true,api_discovery:true,private_companion_integration:false},storage:{images_path:"data/images",thumbnails_path:"data/thumbnails",materials_path:"data/materials",styles_path:"data/styles",archives_path:"data/archives",temp_path:"data/temp"},database:{backend:"auto",sqlite:{path:"data/imagestudio.db"},postgresql:{enabled:false,host:"127.0.0.1",port:5432,database:"imagestudio",user:"",password:""}}}))
|
||||
const previewConfig = computed<Record<string,unknown>>(()=>({generation:{default_model:"image_default",provider:{provider_id:"openai-compatible",base_url:"",image_endpoint:"/v1/images/generations",model_id:"",route_name:"image_default",api_key_env_var:"IMAGE_API_KEY",timeout_seconds:180}},model_assignments:{material_recognition:"material_vlm",quick_generation:"image_default",portrait_generation:"image_default",halfbody_generation:"image_default",fullbody_generation:"image_default",sheet_generation:"image_default",hires_fix:"image_default"},recognition_prompts:{default_instruction:"请先判断图片中素材的准确分类,再尽可能完整提取所有可见事实,包括颜色、材质、纹理、结构、轮廓、图案、裁剪、装饰、配件、视角和光照。不要把推测写成事实。根据结果生成可直接用于生图的详细正向提示词和负向提示词。仅返回 JSON:prompt、negative_prompt、tags、confidence、description。",category_requirements:[]},chat_access:{group_allowlist:[],user_allowlist:[]},features:{quick_profile:true,workspace:true,material_library:true,wardrobe:true,api_discovery:true,private_companion_integration:false},storage:{images_path:"data/images",thumbnails_path:"data/thumbnails",materials_path:"data/materials",styles_path:"data/styles",archives_path:"data/archives",temp_path:"data/temp"},database:{backend:"auto",sqlite:{path:"data/imagestudio.db"},postgresql:{enabled:false,host:"127.0.0.1",port:5432,database:"imagestudio",user:"",password:""}}}))
|
||||
const effectiveSchema=computed(()=>{const schema=clone(props.schema??previewSchema);for(const section of [{key:"review",title:"审查策略",fields:[]},{key:"capabilities",title:"能力档案",fields:[]},{key:"integration",title:"私伴集成",fields:[]},{key:"cost_guard",title:"成本保护",fields:[]},{key:"diagnostics",title:"系统诊断",fields:[]},{key:"backup",title:"数据备份",fields:[]}])if(!schema.sections.some(item=>item.key===section.key))schema.sections.push(section);return schema})
|
||||
const baseline=computed(()=>props.current?.config??previewConfig.value)
|
||||
const draft=ref<Record<string,unknown>>({})
|
||||
|
|
@ -86,13 +88,14 @@ function fieldValue(path:string):ConfigValue{let c:unknown=draft.value;for(const
|
|||
function updateField(path:string,value:ConfigValue){const next=clone(draft.value);const parts=path.split(".");let c=next;for(const p of parts.slice(0,-1)){if(!c[p]||typeof c[p]!=="object"||Array.isArray(c[p]))c[p]={};c=c[p] as Record<string,unknown>}c[parts.at(-1)!]=value;draft.value=next}
|
||||
function updateModelAssignments(value:Record<string,unknown>){draft.value={...clone(draft.value),model_assignments:value}}
|
||||
function updateRecognitionPrompts(value:Record<string,unknown>){draft.value={...clone(draft.value),recognition_prompts:value}}
|
||||
function updateChatAccess(value:Record<string,unknown>){draft.value={...clone(draft.value),chat_access:value}}
|
||||
function inputValue(e:Event,type:string):ConfigValue{const t=e.target as HTMLInputElement|HTMLSelectElement;if(type==="bool"||type==="boolean")return t.value==="true";if(type==="number")return t.value===""?null:Number(t.value);return t.value}
|
||||
</script>
|
||||
|
||||
<template><section class="settings-page">
|
||||
<header class="hero"><div><span>系统设置</span><h2>插件与生成服务</h2><p>集中管理 ImageStudio 的生成适配器、运行参数与功能配置。</p></div><div class="actions"><button @click="emit('refresh')">刷新配置</button><button :disabled="busy||!backendConnected||!canManage" @click="emit('reload')">重载配置</button></div></header>
|
||||
<section v-if="error||message" :class="['notice',{error:!!error}]">{{error||message}}</section>
|
||||
<section class="workspace"><aside class="nav"><header><span>设置导航</span><strong>{{effectiveSchema.sections.length}}</strong></header><button v-for="s in effectiveSchema.sections" :key="s.key" :class="{active:activeSection?.key===s.key}" @click="activeSectionKey=s.key"><span>{{s.title}}</span><small>{{s.key==='generation'?`${adapters.length} 个适配器`:s.key==='model_assignments'?'12 个功能节点':s.key==='recognition_prompts'?'分类识别要求':s.key==='backup'?'导入 / 导出':s.key==='review'?'规则管理':s.key==='capabilities'?'模型档案':s.key==='integration'?'凭据管理':s.key==='cost_guard'?'预算预检':s.key==='diagnostics'?'运行检查':`${s.fields.length} 项`}}</small></button></aside>
|
||||
<section class="workspace"><aside class="nav"><header><span>设置导航</span><strong>{{effectiveSchema.sections.length}}</strong></header><button v-for="s in effectiveSchema.sections" :key="s.key" :class="{active:activeSection?.key===s.key}" @click="activeSectionKey=s.key"><span>{{s.title}}</span><small>{{s.key==='generation'?`${adapters.length} 个适配器`:s.key==='model_assignments'?'12 个功能节点':s.key==='recognition_prompts'?'分类识别要求':s.key==='chat_access'?'群聊 / 用户':s.key==='backup'?'导入 / 导出':s.key==='review'?'规则管理':s.key==='capabilities'?'模型档案':s.key==='integration'?'凭据管理':s.key==='cost_guard'?'预算预检':s.key==='diagnostics'?'运行检查':`${s.fields.length} 项`}}</small></button></aside>
|
||||
<main class="editor">
|
||||
<template v-if="activeSection?.key==='generation'"><header class="section-head"><div><span>生成服务</span><h3>API 适配器</h3><p>每个服务独立配置,展开卡片后填写 API 信息。首张卡片作为当前默认生成路由。</p></div></header>
|
||||
<div class="adapter-list"><article v-for="(a,index) in adapters" :key="a.id" class="adapter-card" :class="{connected:a.enabled&&!!a.base_url,disabled:!a.enabled}"><button class="adapter-summary" @click="expandedAdapter=a.id"><span class="adapter-icon">{{a.name.slice(0,1).toUpperCase()}}</span><span class="adapter-title"><strong>{{a.name}}</strong><small>{{a.enabled?(a.base_url?'链接已配置':'等待配置'):'已停用'}}</small></span><em v-if="index===0">默认</em><span class="corner" aria-hidden="true"></span></button></article></div>
|
||||
|
|
@ -114,6 +117,7 @@ function inputValue(e:Event,type:string):ConfigValue{const t=e.target as HTMLInp
|
|||
<SystemManagementPanel v-else-if="activeSection?.key==='diagnostics'" mode="diagnostics" :backend-connected="backendConnected" :can-manage="canManage" />
|
||||
<ModelAssignmentsPanel v-else-if="activeSection?.key==='model_assignments'" :model-value="modelAssignments" :adapters="modelAdapterOptions" :vision-route="visionRouteOption" :disabled="backendConnected&&!canManage" @update:model-value="updateModelAssignments" />
|
||||
<RecognitionPromptsPanel v-else-if="activeSection?.key==='recognition_prompts'" :model-value="obj(draft.recognition_prompts)" :disabled="backendConnected&&!canManage" @update:model-value="updateRecognitionPrompts" />
|
||||
<ChatAccessPanel v-else-if="activeSection?.key==='chat_access'" :model-value="obj(draft.chat_access)" :disabled="backendConnected&&!canManage" @update:model-value="updateChatAccess" />
|
||||
<div v-else-if="activeSection?.key==='features'" class="feature-grid"><article v-for="f in activeSection.fields" :key="f.key" class="feature-card" :class="{enabled:fieldValue(fieldPath(f.key))===true}"><div class="feature-mark">{{f.label.slice(0,1)}}</div><div><strong>{{f.label}}</strong><p>{{featureDescription(f.key)}}</p></div><label class="toggle"><input type="checkbox" :checked="fieldValue(fieldPath(f.key))===true" @change="updateField(fieldPath(f.key),($event.target as HTMLInputElement).checked)"><span></span></label></article></div>
|
||||
<div v-else class="config-panel"><div class="config-banner"><div class="config-symbol">{{activeSection?.key==='storage'?'▣':'DB'}}</div><div><strong>{{activeSection?.key==='storage'?'存储目录规划':'数据库连接'}}</strong><p>{{activeSection?.key==='storage'?'支持相对插件数据目录或绝对路径,保存前请确保 AstrBot 进程具备写入权限。':'auto 会优先使用已配置的 PostgreSQL,否则回退到本地 SQLite。'}}</p></div></div><div class="fields"><label v-for="f in activeSection?.fields||[]" :key="f.key"><span>{{f.label}}</span><select v-if="f.options.length||f.type==='bool'||f.type==='boolean'" :value="String(fieldValue(fieldPath(f.key)))" @change="updateField(fieldPath(f.key),inputValue($event,f.type))"><option v-if="f.type==='bool'||f.type==='boolean'" value="true">开启</option><option v-if="f.type==='bool'||f.type==='boolean'" value="false">关闭</option><option v-for="o in f.options" :key="o" :value="o">{{o}}</option></select><input v-else :type="f.type==='number'?'number':f.sensitive?'password':'text'" :placeholder="f.type==='path'?'输入目录或文件路径':''" :value="fieldValue(fieldPath(f.key)) as any" @input="updateField(fieldPath(f.key),inputValue($event,f.type))"><small>{{fieldPath(f.key)}}</small></label></div><StorageMaintenance v-if="activeSection?.key==='storage'" :can-manage="canManage" :backend-connected="backendConnected" /></div>
|
||||
</template>
|
||||
|
|
|
|||
665
main.py
665
main.py
|
|
@ -13,6 +13,7 @@ import inspect
|
|||
import importlib
|
||||
import json
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Mapping
|
||||
|
||||
|
|
@ -30,6 +31,20 @@ from adapters.astrbot_adapter import (
|
|||
runtime_registration_manifest,
|
||||
runtime_route_table,
|
||||
)
|
||||
from adapters.astrbot_command_adapter import (
|
||||
accepted_text,
|
||||
access_denied_text,
|
||||
command_allowed,
|
||||
command_context_from_event,
|
||||
help_text,
|
||||
message_text_from_event,
|
||||
)
|
||||
from adapters.astrbot_card_renderer import render_help_card, render_profile_card, render_status_card
|
||||
from adapters.astrbot_command_parser import parse_single_image_command, single_image_usage
|
||||
from adapters.astrbot_media_adapter import image_references_from_event
|
||||
from backend.dto.chat_command_dto import ChatCommandParseError
|
||||
from backend.services.chat_workflow_service import ChatWorkflowService
|
||||
from backend.services.chat_session_service import ChatSessionStore
|
||||
from adapters.webui_adapter import get_web_mount_manifest
|
||||
from backend.route_registry import ROUTES
|
||||
from backend.services.model_provider_bootstrap import (
|
||||
|
|
@ -57,7 +72,7 @@ load_database_settings = _database_db_helper.load_database_settings
|
|||
|
||||
PLUGIN_NAME = "astrbot_plugin_imagestudio"
|
||||
PLUGIN_DESC = "AstrBot ImageStudio role asset production and image-generation workspace."
|
||||
PLUGIN_VERSION = "3.0.0"
|
||||
PLUGIN_VERSION = "3.1.0"
|
||||
BRIDGE_PERMISSIONS = frozenset(
|
||||
{"can_write", "can_manage_config", "can_manage_materials", "can_retry_tasks"}
|
||||
)
|
||||
|
|
@ -66,6 +81,10 @@ _MISSING = object()
|
|||
try:
|
||||
from astrbot.api.star import Star as AstrBotStar
|
||||
from astrbot.api.star import register as astrbot_star_register
|
||||
from astrbot.api.event import AstrMessageEvent, filter as astrbot_filter
|
||||
from astrbot.api.event import MessageChain as AstrBotMessageChain
|
||||
from astrbot.api.message_components import Image as AstrBotImage
|
||||
from astrbot.api.message_components import Plain as AstrBotPlain
|
||||
except Exception: # pragma: no cover - AstrBot is only present in runtime.
|
||||
class AstrBotStar: # type: ignore[no-redef]
|
||||
def __init__(self, context: Any | None = None, *args: Any, **kwargs: Any) -> None:
|
||||
|
|
@ -77,6 +96,33 @@ except Exception: # pragma: no cover - AstrBot is only present in runtime.
|
|||
|
||||
return decorator
|
||||
|
||||
AstrMessageEvent = Any # type: ignore[misc,assignment]
|
||||
AstrBotImage = None # type: ignore[assignment]
|
||||
AstrBotPlain = None # type: ignore[assignment]
|
||||
AstrBotMessageChain = None # type: ignore[assignment]
|
||||
|
||||
class _FallbackCommandGroup:
|
||||
def __call__(self, function: Callable[..., Any]) -> Callable[..., Any]:
|
||||
setattr(function, "command", self.command)
|
||||
return function
|
||||
|
||||
def command(self, *args: Any, **kwargs: Any) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
||||
return lambda function: function
|
||||
|
||||
class _FallbackFilter:
|
||||
class EventMessageType:
|
||||
ALL = "all"
|
||||
|
||||
@staticmethod
|
||||
def command_group(*args: Any, **kwargs: Any) -> _FallbackCommandGroup:
|
||||
return _FallbackCommandGroup()
|
||||
|
||||
@staticmethod
|
||||
def event_message_type(*args: Any, **kwargs: Any) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
||||
return lambda function: function
|
||||
|
||||
astrbot_filter = _FallbackFilter()
|
||||
|
||||
|
||||
def get_plugin_manifest() -> dict[str, Any]:
|
||||
web_manifest = get_web_mount_manifest()
|
||||
|
|
@ -226,6 +272,9 @@ class Main(AstrBotStar):
|
|||
self.registration_result: dict[str, Any] | None = None
|
||||
self.database_result: dict[str, Any] | None = None
|
||||
self.runtime_config_result: dict[str, Any] | None = None
|
||||
self.chat_workflow_service = ChatWorkflowService(dispatch_web_request)
|
||||
self.chat_sessions = ChatSessionStore(ttl_seconds=600, max_sessions=1000)
|
||||
self.chat_background_tasks: set[asyncio.Task[Any]] = set()
|
||||
|
||||
async def initialize(self) -> None:
|
||||
self.runtime_config_result = apply_astrbot_config_overrides(self.astrbot_config)
|
||||
|
|
@ -236,8 +285,595 @@ class Main(AstrBotStar):
|
|||
return None
|
||||
|
||||
async def terminate(self) -> None:
|
||||
for task in list(self.chat_background_tasks):
|
||||
task.cancel()
|
||||
if self.chat_background_tasks:
|
||||
await asyncio.gather(*self.chat_background_tasks, return_exceptions=True)
|
||||
return None
|
||||
|
||||
@astrbot_filter.command_group("影棚")
|
||||
def imagestudio_command(self) -> None:
|
||||
"""ImageStudio chat command group."""
|
||||
return None
|
||||
|
||||
@imagestudio_command.command("帮助")
|
||||
async def imagestudio_help(self, event: AstrMessageEvent):
|
||||
yield self._card_result(event, self._help_card, help_text())
|
||||
|
||||
@imagestudio_command.command("状态")
|
||||
async def imagestudio_status(self, event: AstrMessageEvent):
|
||||
health = get_runtime_health()
|
||||
state = "正常" if health.get("healthy") is not False else "异常"
|
||||
database = "已初始化" if self.database_result else "等待初始化"
|
||||
text = f"🛰 ImageStudio 状态:{state}\n版本:{PLUGIN_VERSION}\nAPI:{API_BASE}\n数据库:{database}"
|
||||
yield self._card_result(event, lambda: render_status_card(state=state, version=PLUGIN_VERSION, database=database, api=API_BASE), text)
|
||||
|
||||
@imagestudio_command.command("快速角色")
|
||||
async def imagestudio_quick_profile(self, event: AstrMessageEvent, description: str = ""):
|
||||
context = command_context_from_event(event)
|
||||
config = _database_db_helper.load_config_payload()
|
||||
if not command_allowed(config, "quick_profile", context):
|
||||
self._record_chat_denied(context, "quick_profile")
|
||||
yield event.plain_result(access_denied_text("快速角色", context))
|
||||
return
|
||||
try:
|
||||
draft = await asyncio.to_thread(self.chat_workflow_service.create_quick_profile_draft, description, context)
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 快速角色草稿创建失败:{exc}")
|
||||
return
|
||||
self.chat_sessions.put(self._session_key(context), "confirm_quick_profile", {"draft": draft})
|
||||
preview = draft.get("profile_preview", {})
|
||||
text = (
|
||||
f"🧩 快速角色草稿\n\n名称:{preview.get('name')}\n基础:{preview.get('base_prompt') or '—'}\n"
|
||||
f"外观:{preview.get('appearance_prompt') or '—'}\n风格:{preview.get('style_prompt') or '—'}\n\n"
|
||||
"发送 /yp 确认 保存,或 /yp 放弃 取消。"
|
||||
)
|
||||
yield self._card_result(
|
||||
event,
|
||||
lambda: render_profile_card(
|
||||
name=str(preview.get("name") or ""), base=str(preview.get("base_prompt") or ""),
|
||||
appearance=str(preview.get("appearance_prompt") or ""), style=str(preview.get("style_prompt") or ""),
|
||||
),
|
||||
text,
|
||||
)
|
||||
|
||||
@imagestudio_command.command("工作流")
|
||||
async def imagestudio_workflow(self, event: AstrMessageEvent, profile: str = ""):
|
||||
context = command_context_from_event(event)
|
||||
config = _database_db_helper.load_config_payload()
|
||||
if not command_allowed(config, "character_workflow", context):
|
||||
self._record_chat_denied(context, "character_workflow")
|
||||
yield event.plain_result(access_denied_text("角色工作流", context))
|
||||
return
|
||||
try:
|
||||
detail = await asyncio.to_thread(self.chat_workflow_service.create_or_resume_character_workflow, profile, context)
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 工作流创建失败:{exc}")
|
||||
return
|
||||
yield event.plain_result(self._format_workflow(detail))
|
||||
|
||||
@imagestudio_command.command("确认")
|
||||
async def imagestudio_confirm(self, event: AstrMessageEvent):
|
||||
context = command_context_from_event(event)
|
||||
session = self.chat_sessions.pop(self._session_key(context))
|
||||
if session is None:
|
||||
yield event.plain_result("当前没有等待确认的 ImageStudio 操作。")
|
||||
return
|
||||
if session.action == "confirm_quick_profile":
|
||||
try:
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.save_quick_profile_draft, session.payload["draft"], context)
|
||||
nodes = result.get("nodes", [])
|
||||
if nodes:
|
||||
self.chat_sessions.put(self._session_key(context), "quick_profile_ready", {"node_id": nodes[0]["node_id"]})
|
||||
yield event.plain_result(f"✅ 快速角色已保存\n角色:{result['profile']['name']}\nID:{result['profile']['profile_id']}\n工作流:{result.get('workflow', {}).get('workflow_id', '—')}")
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 保存失败:{exc}")
|
||||
return
|
||||
if session.action == "confirm_materials":
|
||||
confirmed = []
|
||||
try:
|
||||
for material_id in session.payload["material_ids"]:
|
||||
confirmed.append(await asyncio.to_thread(self.chat_workflow_service.confirm_material, material_id, context))
|
||||
yield event.plain_result("✅ 素材已确认:" + "、".join(item["material_id"] for item in confirmed))
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 素材确认失败:{exc}")
|
||||
return
|
||||
if session.action == "confirm_material":
|
||||
try:
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.confirm_material, session.payload["material_id"], context)
|
||||
yield event.plain_result(f"✅ 素材已确认:{result['material_id']}")
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 素材确认失败:{exc}")
|
||||
return
|
||||
yield event.plain_result("该会话暂不支持确认。")
|
||||
|
||||
@imagestudio_command.command("放弃")
|
||||
async def imagestudio_discard(self, event: AstrMessageEvent):
|
||||
session = self.chat_sessions.pop(self._session_key(command_context_from_event(event)))
|
||||
yield event.plain_result("已取消当前操作。" if session else "当前没有待取消的操作。")
|
||||
|
||||
@imagestudio_command.command("修改")
|
||||
async def imagestudio_modify_draft(self, event: AstrMessageEvent, addition: str = ""):
|
||||
context = command_context_from_event(event)
|
||||
session = self.chat_sessions.get(self._session_key(context))
|
||||
if session is None or session.action != "confirm_quick_profile":
|
||||
yield event.plain_result("当前没有等待修改的快速角色草稿。")
|
||||
return
|
||||
preview = session.payload["draft"].get("profile_preview", {})
|
||||
description = f"{preview.get('name', '')} {preview.get('base_prompt', '')} {addition}".strip()
|
||||
try:
|
||||
draft = await asyncio.to_thread(self.chat_workflow_service.create_quick_profile_draft, description, context)
|
||||
self.chat_sessions.put(self._session_key(context), "confirm_quick_profile", {"draft": draft})
|
||||
updated = draft.get("profile_preview", {})
|
||||
yield event.plain_result(f"📝 草稿已更新\n名称:{updated.get('name')}\n设定:{updated.get('base_prompt')}\n发送 /yp 确认 保存。")
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 修改失败:{exc}")
|
||||
|
||||
@imagestudio_command.command("节点")
|
||||
async def imagestudio_nodes(self, event: AstrMessageEvent, workflow_id: str = ""):
|
||||
try:
|
||||
detail = await asyncio.to_thread(self.chat_workflow_service.workflow_detail, workflow_id.strip(), command_context_from_event(event))
|
||||
yield event.plain_result(self._format_workflow(detail))
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 节点查询失败:{exc}")
|
||||
|
||||
@imagestudio_command.command("生成")
|
||||
async def imagestudio_generate_node(self, event: AstrMessageEvent, node_id: str = ""):
|
||||
context = command_context_from_event(event)
|
||||
try:
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.generate_node, node_id.strip(), context)
|
||||
images = result.get("images", [])
|
||||
if images:
|
||||
self.chat_sessions.put(self._session_key(context), "select_image", {"node_id": node_id.strip(), "image_ids": [item["image_id"] for item in images]})
|
||||
yield self._generation_result(event, f"✅ 节点生成完成\n节点:{node_id}\n任务:{result.get('task_id') or result.get('request_id') or '—'}\n回复数字选图,或使用 /yp 选择 <序号>。", images)
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 节点生成失败:{exc}")
|
||||
|
||||
@imagestudio_command.command("重试节点")
|
||||
async def imagestudio_retry_node(self, event: AstrMessageEvent, node_id: str = ""):
|
||||
try:
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.retry_node, node_id.strip(), command_context_from_event(event))
|
||||
yield event.plain_result(f"✅ 节点已重试:{result.get('task_id') or node_id}")
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 节点重试失败:{exc}")
|
||||
|
||||
@imagestudio_command.command("完成节点")
|
||||
async def imagestudio_complete_node(self, event: AstrMessageEvent, node_id: str = ""):
|
||||
try:
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.complete_node, node_id.strip(), command_context_from_event(event))
|
||||
yield event.plain_result(f"✅ 节点已完成:{result.get('node_id', node_id)}")
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 完成节点失败:{exc}")
|
||||
|
||||
@imagestudio_command.command("下一步")
|
||||
async def imagestudio_next_step(self, event: AstrMessageEvent, workflow_id: str = ""):
|
||||
try:
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.next_workflow_step, workflow_id.strip(), command_context_from_event(event))
|
||||
if result.get("completed"):
|
||||
yield event.plain_result(f"✅ 工作流已没有待执行节点:{workflow_id}")
|
||||
else:
|
||||
yield event.plain_result(f"✅ 已执行下一节点\n节点:{result['node']['node_id']}\n任务:{result['generation'].get('task_id') or '—'}")
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 下一步执行失败:{exc}")
|
||||
|
||||
@imagestudio_command.command("选图")
|
||||
async def imagestudio_select_image(self, event: AstrMessageEvent, node_id: str = "", image_id: str = ""):
|
||||
try:
|
||||
if image_id.strip().isdigit():
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.select_node_image_by_number, node_id.strip(), int(image_id), command_context_from_event(event))
|
||||
else:
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.select_node_image, node_id.strip(), image_id.strip(), command_context_from_event(event))
|
||||
yield event.plain_result(f"✅ 已选择图片:{result.get('image_id', image_id)}")
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 选图失败:{exc}")
|
||||
|
||||
@imagestudio_command.command("候选图")
|
||||
async def imagestudio_candidate_images(self, event: AstrMessageEvent, node_id: str = ""):
|
||||
context = command_context_from_event(event)
|
||||
try:
|
||||
images = await asyncio.to_thread(self.chat_workflow_service.list_node_images, node_id.strip(), context)
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 候选图读取失败:{exc}")
|
||||
return
|
||||
if not images:
|
||||
yield event.plain_result("当前节点没有候选图。")
|
||||
return
|
||||
self.chat_sessions.put(
|
||||
self._session_key(context),
|
||||
"select_image",
|
||||
{"node_id": node_id.strip(), "image_ids": [item["image_id"] for item in images]},
|
||||
)
|
||||
yield self._generation_result(event, "回复 /yp 选择 1 采用第一张候选图。", images)
|
||||
|
||||
@imagestudio_command.command("选择")
|
||||
async def imagestudio_choose_candidate(self, event: AstrMessageEvent, number: str = ""):
|
||||
context = command_context_from_event(event)
|
||||
session = self.chat_sessions.get(self._session_key(context))
|
||||
if session is None or session.action != "select_image":
|
||||
yield event.plain_result("当前没有等待选择的候选图。")
|
||||
return
|
||||
try:
|
||||
index = int(number) - 1
|
||||
image_id = session.payload["image_ids"][index]
|
||||
result = await asyncio.to_thread(
|
||||
self.chat_workflow_service.select_node_image,
|
||||
session.payload["node_id"],
|
||||
image_id,
|
||||
context,
|
||||
)
|
||||
self.chat_sessions.pop(self._session_key(context))
|
||||
yield event.plain_result(f"✅ 已采用第 {index + 1} 张:{result.get('image_id', image_id)}\n可继续使用 /yp 下一步、/yp 重试节点 或 /yp 审核。")
|
||||
except (ValueError, IndexError):
|
||||
yield event.plain_result(f"请输入 1 到 {len(session.payload['image_ids'])} 之间的序号。")
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 选图失败:{exc}")
|
||||
|
||||
@imagestudio_command.command("审核")
|
||||
async def imagestudio_review(self, event: AstrMessageEvent, target_id: str = ""):
|
||||
try:
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.review, target_id.strip(), command_context_from_event(event))
|
||||
yield event.plain_result("🔎 审核结果\n" + json.dumps(result, ensure_ascii=False, indent=2)[:3000])
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 审核失败:{exc}")
|
||||
|
||||
@imagestudio_command.command("高清")
|
||||
async def imagestudio_hires(self, event: AstrMessageEvent, image_id: str = "", size: str = "2K"):
|
||||
normalized_size = {"1K": "1920x1080", "2K": "2560x1440", "4K": "3840x2160"}.get(size.upper())
|
||||
if not image_id.strip() or normalized_size is None:
|
||||
yield event.plain_result("用法:/yp 高清 <image_id> 2K|4K")
|
||||
return
|
||||
try:
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.hires_fix, image_id.strip(), normalized_size, command_context_from_event(event))
|
||||
yield self._generation_result(event, f"✅ 高清修复完成\n原图:{image_id}\n尺寸:{normalized_size}", result.get("images", []))
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 高清修复失败:{exc}")
|
||||
|
||||
@imagestudio_command.command("素材导入")
|
||||
async def imagestudio_import_material(self, event: AstrMessageEvent, category: str = ""):
|
||||
references = image_references_from_event(event)
|
||||
if not category.strip() or not references:
|
||||
yield event.plain_result("用法:发送图片并附带 /yp 素材导入 <现有分类名称或ID>")
|
||||
return
|
||||
context = command_context_from_event(event)
|
||||
try:
|
||||
results = [await asyncio.to_thread(self.chat_workflow_service.import_material, reference, category.strip(), context) for reference in references]
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 素材导入或识别失败:{exc}")
|
||||
return
|
||||
material = results[0]["material"]
|
||||
material_ids = [item["material"]["material_id"] for item in results]
|
||||
profile_names = [item.get("name") for item in results[0].get("profiles", []) if item.get("name")]
|
||||
self.chat_sessions.put(self._session_key(context), "confirm_materials", {"material_ids": material_ids})
|
||||
yield event.plain_result(
|
||||
f"🧵 已识别 {len(results)} 个素材\nID:{'、'.join(material_ids)}\n分类:{results[0]['category']['name']}\n"
|
||||
f"提示词:{material.get('prompt') or '—'}\n标签:{'、'.join(material.get('tags') or [])}\n\n"
|
||||
f"可用角色:{'、'.join(profile_names[:10]) or '暂无'}\n\n发送 /yp 确认 保存素材,或 /yp 放弃 取消。"
|
||||
)
|
||||
|
||||
@imagestudio_command.command("重新识别")
|
||||
async def imagestudio_re_recognize_material(self, event: AstrMessageEvent, material_id: str = ""):
|
||||
try:
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.re_recognize_material, material_id.strip(), command_context_from_event(event))
|
||||
yield event.plain_result(f"✅ 素材已重新识别\nID:{result['material_id']}\n提示词:{result.get('prompt') or '—'}")
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 重新识别失败:{exc}")
|
||||
|
||||
@imagestudio_command.command("加入衣橱")
|
||||
async def imagestudio_add_wardrobe(self, event: AstrMessageEvent, material_id: str = "", profile: str = "", category: str = "top"):
|
||||
try:
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.add_material_to_wardrobe, material_id.strip(), profile.strip(), category.strip(), command_context_from_event(event))
|
||||
yield event.plain_result(f"✅ 素材已加入角色衣橱:{result.get('wardrobe_item_id') or material_id}")
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 加入衣橱失败:{exc}")
|
||||
|
||||
@imagestudio_command.command("单图")
|
||||
async def imagestudio_single_image(self, event: AstrMessageEvent, prompt: str = ""):
|
||||
context = command_context_from_event(event)
|
||||
config = _database_db_helper.load_config_payload()
|
||||
if not command_allowed(config, "single_image", context):
|
||||
self._record_chat_denied(context, "single_image")
|
||||
yield event.plain_result(access_denied_text("单图生成", context))
|
||||
return
|
||||
try:
|
||||
command = parse_single_image_command(prompt)
|
||||
except ChatCommandParseError as exc:
|
||||
yield event.plain_result(single_image_usage(str(exc)))
|
||||
return
|
||||
request_id = f"chatreq_{uuid4().hex}"
|
||||
task = asyncio.create_task(self._run_single_image_background(command, context, request_id))
|
||||
self.chat_background_tasks.add(task)
|
||||
task.add_done_callback(self.chat_background_tasks.discard)
|
||||
yield event.plain_result(
|
||||
"✅ 单图请求已进入后台执行\n\n"
|
||||
f"请求:{request_id}\n尺寸:{command.size}\n数量:{command.count}\n"
|
||||
f"模型:{command.model_route or 'quick_generation'}\n\n生成完成后会自动发送到当前会话。"
|
||||
)
|
||||
|
||||
@imagestudio_command.command("任务")
|
||||
async def imagestudio_jobs(self, event: AstrMessageEvent, task_id: str = ""):
|
||||
context = command_context_from_event(event)
|
||||
try:
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.list_jobs, context, task_id=task_id.strip() or None)
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 任务查询失败:{exc}")
|
||||
return
|
||||
yield event.plain_result(self._format_jobs(result))
|
||||
|
||||
@imagestudio_command.command("取消")
|
||||
async def imagestudio_cancel_job(self, event: AstrMessageEvent, task_id: str = ""):
|
||||
if not task_id.strip():
|
||||
yield event.plain_result("请提供任务 ID,例如:/yp 取消 task_xxx")
|
||||
return
|
||||
try:
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.cancel_job, command_context_from_event(event), task_id.strip())
|
||||
yield event.plain_result(f"✅ 任务已取消:{result.get('task_id', task_id)}")
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 取消失败:{exc}")
|
||||
|
||||
@imagestudio_command.command("重试")
|
||||
async def imagestudio_retry_job(self, event: AstrMessageEvent, task_id: str = ""):
|
||||
if not task_id.strip():
|
||||
yield event.plain_result("请提供任务 ID,例如:/yp 重试 task_xxx")
|
||||
return
|
||||
try:
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.retry_job, command_context_from_event(event), task_id.strip())
|
||||
yield event.plain_result(f"✅ 已创建重试任务:{result.get('task_id', task_id)}")
|
||||
except Exception as exc:
|
||||
yield event.plain_result(f"❌ 重试失败:{exc}")
|
||||
|
||||
async def _chat_command_result(self, event: AstrMessageEvent, action: str, label: str, argument: str):
|
||||
context = command_context_from_event(event)
|
||||
config = _database_db_helper.load_config_payload()
|
||||
if not command_allowed(config, action, context):
|
||||
yield event.plain_result(access_denied_text(label, context))
|
||||
return
|
||||
yield event.plain_result(accepted_text(label, argument, context))
|
||||
|
||||
@astrbot_filter.event_message_type(astrbot_filter.EventMessageType.ALL)
|
||||
async def imagestudio_session_reply(self, event: AstrMessageEvent):
|
||||
text = message_text_from_event(event)
|
||||
if not text or text.startswith(("/", "!", "!")):
|
||||
return
|
||||
context = command_context_from_event(event)
|
||||
session = self.chat_sessions.get(self._session_key(context))
|
||||
if session is None:
|
||||
return
|
||||
normalized = text.strip().lower()
|
||||
if normalized in {"取消", "退出", "放弃", "cancel"}:
|
||||
self.chat_sessions.pop(self._session_key(context))
|
||||
yield event.plain_result("已取消当前 ImageStudio 会话。")
|
||||
return
|
||||
if normalized in {"确认", "保存", "confirm"}:
|
||||
async for result in self.imagestudio_confirm(event):
|
||||
yield result
|
||||
return
|
||||
if session.action == "select_image" and normalized.isdigit():
|
||||
async for result in self.imagestudio_choose_candidate(event, normalized):
|
||||
yield result
|
||||
return
|
||||
if session.action == "quick_profile_ready" and normalized in {"生成", "开始", "generate"}:
|
||||
self.chat_sessions.pop(self._session_key(context))
|
||||
async for result in self.imagestudio_generate_node(event, session.payload["node_id"]):
|
||||
yield result
|
||||
|
||||
@astrbot_filter.command_group("yp")
|
||||
def imagestudio_short_command(self) -> None:
|
||||
"""Short alias for the ImageStudio command group."""
|
||||
return None
|
||||
|
||||
@imagestudio_short_command.command("帮助")
|
||||
async def imagestudio_short_help(self, event: AstrMessageEvent):
|
||||
async for result in self.imagestudio_help(event):
|
||||
yield result
|
||||
|
||||
@imagestudio_short_command.command("状态")
|
||||
async def imagestudio_short_status(self, event: AstrMessageEvent):
|
||||
async for result in self.imagestudio_status(event):
|
||||
yield result
|
||||
|
||||
@imagestudio_short_command.command("快速角色")
|
||||
async def imagestudio_short_quick_profile(self, event: AstrMessageEvent, description: str = ""):
|
||||
async for result in self.imagestudio_quick_profile(event, description):
|
||||
yield result
|
||||
|
||||
@imagestudio_short_command.command("工作流")
|
||||
async def imagestudio_short_workflow(self, event: AstrMessageEvent, profile: str = ""):
|
||||
async for result in self.imagestudio_workflow(event, profile):
|
||||
yield result
|
||||
|
||||
@imagestudio_short_command.command("单图")
|
||||
async def imagestudio_short_single_image(self, event: AstrMessageEvent, prompt: str = ""):
|
||||
async for result in self.imagestudio_single_image(event, prompt):
|
||||
yield result
|
||||
|
||||
@imagestudio_short_command.command("任务")
|
||||
async def imagestudio_short_jobs(self, event: AstrMessageEvent, task_id: str = ""):
|
||||
async for result in self.imagestudio_jobs(event, task_id):
|
||||
yield result
|
||||
|
||||
@imagestudio_short_command.command("取消")
|
||||
async def imagestudio_short_cancel_job(self, event: AstrMessageEvent, task_id: str = ""):
|
||||
async for result in self.imagestudio_cancel_job(event, task_id):
|
||||
yield result
|
||||
|
||||
@imagestudio_short_command.command("重试")
|
||||
async def imagestudio_short_retry_job(self, event: AstrMessageEvent, task_id: str = ""):
|
||||
async for result in self.imagestudio_retry_job(event, task_id):
|
||||
yield result
|
||||
|
||||
@imagestudio_short_command.command("确认")
|
||||
async def imagestudio_short_confirm(self, event: AstrMessageEvent):
|
||||
async for result in self.imagestudio_confirm(event): yield result
|
||||
|
||||
@imagestudio_short_command.command("放弃")
|
||||
async def imagestudio_short_discard(self, event: AstrMessageEvent):
|
||||
async for result in self.imagestudio_discard(event): yield result
|
||||
|
||||
@imagestudio_short_command.command("修改")
|
||||
async def imagestudio_short_modify_draft(self, event: AstrMessageEvent, addition: str = ""):
|
||||
async for result in self.imagestudio_modify_draft(event, addition): yield result
|
||||
|
||||
@imagestudio_short_command.command("节点")
|
||||
async def imagestudio_short_nodes(self, event: AstrMessageEvent, workflow_id: str = ""):
|
||||
async for result in self.imagestudio_nodes(event, workflow_id): yield result
|
||||
|
||||
@imagestudio_short_command.command("生成")
|
||||
async def imagestudio_short_generate_node(self, event: AstrMessageEvent, node_id: str = ""):
|
||||
async for result in self.imagestudio_generate_node(event, node_id): yield result
|
||||
|
||||
@imagestudio_short_command.command("重试节点")
|
||||
async def imagestudio_short_retry_node(self, event: AstrMessageEvent, node_id: str = ""):
|
||||
async for result in self.imagestudio_retry_node(event, node_id): yield result
|
||||
|
||||
@imagestudio_short_command.command("完成节点")
|
||||
async def imagestudio_short_complete_node(self, event: AstrMessageEvent, node_id: str = ""):
|
||||
async for result in self.imagestudio_complete_node(event, node_id): yield result
|
||||
|
||||
@imagestudio_short_command.command("下一步")
|
||||
async def imagestudio_short_next_step(self, event: AstrMessageEvent, workflow_id: str = ""):
|
||||
async for result in self.imagestudio_next_step(event, workflow_id): yield result
|
||||
|
||||
@imagestudio_short_command.command("选图")
|
||||
async def imagestudio_short_select_image(self, event: AstrMessageEvent, node_id: str = "", image_id: str = ""):
|
||||
async for result in self.imagestudio_select_image(event, node_id, image_id): yield result
|
||||
|
||||
@imagestudio_short_command.command("审核")
|
||||
async def imagestudio_short_review(self, event: AstrMessageEvent, target_id: str = ""):
|
||||
async for result in self.imagestudio_review(event, target_id): yield result
|
||||
|
||||
@imagestudio_short_command.command("高清")
|
||||
async def imagestudio_short_hires(self, event: AstrMessageEvent, image_id: str = "", size: str = "2K"):
|
||||
async for result in self.imagestudio_hires(event, image_id, size): yield result
|
||||
|
||||
@imagestudio_short_command.command("素材导入")
|
||||
async def imagestudio_short_import_material(self, event: AstrMessageEvent, category: str = ""):
|
||||
async for result in self.imagestudio_import_material(event, category): yield result
|
||||
|
||||
@imagestudio_short_command.command("重新识别")
|
||||
async def imagestudio_short_re_recognize_material(self, event: AstrMessageEvent, material_id: str = ""):
|
||||
async for result in self.imagestudio_re_recognize_material(event, material_id): yield result
|
||||
|
||||
@imagestudio_short_command.command("加入衣橱")
|
||||
async def imagestudio_short_add_wardrobe(self, event: AstrMessageEvent, material_id: str = "", profile: str = "", category: str = "top"):
|
||||
async for result in self.imagestudio_add_wardrobe(event, material_id, profile, category): yield result
|
||||
|
||||
@imagestudio_short_command.command("候选图")
|
||||
async def imagestudio_short_candidate_images(self, event: AstrMessageEvent, node_id: str = ""):
|
||||
async for result in self.imagestudio_candidate_images(event, node_id): yield result
|
||||
|
||||
@imagestudio_short_command.command("选择")
|
||||
async def imagestudio_short_choose_candidate(self, event: AstrMessageEvent, number: str = ""):
|
||||
async for result in self.imagestudio_choose_candidate(event, number): yield result
|
||||
|
||||
@staticmethod
|
||||
def _format_jobs(result: Any) -> str:
|
||||
if isinstance(result, dict) and "task_id" in result:
|
||||
request = result.get("request") if isinstance(result.get("request"), dict) else {}
|
||||
return (
|
||||
f"📋 任务 {result['task_id']}\n状态:{result.get('status', 'unknown')}\n"
|
||||
f"进度:{result.get('progress', 0)}%\n模型:{result.get('model_route') or '—'}\n"
|
||||
f"尺寸:{request.get('size') or '—'}\n数量:{request.get('count') or '—'}\n"
|
||||
f"节点:{result.get('node_id') or '—'}\n创建:{result.get('created_at') or '—'}"
|
||||
)
|
||||
items = result.get("items", []) if isinstance(result, dict) else result if isinstance(result, list) else []
|
||||
if not items:
|
||||
return "当前没有任务。"
|
||||
lines = ["📋 最近任务"]
|
||||
for item in items[:10]:
|
||||
request = item.get("request") if isinstance(item.get("request"), dict) else {}
|
||||
lines.append(f"• {item.get('task_id')} · {item.get('status')} · {item.get('progress', 0)}% · {request.get('size') or '默认尺寸'} · {item.get('model_route') or '默认模型'}")
|
||||
return "\n".join(lines)
|
||||
|
||||
@staticmethod
|
||||
def _session_key(context: Any) -> str:
|
||||
return f"{context.platform}:{context.message_origin}:{context.user_id}"
|
||||
|
||||
@staticmethod
|
||||
def _format_workflow(detail: dict[str, Any]) -> str:
|
||||
workflow = detail.get("workflow", detail)
|
||||
nodes = detail.get("nodes", [])
|
||||
lines = [f"📋 {detail.get('profile', {}).get('name', '角色')} 工作流", f"ID:{workflow.get('workflow_id')}", f"状态:{workflow.get('status')}"]
|
||||
for node in nodes:
|
||||
marker = "▶" if node.get("node_id") == workflow.get("current_node_id") else "✅" if node.get("status") == "completed" else "○"
|
||||
lines.append(f"{marker} {node.get('display_name') or node.get('node_key')} · {node.get('status')}")
|
||||
return "\n".join(lines)
|
||||
|
||||
def _help_card(self) -> Path:
|
||||
return render_help_card([
|
||||
"/影棚 帮助 /yp 帮助",
|
||||
"/影棚 状态 /yp 状态",
|
||||
"/影棚 快速角色 <角色描述>",
|
||||
"/影棚 工作流 <角色名或 ID>",
|
||||
"/影棚 单图 <提示词>",
|
||||
])
|
||||
|
||||
def _card_result(self, event: AstrMessageEvent, renderer: Callable[[], Path], fallback: str):
|
||||
if AstrBotImage is not None and hasattr(event, "chain_result"):
|
||||
try:
|
||||
return event.chain_result([AstrBotImage.fromFileSystem(str(renderer()))])
|
||||
except Exception:
|
||||
pass
|
||||
return event.plain_result(fallback)
|
||||
|
||||
def _generation_result(self, event: AstrMessageEvent, text: str, images: list[dict[str, Any]]):
|
||||
if AstrBotImage is not None and AstrBotPlain is not None and hasattr(event, "chain_result"):
|
||||
try:
|
||||
chain: list[Any] = [AstrBotPlain(text)]
|
||||
for index, item in enumerate(images, 1):
|
||||
url = item.get("image_url") or item.get("thumbnail_url")
|
||||
if url:
|
||||
chain.extend([AstrBotPlain(f"\n候选图 {index}\n"), AstrBotImage.fromURL(str(url))])
|
||||
if len(chain) > 1:
|
||||
return event.chain_result(chain)
|
||||
except Exception:
|
||||
pass
|
||||
suffix = "".join(
|
||||
f"\n候选图 {index}:{item.get('image_url') or item.get('image_id')}"
|
||||
for index, item in enumerate(images, 1)
|
||||
)
|
||||
return event.plain_result(text + suffix)
|
||||
|
||||
async def _run_single_image_background(self, command: Any, context: Any, request_id: str) -> None:
|
||||
try:
|
||||
result = await asyncio.to_thread(self.chat_workflow_service.submit_single_image, command, context)
|
||||
generation = result["generation"]
|
||||
text = (
|
||||
f"✅ 单图生成完成\n请求:{request_id}\n任务:{generation.get('task_id') or '—'}\n"
|
||||
f"工作流:{result['workflow']['workflow_id']}\n节点:{result['node']['node_id']}"
|
||||
)
|
||||
await self._send_proactive(context.message_origin, text, result.get("images", []))
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
await self._send_proactive(context.message_origin, f"❌ 单图生成失败\n请求:{request_id}\n错误:{exc}", [])
|
||||
|
||||
async def _send_proactive(self, message_origin: str, text: str, images: list[dict[str, Any]]) -> None:
|
||||
sender = getattr(self.context, "send_message", None)
|
||||
if not callable(sender) or not message_origin:
|
||||
return
|
||||
try:
|
||||
components: list[Any] = []
|
||||
if AstrBotPlain is not None:
|
||||
components.append(AstrBotPlain(text))
|
||||
for index, item in enumerate(images, 1):
|
||||
url = item.get("image_url") or item.get("thumbnail_url")
|
||||
if url and AstrBotImage is not None:
|
||||
if AstrBotPlain is not None:
|
||||
components.append(AstrBotPlain(f"\n候选图 {index}\n"))
|
||||
components.append(AstrBotImage.fromURL(str(url)))
|
||||
message = AstrBotMessageChain(components) if AstrBotMessageChain is not None else components
|
||||
result = sender(message_origin, message)
|
||||
if inspect.isawaitable(result):
|
||||
await result
|
||||
except Exception:
|
||||
return
|
||||
|
||||
def _record_chat_denied(self, context: Any, action: str) -> None:
|
||||
try:
|
||||
self.chat_workflow_service.guard.record(context, action, allowed=False, details={"reason": "allowlist"})
|
||||
except Exception:
|
||||
return
|
||||
|
||||
def get_plugin_manifest(self) -> dict[str, Any]:
|
||||
return get_plugin_manifest()
|
||||
|
||||
|
|
@ -303,6 +939,14 @@ def _mapping_from_runtime_config(config: Any | None) -> dict[str, Any]:
|
|||
"model_fullbody_generation",
|
||||
"model_sheet_generation",
|
||||
"model_hires_fix",
|
||||
"chat_group_allowlist",
|
||||
"chat_user_allowlist",
|
||||
"chat_user_concurrency_limit",
|
||||
"chat_group_concurrency_limit",
|
||||
"chat_daily_user_generation_limit",
|
||||
"chat_daily_group_generation_limit",
|
||||
"chat_allow_2k",
|
||||
"chat_allow_4k",
|
||||
"enable_private_companion_integration",
|
||||
"database_backend",
|
||||
"sqlite_path",
|
||||
|
|
@ -456,6 +1100,25 @@ def _runtime_config_patch_from_mapping(mapping: Mapping[str, Any]) -> dict[str,
|
|||
if value:
|
||||
_set_nested(patch, ("model_assignments", target_key), value)
|
||||
|
||||
for target_key, source_key in {
|
||||
"group_allowlist": "chat_group_allowlist",
|
||||
"user_allowlist": "chat_user_allowlist",
|
||||
}.items():
|
||||
value = _runtime_value(mapping, source_key)
|
||||
if isinstance(value, (list, tuple, set, frozenset)):
|
||||
_set_nested(patch, ("chat_access", target_key), [str(item).strip() for item in value if str(item).strip()])
|
||||
for target_key, source_key in {
|
||||
"user_concurrency_limit": "chat_user_concurrency_limit",
|
||||
"group_concurrency_limit": "chat_group_concurrency_limit",
|
||||
"daily_user_generation_limit": "chat_daily_user_generation_limit",
|
||||
"daily_group_generation_limit": "chat_daily_group_generation_limit",
|
||||
"allow_2k": "chat_allow_2k",
|
||||
"allow_4k": "chat_allow_4k",
|
||||
}.items():
|
||||
value = _runtime_value(mapping, source_key)
|
||||
if value is not None:
|
||||
_set_nested(patch, ("chat_access", target_key), value)
|
||||
|
||||
private_companion = _runtime_value(
|
||||
mapping,
|
||||
"enable_private_companion_integration",
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ name: astrbot_plugin_imagestudio
|
|||
display_name: ImageStudio
|
||||
desc: AstrBot >=4.25 ImageStudio role asset and image-generation workspace for Windows, Linux, macOS and Docker.
|
||||
short_desc: AstrBot 内的角色资产、工作流与图片生成管理工作台。
|
||||
version: 3.0.0
|
||||
version: 3.1.0
|
||||
author: YokiiroBW
|
||||
repo: "http://192.168.31.210:18085/YokiiroBW/astrbot_plugin_imagestudio"
|
||||
astrbot_version: ">=4.25.0,<5"
|
||||
|
|
|
|||
文件差异因一行或多行过长而隐藏
文件差异因一行或多行过长而隐藏
文件差异因一行或多行过长而隐藏
文件差异因一行或多行过长而隐藏
|
|
@ -4,8 +4,8 @@
|
|||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>AstrBot ImageStudio</title>
|
||||
<script type="module" crossorigin src="./assets/index-S8PI1-k-.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="./assets/index-DoRMtpTr.css">
|
||||
<script type="module" crossorigin src="./assets/index-zEvRFDXh.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="./assets/index-Ccb1kxoS.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
# 默认 SQLite 模式只使用 Python 标准库,不需要额外运行依赖。
|
||||
# 帮助/状态图片卡片会在运行环境已有 Pillow 时启用;未安装时自动回退文字。
|
||||
# 为保持插件默认零依赖,不在这里强制安装 Pillow。
|
||||
#
|
||||
# PostgreSQL 是可选后端。不要取消下面两行的注释并同时安装两套驱动;
|
||||
# 需要 PG 时由管理员任选其一安装,避免所有 SQLite 用户被强制安装二进制依赖:
|
||||
|
|
|
|||
|
|
@ -0,0 +1,13 @@
|
|||
from adapters.astrbot_card_renderer import render_help_card, render_status_card
|
||||
import pytest
|
||||
|
||||
|
||||
def test_help_and_status_cards_render_png(tmp_path, monkeypatch):
|
||||
pytest.importorskip("PIL")
|
||||
import adapters.astrbot_card_renderer as renderer
|
||||
|
||||
monkeypatch.setattr(renderer, "CARD_DIR", tmp_path)
|
||||
help_card = render_help_card(["/影棚 帮助", "/yp 状态"])
|
||||
status_card = render_status_card(state="正常", version="3.0.0", database="已初始化", api="/api/test")
|
||||
assert help_card.read_bytes().startswith(b"\x89PNG")
|
||||
assert status_card.read_bytes().startswith(b"\x89PNG")
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
from adapters.astrbot_command_adapter import command_allowed, command_context_from_event, help_text, message_text_from_event
|
||||
|
||||
|
||||
class FakeEvent:
|
||||
unified_msg_origin = "qq:group:100"
|
||||
message_str = "确认"
|
||||
|
||||
def get_sender_id(self):
|
||||
return "user-1"
|
||||
|
||||
def get_group_id(self):
|
||||
return "group-1"
|
||||
|
||||
def get_platform_name(self):
|
||||
return "aiocqhttp"
|
||||
|
||||
|
||||
def test_command_context_uses_platform_neutral_event_fields():
|
||||
context = command_context_from_event(FakeEvent())
|
||||
assert context.user_id == "user-1"
|
||||
assert context.group_id == "group-1"
|
||||
assert context.message_origin == "qq:group:100"
|
||||
assert context.platform == "aiocqhttp"
|
||||
assert context.message_id == ""
|
||||
assert message_text_from_event(FakeEvent()) == "确认"
|
||||
|
||||
|
||||
def test_command_adapter_reuses_allowlist_policy():
|
||||
config = {"chat_access": {"group_allowlist": ["group-1"], "user_allowlist": ["user-1"]}}
|
||||
context = command_context_from_event(FakeEvent())
|
||||
assert command_allowed(config, "quick_profile", context)
|
||||
assert command_allowed(config, "single_image", context)
|
||||
assert "/影棚 快速角色" in help_text()
|
||||
assert "/yp 帮助" in help_text()
|
||||
|
||||
|
||||
def test_event_context_falls_back_for_telegram_and_discord_style_fields():
|
||||
telegram = type("TelegramEvent", (), {"sender_id": 42, "group_id": -1001, "platform_name": "telegram", "message_origin": "telegram:chat:-1001"})()
|
||||
discord = type("DiscordEvent", (), {"user_id": "u2", "group_id": "guild-2", "platform_name": "discord", "message_origin": "discord:guild:guild-2"})()
|
||||
assert command_context_from_event(telegram).platform == "telegram"
|
||||
assert command_context_from_event(telegram).group_id == "-1001"
|
||||
assert command_context_from_event(discord).user_id == "u2"
|
||||
assert command_context_from_event(discord).message_origin == "discord:guild:guild-2"
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
import pytest
|
||||
|
||||
from adapters.astrbot_command_parser import parse_single_image_command
|
||||
from backend.dto.chat_command_dto import ChatCommandParseError
|
||||
|
||||
|
||||
def test_parse_natural_and_explicit_single_image_command():
|
||||
command = parse_single_image_command('雨夜街道中的少女 --角色 "米卡" --尺寸 2K --数量 2 --负面 水印')
|
||||
assert command.prompt == "雨夜街道中的少女"
|
||||
assert command.profile_ref == "米卡"
|
||||
assert command.size == "2560x1440"
|
||||
assert command.count == 2
|
||||
assert command.negative_prompt == "水印"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", ["", "测试 --尺寸 8K", "测试 --数量 0", "测试 --未知 x"])
|
||||
def test_parse_rejects_invalid_single_image_commands(raw):
|
||||
with pytest.raises(ChatCommandParseError):
|
||||
parse_single_image_command(raw)
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
from main import Main
|
||||
import pytest
|
||||
from adapters.astrbot_command_adapter import command_context_from_event
|
||||
|
||||
|
||||
class Event:
|
||||
def plain_result(self, text):
|
||||
return {"type": "plain", "text": text}
|
||||
|
||||
|
||||
def test_card_and_image_results_fall_back_to_text_without_platform_components():
|
||||
plugin = Main(None)
|
||||
event = Event()
|
||||
card = plugin._card_result(event, lambda: (_ for _ in ()).throw(RuntimeError("no renderer")), "fallback")
|
||||
images = plugin._generation_result(event, "done", [{"image_id": "img-1", "image_url": "https://example.com/a.png"}])
|
||||
assert card["text"] == "fallback"
|
||||
assert "https://example.com/a.png" in images["text"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("platform,origin", [("aiocqhttp", "qq:group:1"), ("telegram", "telegram:chat:1"), ("discord", "discord:guild:1")])
|
||||
def test_platform_context_and_image_fallback_contract(platform, origin):
|
||||
event = type("PlatformEvent", (), {"sender_id": "u1", "group_id": "g1", "platform_name": platform, "message_origin": origin})()
|
||||
context = command_context_from_event(event)
|
||||
assert context.platform == platform
|
||||
assert context.message_origin == origin
|
||||
result = Main(None)._generation_result(Event(), "completed", [{"image_id": "img", "image_url": "https://example.com/image.png"}])
|
||||
assert "image.png" in result["text"]
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
from adapters.astrbot_media_adapter import image_references_from_event
|
||||
|
||||
|
||||
class Image:
|
||||
def __init__(self, url):
|
||||
self.url = url
|
||||
|
||||
|
||||
class Plain:
|
||||
text = "hello"
|
||||
|
||||
|
||||
class Event:
|
||||
message_obj = type("Message", (), {"message": [Plain(), Image("https://example.com/a.png")]})()
|
||||
|
||||
|
||||
def test_extracts_only_image_references():
|
||||
assert image_references_from_event(Event()) == ["https://example.com/a.png"]
|
||||
17
tests/test_chat_access_policy.py
普通文件
17
tests/test_chat_access_policy.py
普通文件
|
|
@ -0,0 +1,17 @@
|
|||
from core.chat_access_policy import chat_action_allowed
|
||||
|
||||
|
||||
CONFIG = {"chat_access": {"group_allowlist": ["group-1"], "user_allowlist": ["user-1"]}}
|
||||
|
||||
|
||||
def test_quick_profile_and_workflow_require_both_allowlists():
|
||||
assert chat_action_allowed(CONFIG, "quick_profile", group_id="group-1", user_id="user-1")
|
||||
assert chat_action_allowed(CONFIG, "character_workflow", group_id="group-1", user_id="user-1")
|
||||
assert not chat_action_allowed(CONFIG, "quick_profile", group_id="group-1", user_id="user-2")
|
||||
assert not chat_action_allowed(CONFIG, "character_workflow", group_id=None, user_id="user-1")
|
||||
|
||||
|
||||
def test_single_image_accepts_either_allowlist():
|
||||
assert chat_action_allowed(CONFIG, "single_image", group_id="group-1", user_id="user-2")
|
||||
assert chat_action_allowed(CONFIG, "single_image", group_id="group-2", user_id="user-1")
|
||||
assert not chat_action_allowed(CONFIG, "single_image", group_id="group-2", user_id="user-2")
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import pytest
|
||||
|
||||
from adapters.astrbot_command_adapter import ChatCommandContext
|
||||
from backend.services.chat_command_guard_service import ChatCommandGuardService
|
||||
|
||||
|
||||
class Audit:
|
||||
def record(self, **kwargs): pass
|
||||
|
||||
|
||||
class Guard(ChatCommandGuardService):
|
||||
def __init__(self):
|
||||
self.audit = Audit()
|
||||
def _daily_count(self, user_id): return 0
|
||||
def _daily_group_count(self, group_id): return 0
|
||||
|
||||
|
||||
CHAT = ChatCommandContext("user-1", "group-1", "qq:group:1", "aiocqhttp", "msg-1")
|
||||
|
||||
|
||||
def test_guard_enforces_resolution_and_concurrency():
|
||||
guard = Guard()
|
||||
config = {"chat_access": {"allow_2k": True, "allow_4k": False, "user_concurrency_limit": 1}}
|
||||
guard.check_generation(config, CHAT, size="2560x1440", active_jobs=[])
|
||||
with pytest.raises(ValueError, match="4K"):
|
||||
guard.check_generation(config, CHAT, size="3840x2160", active_jobs=[])
|
||||
with pytest.raises(ValueError, match="用户并发"):
|
||||
guard.check_generation(config, CHAT, size="1920x1080", active_jobs=[{"request": {"metadata": {"user_id": "user-1"}}}])
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import base64
|
||||
from pathlib import Path
|
||||
|
||||
from backend.services.chat_media_import_service import ChatMediaImportService
|
||||
|
||||
|
||||
class Storage:
|
||||
def __init__(self, root): self.root = Path(root)
|
||||
def resolve_uri(self, uri): return self.root / uri.removeprefix("storage://materials/")
|
||||
def ensure_file(self, uri):
|
||||
path = self.resolve_uri(uri)
|
||||
if not path.is_file(): raise FileNotFoundError(uri)
|
||||
return path
|
||||
|
||||
|
||||
def test_data_url_import_uses_portable_storage_path(tmp_path):
|
||||
service = ChatMediaImportService(Storage(tmp_path))
|
||||
uri, filename, size = service.import_image("data:image/png;base64," + base64.b64encode(b"png-data").decode())
|
||||
assert uri.startswith("storage://materials/chat/")
|
||||
assert "\\" not in uri
|
||||
assert filename.endswith(".png")
|
||||
assert size == 8
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
from backend.services.chat_session_service import ChatSessionStore
|
||||
import time
|
||||
|
||||
|
||||
def test_chat_session_store_binds_and_pops_session(tmp_path):
|
||||
path = tmp_path / "sessions.json"
|
||||
store = ChatSessionStore(ttl_seconds=60, max_sessions=2, persistence_path=path)
|
||||
store.put("qq:group:user", "select_image", {"images": ["img-1"]})
|
||||
restored = ChatSessionStore(ttl_seconds=60, max_sessions=2, persistence_path=path)
|
||||
assert restored.get("qq:group:user").action == "select_image"
|
||||
assert store.get("qq:group:user").payload["images"] == ["img-1"]
|
||||
assert store.pop("qq:group:user").action == "select_image"
|
||||
assert store.get("qq:group:user") is None
|
||||
|
||||
|
||||
def test_chat_session_expires(tmp_path):
|
||||
store = ChatSessionStore(ttl_seconds=0, max_sessions=2, persistence_path=tmp_path / "expired.json")
|
||||
store.put("key", "confirm", {})
|
||||
time.sleep(0.01)
|
||||
assert store.get("key") is None
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
from adapters.astrbot_command_adapter import ChatCommandContext
|
||||
from backend.dto.chat_command_dto import SingleImageCommand
|
||||
from backend.services.chat_workflow_service import ChatWorkflowService, _quick_questionnaire
|
||||
|
||||
|
||||
def test_single_image_orchestration_reuses_existing_routes():
|
||||
calls = []
|
||||
|
||||
def dispatch(ctx, method, path, query=None, payload=None):
|
||||
calls.append((method, path, query, payload))
|
||||
if method == "GET" and path == "jobs":
|
||||
return {"ok": True, "data": {"items": []}}
|
||||
if method == "GET" and path == "profiles":
|
||||
return {"ok": True, "data": {"items": []}}
|
||||
if method == "POST" and path == "profiles":
|
||||
return {"ok": True, "data": {"profile_id": "profile-chat", "name": "chat"}}
|
||||
if path.endswith("/workflows"):
|
||||
return {"ok": True, "data": {"workflow": {"workflow_id": "wf-1"}, "nodes": [{"node_id": "node-1"}]}}
|
||||
if path.endswith("/start"):
|
||||
return {"ok": True, "data": {"status": "running"}}
|
||||
if path.endswith("/generate"):
|
||||
return {"ok": True, "data": {"task_id": "task-1", "images": [{"image_id": "img-1"}]}}
|
||||
if path == "images/img-1":
|
||||
return {"ok": True, "data": {"image_id": "img-1", "image_url": "/media/img-1"}}
|
||||
raise AssertionError((method, path))
|
||||
|
||||
class Guard:
|
||||
def check_generation(self, *args, **kwargs): pass
|
||||
def record(self, *args, **kwargs): pass
|
||||
|
||||
service = ChatWorkflowService(
|
||||
dispatch,
|
||||
lambda: {"chat_access": {"group_allowlist": ["group-1"], "user_allowlist": ["user-1"]}},
|
||||
guard=Guard(),
|
||||
)
|
||||
context = ChatCommandContext("user-1", "group-1", "qq:group:1", "aiocqhttp", "msg-1")
|
||||
result = service.submit_single_image(SingleImageCommand("portrait"), context)
|
||||
assert result["generation"]["task_id"] == "task-1"
|
||||
assert result["images"][0]["image_url"] == "/media/img-1"
|
||||
generate = next(item for item in calls if item[1] == "nodes/node-1/generate")
|
||||
assert generate[3]["size"] == "1920x1080"
|
||||
assert generate[3]["idempotency_key"].startswith("chat_")
|
||||
first_key = generate[3]["idempotency_key"]
|
||||
assert first_key == "chat_" + __import__("hashlib").sha256(b"msg-1").hexdigest()[:32]
|
||||
|
||||
|
||||
def test_quick_questionnaire_extracts_character_fields():
|
||||
result = _quick_questionnaire("米卡 银发蓝眼的冷静少女,穿学院制服,留着长发")
|
||||
assert result["name"] == "米卡"
|
||||
assert "冷静" in result["personality"]
|
||||
assert "制服" in result["clothing_keywords"]
|
||||
assert result["hairstyle"] == "长发"
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
from backend.services.cross_review_service import CrossReviewService, _disagreements
|
||||
|
||||
|
||||
def test_cross_review_routes_are_deduplicated_and_include_legacy_fields():
|
||||
service = CrossReviewService.__new__(CrossReviewService)
|
||||
service.config = {"model_assignments": {"cross_review_routes": ["vision-a", "vision-b"], "cross_review_primary": "vision-a", "cross_review_secondary": "vision-c"}}
|
||||
assert service._routes() == ["vision-a", "vision-b", "vision-c"]
|
||||
|
||||
|
||||
def test_cross_review_reports_model_disagreements():
|
||||
result = _disagreements([{"defects": ["hands", "text"]}, {"defects": ["hands", "anatomy"]}])
|
||||
assert result == ["anatomy", "text"]
|
||||
54
web/assets/index-CflzltCY.js
普通文件
54
web/assets/index-CflzltCY.js
普通文件
文件差异因一行或多行过长而隐藏
文件差异因一行或多行过长而隐藏
文件差异因一行或多行过长而隐藏
文件差异因一行或多行过长而隐藏
|
|
@ -4,8 +4,8 @@
|
|||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>AstrBot ImageStudio</title>
|
||||
<script type="module" crossorigin src="/api/v1/plugins/extensions/astrbot_plugin_imagestudio/web/assets/index-DyWLLdwX.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/api/v1/plugins/extensions/astrbot_plugin_imagestudio/web/assets/index-D1gSt_ux.css">
|
||||
<script type="module" crossorigin src="/api/v1/plugins/extensions/astrbot_plugin_imagestudio/web/assets/index-CflzltCY.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/api/v1/plugins/extensions/astrbot_plugin_imagestudio/web/assets/index-DA6FvhZm.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用