89 行
2.1 KiB
Python
89 行
2.1 KiB
Python
"""Shared chat command parsing helpers."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from dataclasses import dataclass
|
||
from typing import Any
|
||
|
||
|
||
WORKBENCH_ALIASES = frozenset(
|
||
{
|
||
"imagestudio",
|
||
"image studio",
|
||
"is",
|
||
"图像工作台",
|
||
"打开图像工作台",
|
||
"工作台",
|
||
"打开工作台",
|
||
"生图工作台",
|
||
"打开生图工作台",
|
||
}
|
||
)
|
||
|
||
PROFILE_COMMAND_PREFIXES = (
|
||
"profile",
|
||
"quick profile",
|
||
"imagestudio profile",
|
||
"image studio profile",
|
||
"is profile",
|
||
"创建角色",
|
||
"新建角色",
|
||
"创建人设",
|
||
"新建人设",
|
||
"imagestudio 创建角色",
|
||
"image studio 创建角色",
|
||
"is 创建角色",
|
||
)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class ChatCommandAction:
|
||
action: str
|
||
payload: dict[str, Any]
|
||
|
||
|
||
def normalize_command_text(text: str) -> str:
|
||
normalized = str(text or "").replace("/", "/").strip().lower()
|
||
return re.sub(r"\s+", " ", normalized)
|
||
|
||
|
||
def command_key(text: str) -> str:
|
||
return normalize_command_text(text).lstrip("/")
|
||
|
||
|
||
def is_workbench_command(text: str) -> bool:
|
||
return command_key(text) in WORKBENCH_ALIASES
|
||
|
||
|
||
def parse_chat_command(text: str) -> ChatCommandAction | None:
|
||
if is_workbench_command(text):
|
||
return ChatCommandAction("open_workbench", {})
|
||
|
||
profile_name = parse_quick_profile_name(text)
|
||
if profile_name is None:
|
||
return None
|
||
return ChatCommandAction(
|
||
"quick_profile",
|
||
{
|
||
"action_type": "quick_profile",
|
||
"draft_only": True,
|
||
"questionnaire": {"name": profile_name},
|
||
},
|
||
)
|
||
|
||
|
||
def parse_quick_profile_name(text: str) -> str | None:
|
||
raw = re.sub(r"\s+", " ", str(text or "").replace("/", "/").strip()).lstrip("/")
|
||
normalized = raw.lower()
|
||
for prefix in sorted(PROFILE_COMMAND_PREFIXES, key=len, reverse=True):
|
||
if normalized == prefix:
|
||
return None
|
||
if normalized.startswith(f"{prefix} "):
|
||
return _clean_profile_name(raw[len(prefix) + 1 :])
|
||
return None
|
||
|
||
|
||
def _clean_profile_name(text: str) -> str | None:
|
||
name = text.strip(" \t\r\n::")
|
||
return name or None
|