astrbot_plugin_imagestudio/adapters/astrbot_command_parser.py

70 行
2.4 KiB
Python

"""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"
"可用参数:--角色、--模型、--尺寸、--数量、--负面"
)