feat(image): add owned reaction asset workbench
这个提交存在于:
父节点
2cf690cdd5
当前提交
e526217373
共有 9 个文件被更改,包括 691 次插入 和 10 次删除
|
|
@ -2989,6 +2989,18 @@
|
|||
"default": [],
|
||||
"invisible": true
|
||||
},
|
||||
"enable_owned_reaction_asset_workbench": {
|
||||
"description": "Legacy flat config: 启用 Q6 自有反应图素材工作台",
|
||||
"type": "bool",
|
||||
"default": false,
|
||||
"invisible": true
|
||||
},
|
||||
"owned_reaction_assets": {
|
||||
"description": "Legacy flat config: Q6 自有反应图素材清单",
|
||||
"type": "list",
|
||||
"default": [],
|
||||
"invisible": true
|
||||
},
|
||||
"enable_group_nsfw_private_fallback": {
|
||||
"description": "Legacy flat config: 群聊成图安全审核与私聊回退",
|
||||
"type": "bool",
|
||||
|
|
@ -9088,6 +9100,25 @@
|
|||
"enable_p5_structured_reference_assets": true
|
||||
}
|
||||
},
|
||||
"enable_owned_reaction_asset_workbench": {
|
||||
"description": "Q6 自有反应图素材工作台",
|
||||
"type": "bool",
|
||||
"hint": "默认关闭。开启后,pc_find_reaction_image 会先检索管理员登记且哈希校验通过的本地自有反应图;聊天图片、引用图片、视觉缓存和外部 URL 不会自动加入。",
|
||||
"default": false,
|
||||
"condition": {
|
||||
"enable_photo_text_action": true
|
||||
}
|
||||
},
|
||||
"owned_reaction_assets": {
|
||||
"description": "Q6 自有反应图素材清单",
|
||||
"type": "list",
|
||||
"hint": "仅管理员配置。每项为 JSON 对象:id、file(owned_reaction_assets 下的相对路径)、sha256、tags 和可选 meme_only。页面工作台只展示素材 ID、标签、表情包标记、校验状态和缩略图,不显示路径或哈希。",
|
||||
"default": [],
|
||||
"condition": {
|
||||
"enable_photo_text_action": true,
|
||||
"enable_owned_reaction_asset_workbench": true
|
||||
}
|
||||
},
|
||||
"enable_group_nsfw_private_fallback": {
|
||||
"description": "群聊成图安全审核与私聊回退",
|
||||
"type": "bool",
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ from .helpers import (
|
|||
_strip_internal_message_blocks,
|
||||
)
|
||||
from .memo_notes import apply_memo_note_action, memo_note_sort_key, normalize_memo_note
|
||||
from .owned_reaction_asset_catalog import OwnedReactionAssetCatalog
|
||||
from .qzone_selection import parse_qzone_post_selection
|
||||
|
||||
|
||||
|
|
@ -158,6 +159,40 @@ class LlmToolActionsMixin:
|
|||
except Exception:
|
||||
return None
|
||||
|
||||
def _find_owned_reaction_asset(
|
||||
self,
|
||||
query: str,
|
||||
*,
|
||||
search_context: str = "",
|
||||
meme_only: bool = True,
|
||||
) -> dict[str, Any] | None:
|
||||
if not bool(getattr(self, "enable_owned_reaction_asset_workbench", False)):
|
||||
return None
|
||||
catalog = OwnedReactionAssetCatalog(getattr(self, "data_dir", ""))
|
||||
asset, status, confidence = catalog.find(
|
||||
getattr(self, "owned_reaction_assets", []),
|
||||
query=query,
|
||||
search_context=search_context,
|
||||
meme_only=bool(meme_only),
|
||||
)
|
||||
if asset is None:
|
||||
logger.debug(
|
||||
"[PrivateCompanion] Q6 自有反应图未命中: status=%s",
|
||||
status,
|
||||
)
|
||||
return None
|
||||
return {
|
||||
"success": True,
|
||||
"status": "success",
|
||||
"source": "owned_reaction_assets",
|
||||
"path": str(asset.path),
|
||||
"image_id": asset.asset_id,
|
||||
"tags": list(asset.tags),
|
||||
"need": _single_line(query, 220),
|
||||
"reason": "管理员登记的受管自有反应图标签命中",
|
||||
"confidence": confidence,
|
||||
}
|
||||
|
||||
def _photo_tool_call_timeout_seconds(self) -> float:
|
||||
context = getattr(self, "context", None)
|
||||
getter = getattr(context, "get_config", None)
|
||||
|
|
@ -2185,8 +2220,23 @@ class LlmToolActionsMixin:
|
|||
_single_line(exc, 160),
|
||||
)
|
||||
|
||||
api = self._smart_imagechat_api()
|
||||
if api is None or not callable(getattr(api, "find_image", None)):
|
||||
# Q6 is an optional, hash-locked local source. It only selects
|
||||
# administrator-declared files and keeps the existing delivery checks.
|
||||
owned_lookup = getattr(self, "_find_owned_reaction_asset", None)
|
||||
lookup = (
|
||||
owned_lookup(
|
||||
query_text,
|
||||
search_context=lookup_context,
|
||||
meme_only=meme_filter,
|
||||
)
|
||||
if callable(owned_lookup)
|
||||
else None
|
||||
)
|
||||
if not isinstance(lookup, dict) or not lookup.get("success"):
|
||||
lookup = None
|
||||
|
||||
api = self._smart_imagechat_api() if lookup is None else None
|
||||
if lookup is None and (api is None or not callable(getattr(api, "find_image", None))):
|
||||
return json.dumps(
|
||||
{
|
||||
"status": "unavailable",
|
||||
|
|
@ -2200,7 +2250,7 @@ class LlmToolActionsMixin:
|
|||
)
|
||||
|
||||
try:
|
||||
lookup = await api.find_image(
|
||||
lookup = lookup or await api.find_image(
|
||||
event,
|
||||
query_text,
|
||||
context=lookup_context,
|
||||
|
|
@ -2340,8 +2390,8 @@ class LlmToolActionsMixin:
|
|||
self._save_data_sync()
|
||||
|
||||
success = bool(image_path and (not send_image or sent))
|
||||
return json.dumps(
|
||||
{
|
||||
source = _single_line(lookup.get("source"), 60) or "smart_imagechat"
|
||||
result_payload = {
|
||||
"status": "success" if success else "delivery_failed",
|
||||
"success": success,
|
||||
"found": True,
|
||||
|
|
@ -2352,8 +2402,9 @@ class LlmToolActionsMixin:
|
|||
if send_image
|
||||
else "已找到图库图片,但按请求未发送"
|
||||
),
|
||||
"path": image_path,
|
||||
"source": source,
|
||||
"image_id": _single_line(lookup.get("image_id"), 120),
|
||||
"asset_id": _single_line(lookup.get("image_id"), 120) if source == "owned_reaction_assets" else "",
|
||||
"tags": tags,
|
||||
"need": need,
|
||||
"reason": match_reason,
|
||||
|
|
@ -2365,9 +2416,12 @@ class LlmToolActionsMixin:
|
|||
if sent
|
||||
else ""
|
||||
),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
}
|
||||
# Keep the legacy Smart ImageChat result compatible, but never expose
|
||||
# an owned asset's absolute host path to the language model.
|
||||
if source != "owned_reaction_assets":
|
||||
result_payload["path"] = image_path
|
||||
return json.dumps(result_payload, ensure_ascii=False)
|
||||
|
||||
async def _pc_qzone_view_feed_impl(
|
||||
self,
|
||||
|
|
|
|||
11
main.py
11
main.py
|
|
@ -1750,6 +1750,17 @@ class PrivateCompanionPlugin(
|
|||
if isinstance(raw_structured_assets, list)
|
||||
else []
|
||||
)
|
||||
self.enable_owned_reaction_asset_workbench = self._cfg_bool(
|
||||
c,
|
||||
"enable_owned_reaction_asset_workbench",
|
||||
False,
|
||||
)
|
||||
raw_owned_reaction_assets = self._cfg_raw(c, "owned_reaction_assets", [])
|
||||
self.owned_reaction_assets = (
|
||||
[dict(item) for item in raw_owned_reaction_assets if isinstance(item, dict)][:96]
|
||||
if isinstance(raw_owned_reaction_assets, list)
|
||||
else []
|
||||
)
|
||||
self.comfyui_photo_wait_seconds = self._cfg_int(c, "comfyui_photo_wait_seconds", 90, 5, 600)
|
||||
self.photo_generation_backend = self._cfg_str(c, "photo_generation_backend", "auto", "auto").strip().lower()
|
||||
if self.photo_generation_backend not in {"auto", "comfyui", "sdgen", "external", "tool_call"}:
|
||||
|
|
|
|||
183
owned_reaction_asset_catalog.py
普通文件
183
owned_reaction_asset_catalog.py
普通文件
|
|
@ -0,0 +1,183 @@
|
|||
"""Hash-locked local catalog for administrator-owned reaction assets (REQ-021 Q6)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
CATALOG_CONTRACT = "ops.q6.owned_reaction_assets.v1"
|
||||
ALLOWED_EXTENSIONS = frozenset({".png", ".jpg", ".jpeg", ".webp"})
|
||||
MAX_ASSET_BYTES = 10 * 1024 * 1024
|
||||
MAX_ASSETS = 96
|
||||
MAX_TAGS = 12
|
||||
_ASSET_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$")
|
||||
_TOKEN_RE = re.compile(r"[a-z0-9_\u4e00-\u9fff]{1,48}", re.I)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OwnedReactionAsset:
|
||||
asset_id: str
|
||||
path: Path
|
||||
tags: tuple[str, ...]
|
||||
meme_only: bool
|
||||
|
||||
|
||||
class OwnedReactionAssetCatalog:
|
||||
"""A source-limited catalog; it never imports chat or vision-cache assets."""
|
||||
|
||||
def __init__(self, data_dir: str | Path) -> None:
|
||||
self._root = (Path(data_dir) / "owned_reaction_assets").resolve()
|
||||
|
||||
@staticmethod
|
||||
def _text(value: Any, limit: int = 160) -> str:
|
||||
return " ".join(str(value or "").split())[:limit]
|
||||
|
||||
@staticmethod
|
||||
def _bool(value: Any, default: bool = False) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if value is None or str(value).strip() == "":
|
||||
return default
|
||||
return str(value).strip().lower() in {"1", "true", "yes", "on", "enabled"}
|
||||
|
||||
def _resolve_path(self, value: Any) -> Path | None:
|
||||
raw = self._text(value, 240).replace("\\", "/")
|
||||
if not raw or raw.startswith(("/", "//")) or ":" in raw or ".." in raw.split("/"):
|
||||
return None
|
||||
try:
|
||||
path = (self._root / raw).resolve()
|
||||
path.relative_to(self._root)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return path
|
||||
|
||||
@staticmethod
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for block in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
@classmethod
|
||||
def _tags(cls, value: Any) -> tuple[str, ...]:
|
||||
raw = value if isinstance(value, (list, tuple, set)) else re.split(r"[,,;;|\s]+", str(value or ""))
|
||||
tags: list[str] = []
|
||||
for item in raw:
|
||||
tag = cls._text(item, 48).casefold()
|
||||
if not tag or "/" in tag or "\\" in tag or ":" in tag:
|
||||
continue
|
||||
if not _TOKEN_RE.fullmatch(tag) or tag in tags:
|
||||
continue
|
||||
tags.append(tag)
|
||||
if len(tags) >= MAX_TAGS:
|
||||
break
|
||||
return tuple(tags)
|
||||
|
||||
def validate_entry(self, raw: Any) -> tuple[OwnedReactionAsset | None, str]:
|
||||
if not isinstance(raw, dict):
|
||||
return None, "entry_not_object"
|
||||
asset_id = self._text(raw.get("id") or raw.get("asset_id"), 80)
|
||||
digest = self._text(raw.get("sha256"), 80).lower()
|
||||
tags = self._tags(raw.get("tags"))
|
||||
path = self._resolve_path(raw.get("file") or raw.get("relative_path"))
|
||||
if not _ASSET_ID_RE.fullmatch(asset_id):
|
||||
return None, "invalid_id"
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", digest):
|
||||
return None, "invalid_hash"
|
||||
if not tags:
|
||||
return None, "missing_tags"
|
||||
if path is None:
|
||||
return None, "outside_managed_directory"
|
||||
try:
|
||||
if not path.is_file():
|
||||
return None, "file_missing"
|
||||
if path.suffix.lower() not in ALLOWED_EXTENSIONS:
|
||||
return None, "unsupported_extension"
|
||||
if path.stat().st_size > MAX_ASSET_BYTES:
|
||||
return None, "file_too_large"
|
||||
if not secrets.compare_digest(self._sha256(path), digest):
|
||||
return None, "hash_mismatch"
|
||||
except OSError:
|
||||
return None, "file_unreadable"
|
||||
return OwnedReactionAsset(
|
||||
asset_id=asset_id,
|
||||
path=path,
|
||||
tags=tags,
|
||||
meme_only=self._bool(raw.get("meme_only"), True),
|
||||
), "ok"
|
||||
|
||||
def inspect(self, entries: Any) -> dict[str, Any]:
|
||||
raw_entries = entries if isinstance(entries, list) else []
|
||||
assets: list[OwnedReactionAsset] = []
|
||||
projection: list[dict[str, Any]] = []
|
||||
seen_ids: set[str] = set()
|
||||
for raw in raw_entries[:MAX_ASSETS]:
|
||||
asset, status = self.validate_entry(raw)
|
||||
raw_id = self._text(raw.get("id") if isinstance(raw, dict) else "", 80)
|
||||
asset_id = raw_id if _ASSET_ID_RE.fullmatch(raw_id) else ""
|
||||
if asset and asset.asset_id in seen_ids:
|
||||
asset, status = None, "duplicate_id"
|
||||
if asset:
|
||||
seen_ids.add(asset.asset_id)
|
||||
assets.append(asset)
|
||||
asset_id = asset.asset_id
|
||||
projection.append({
|
||||
"id": asset_id,
|
||||
"tags": list(asset.tags),
|
||||
"meme_only": asset.meme_only,
|
||||
"status": "ok",
|
||||
"valid": True,
|
||||
})
|
||||
else:
|
||||
projection.append({"id": asset_id, "tags": [], "meme_only": True, "status": status, "valid": False})
|
||||
return {"assets": assets, "items": projection}
|
||||
|
||||
@staticmethod
|
||||
def _query_tokens(value: Any) -> tuple[str, ...]:
|
||||
return tuple(dict.fromkeys(_TOKEN_RE.findall(str(value or "").casefold())))[:24]
|
||||
|
||||
def find(self, entries: Any, *, query: str, search_context: str = "", meme_only: bool = True) -> tuple[OwnedReactionAsset | None, str, float]:
|
||||
inspected = self.inspect(entries)
|
||||
query_tokens = self._query_tokens(query)
|
||||
context_tokens = self._query_tokens(search_context)
|
||||
if not query_tokens:
|
||||
return None, "empty_query", 0.0
|
||||
candidates: list[tuple[float, OwnedReactionAsset]] = []
|
||||
for asset in inspected["assets"]:
|
||||
if meme_only and not asset.meme_only:
|
||||
continue
|
||||
score = 0.0
|
||||
for tag in asset.tags:
|
||||
if tag in query_tokens:
|
||||
score += 10.0
|
||||
elif any(tag in token or token in tag for token in query_tokens if len(token) >= 2):
|
||||
score += 5.0
|
||||
if tag in context_tokens:
|
||||
score += 1.0
|
||||
if score > 0:
|
||||
candidates.append((score, asset))
|
||||
if not candidates:
|
||||
return None, "not_found", 0.0
|
||||
candidates.sort(key=lambda item: (-item[0], item[1].asset_id))
|
||||
score, asset = candidates[0]
|
||||
return asset, "ok", min(1.0, score / 10.0)
|
||||
|
||||
def resolve(self, entries: Any, asset_id: Any) -> OwnedReactionAsset | None:
|
||||
requested = self._text(asset_id, 80)
|
||||
if not _ASSET_ID_RE.fullmatch(requested):
|
||||
return None
|
||||
return next((asset for asset in self.inspect(entries)["assets"] if asset.asset_id == requested), None)
|
||||
|
||||
def public_projection(self, entries: Any) -> dict[str, Any]:
|
||||
inspected = self.inspect(entries)
|
||||
return {
|
||||
"contract": CATALOG_CONTRACT,
|
||||
"managed_directory": "owned_reaction_assets",
|
||||
"items": inspected["items"],
|
||||
"max_assets": MAX_ASSETS,
|
||||
}
|
||||
49
page_api.py
49
page_api.py
|
|
@ -39,6 +39,7 @@ from .memo_notes import (
|
|||
memo_note_sort_key,
|
||||
normalize_memo_note,
|
||||
)
|
||||
from .owned_reaction_asset_catalog import MAX_ASSET_BYTES, OwnedReactionAssetCatalog
|
||||
|
||||
PLUGIN_NAME = "astrbot_plugin_private_companion"
|
||||
PAGE_API_PREFIX = f"/{PLUGIN_NAME}/page"
|
||||
|
|
@ -322,6 +323,8 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
("/image_cache/bulk_delete", self.bulk_delete_image_cache_items, ["POST"], "Private Companion Page bulk delete image cache items"),
|
||||
("/photo_reference/list", self.list_photo_references, ["GET"], "Private Companion Page photo reference list"),
|
||||
("/photo_reference/image_data", self.get_photo_reference_image_data, ["GET"], "Private Companion Page photo reference image data"),
|
||||
("/reaction_assets/list", self.list_owned_reaction_assets, ["GET"], "Private Companion Page owned reaction assets"),
|
||||
("/reaction_assets/image_data", self.get_owned_reaction_asset_image_data, ["GET"], "Private Companion Page owned reaction asset image data"),
|
||||
("/daily_outfit/image", self.get_daily_outfit_image, ["GET"], "Private Companion Page daily outfit image"),
|
||||
("/daily_outfit/image_data", self.get_daily_outfit_image_data, ["GET"], "Private Companion Page daily outfit image data"),
|
||||
("/bookshelf/unlock", self.unlock_bookshelf, ["POST"], "Private Companion Page unlock bookshelf"),
|
||||
|
|
@ -1357,6 +1360,52 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
logger.error(f"[PrivateCompanionPage] 获取参考图预览失败: {exc}", exc_info=True)
|
||||
return self._exception_error(str(exc))
|
||||
|
||||
def _owned_reaction_asset_catalog(self) -> OwnedReactionAssetCatalog:
|
||||
return OwnedReactionAssetCatalog(getattr(self.plugin, "data_dir", ""))
|
||||
|
||||
def _owned_reaction_asset_entries(self) -> list[dict[str, Any]]:
|
||||
entries = getattr(self.plugin, "owned_reaction_assets", [])
|
||||
if not isinstance(entries, list):
|
||||
return []
|
||||
return [dict(entry) for entry in entries if isinstance(entry, dict)][:96]
|
||||
|
||||
async def list_owned_reaction_assets(self) -> dict[str, Any]:
|
||||
try:
|
||||
catalog = self._owned_reaction_asset_catalog()
|
||||
projection = catalog.public_projection(self._owned_reaction_asset_entries())
|
||||
return self._ok({
|
||||
"enabled": bool(getattr(self.plugin, "enable_owned_reaction_asset_workbench", False)),
|
||||
**projection,
|
||||
})
|
||||
except Exception:
|
||||
logger.error("[PrivateCompanionPage] owned reaction asset status failed")
|
||||
return self._exception_error("无法读取自有反应图素材状态")
|
||||
|
||||
async def get_owned_reaction_asset_image_data(self) -> dict[str, Any]:
|
||||
asset_id = self._single_line(request.args.get("id"), 80)
|
||||
if not asset_id:
|
||||
return self._error("缺少素材 id")
|
||||
try:
|
||||
asset = self._owned_reaction_asset_catalog().resolve(
|
||||
self._owned_reaction_asset_entries(),
|
||||
asset_id,
|
||||
)
|
||||
if asset is None:
|
||||
return self._error("素材不存在、未登记或校验失败")
|
||||
mime = mimetypes.guess_type(str(asset.path))[0] or ""
|
||||
if not mime.startswith("image/"):
|
||||
return self._error("素材文件类型不受支持")
|
||||
return self._ok(
|
||||
await self._encode_image_cache_file_data_url(
|
||||
asset.path,
|
||||
mime,
|
||||
max_bytes=MAX_ASSET_BYTES,
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
logger.error("[PrivateCompanionPage] owned reaction asset preview failed")
|
||||
return self._exception_error("无法读取自有反应图预览")
|
||||
|
||||
async def get_image_cache_preview(self) -> Any:
|
||||
try:
|
||||
resolved = await self._resolve_image_cache_preview_for_request()
|
||||
|
|
|
|||
|
|
@ -12322,6 +12322,115 @@ html[data-bookshelf-direction="backward"]::view-transition-new(bookshelf-view) {
|
|||
display: none;
|
||||
}
|
||||
|
||||
.owned-reaction-assets {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
border: 1px solid var(--line-soft);
|
||||
border-radius: var(--radius);
|
||||
padding: 16px;
|
||||
background: rgba(255, 255, 255, 0.74);
|
||||
box-shadow: var(--shadow-ring);
|
||||
}
|
||||
|
||||
.owned-reaction-assets > header,
|
||||
.owned-reaction-asset header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.owned-reaction-assets > header > div {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.owned-reaction-assets > header span,
|
||||
.owned-reaction-assets > header p,
|
||||
.owned-reaction-assets small {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.owned-reaction-assets > header h3,
|
||||
.owned-reaction-assets > header p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.owned-reaction-assets-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.owned-reaction-assets-summary {
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.owned-reaction-asset {
|
||||
display: grid;
|
||||
grid-template-columns: 72px minmax(0, 1fr);
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
border: 1px solid var(--line-soft);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 10px;
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.owned-reaction-asset.is-invalid {
|
||||
border-style: dashed;
|
||||
opacity: 0.74;
|
||||
}
|
||||
|
||||
.owned-reaction-thumb {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 72px;
|
||||
height: 72px;
|
||||
overflow: hidden;
|
||||
border-radius: 9px;
|
||||
background: var(--surface-strong);
|
||||
color: var(--muted);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.owned-reaction-thumb img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.owned-reaction-asset > div {
|
||||
display: grid;
|
||||
align-content: start;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.owned-reaction-asset b {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.owned-reaction-asset p {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 5px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.owned-reaction-asset p span {
|
||||
border: 1px solid var(--line-soft);
|
||||
border-radius: 999px;
|
||||
padding: 2px 6px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.image-cache-page-numbers {
|
||||
display: flex;
|
||||
gap: 5px;
|
||||
|
|
|
|||
|
|
@ -118,6 +118,7 @@ const state = {
|
|||
imageCacheBatchMode: false,
|
||||
selectedImageCacheKeys: new Set(),
|
||||
imageCacheImageData: new Map(),
|
||||
ownedReactionAssets: null,
|
||||
selectedImageCacheKey: "",
|
||||
troubleshootingFilter: "all",
|
||||
troubleshootingCategory: "all",
|
||||
|
|
@ -4793,6 +4794,13 @@ async function loadImageCache({ clampPage = true } = {}) {
|
|||
return data;
|
||||
}
|
||||
|
||||
async function loadOwnedReactionAssets() {
|
||||
const data = await fetchJson("/reaction_assets/list");
|
||||
state.ownedReactionAssets = data || { items: [] };
|
||||
if (state.activeTab === "image-cache") renderOwnedReactionAssets();
|
||||
return data;
|
||||
}
|
||||
|
||||
async function goToImageCachePage(targetPage) {
|
||||
const pageSize = Math.max(1, Number(state.imageCachePageSize || 36));
|
||||
const pages = Math.max(1, Math.ceil(Number(state.imageCacheTotal || 0) / pageSize));
|
||||
|
|
@ -5177,7 +5185,7 @@ async function ensureTabData(tabName, force = false) {
|
|||
await loadConfigBackups(force);
|
||||
} else if (tabName === "image-cache") {
|
||||
renderImageCache();
|
||||
await loadImageCache();
|
||||
await Promise.all([loadImageCache(), loadOwnedReactionAssets()]);
|
||||
} else if (tabName === "troubleshooting") {
|
||||
renderTroubleshooting();
|
||||
loadDiagnostics(force).catch(() => {});
|
||||
|
|
@ -10391,6 +10399,40 @@ function renderImageCache() {
|
|||
renderImageCachePager();
|
||||
void hydrateImageCacheImages(listEl);
|
||||
void hydrateImageCacheImages(detailEl);
|
||||
renderOwnedReactionAssets();
|
||||
}
|
||||
|
||||
function renderOwnedReactionAssets() {
|
||||
const root = $("#ownedReactionAssets");
|
||||
if (!root) return;
|
||||
const catalog = state.ownedReactionAssets;
|
||||
if (!catalog) {
|
||||
root.innerHTML = `<div class="empty small">正在读取管理员登记的自有反应图素材…</div>`;
|
||||
return;
|
||||
}
|
||||
const items = Array.isArray(catalog.items) ? catalog.items : [];
|
||||
const enabled = Boolean(catalog.enabled);
|
||||
root.innerHTML = `
|
||||
<div class="owned-reaction-assets-summary">
|
||||
<span class="badge ${enabled ? "ok" : "off"}">${enabled ? "检索已启用" : "检索关闭"}</span>
|
||||
<small>受管目录:${escapeHtml(catalog.managed_directory || "owned_reaction_assets")} · ${escapeHtml(items.filter((item) => item.valid).length)}/${escapeHtml(items.length)} 校验通过</small>
|
||||
</div>
|
||||
${items.length ? items.map((item) => {
|
||||
const assetId = String(item?.id || "");
|
||||
const previewEndpoint = item?.valid && assetId ? `/reaction_assets/image_data?id=${encodeURIComponent(assetId)}` : "";
|
||||
return `
|
||||
<article class="owned-reaction-asset ${item?.valid ? "is-valid" : "is-invalid"}">
|
||||
${previewEndpoint ? `<span class="owned-reaction-thumb"><img src="${TRANSPARENT_IMAGE}" data-image-cache-src="${escapeHtml(previewEndpoint)}" alt="${escapeHtml(assetId || "自有反应图")}" loading="lazy" /></span>` : `<span class="owned-reaction-thumb placeholder">!</span>`}
|
||||
<div>
|
||||
<header><b>${escapeHtml(assetId || "未命名素材")}</b><span class="badge ${item?.valid ? "ok" : "off"}">${item?.valid ? "校验通过" : "不可用"}</span></header>
|
||||
<p>${Array.isArray(item?.tags) && item.tags.length ? item.tags.map((tag) => `<span>${escapeHtml(tag)}</span>`).join("") : "不显示路径、哈希或来源"}</p>
|
||||
<small>${item?.meme_only === false ? "允许普通图片检索" : "仅表情包检索"}${item?.valid ? "" : ` · ${escapeHtml(item?.status || "校验失败")}`}</small>
|
||||
</div>
|
||||
</article>
|
||||
`;
|
||||
}).join("") : `<div class="empty small">还没有登记素材。请在 Q6 配置清单中填写素材 ID、相对文件名、SHA-256 和标签;不会自动收集聊天图片。</div>`}
|
||||
`;
|
||||
void hydrateImageCacheImages(root);
|
||||
}
|
||||
|
||||
function renderImageCacheBatchControls() {
|
||||
|
|
@ -27815,6 +27857,16 @@ $("#refreshImageCacheBtn")?.addEventListener("click", () => {
|
|||
state.imageCacheImageData.clear();
|
||||
loadImageCache().catch((error) => showToast(`刷新失败:${error.message}`, "error"));
|
||||
});
|
||||
$("#refreshImageCacheBtn")?.addEventListener("click", () => {
|
||||
state.imageCacheImageData.clear();
|
||||
loadOwnedReactionAssets().catch((error) => showToast(`刷新失败:${error.message}`, "error"));
|
||||
});
|
||||
$("#refreshOwnedReactionAssetsBtn")?.addEventListener("click", () => {
|
||||
state.imageCacheImageData.clear();
|
||||
loadOwnedReactionAssets()
|
||||
.then(() => showToast("自有反应图素材状态已刷新"))
|
||||
.catch((error) => showToast(`刷新失败:${error.message}`, "error"));
|
||||
});
|
||||
$("#refreshTroubleshootingBtn")?.addEventListener("click", () => {
|
||||
Promise.all([loadTroubleshooting(), loadDiagnostics(true)])
|
||||
.then(() => showToast("排障信息已刷新"))
|
||||
|
|
|
|||
|
|
@ -1102,6 +1102,17 @@ QQ空间 = 公开札记
|
|||
<div id="imageCacheDetail" class="image-cache-detail"></div>
|
||||
</div>
|
||||
<nav id="imageCachePager" class="image-cache-pager" aria-label="图片缓存分页"></nav>
|
||||
<section class="owned-reaction-assets" aria-labelledby="ownedReactionAssetsTitle">
|
||||
<header>
|
||||
<div>
|
||||
<span>管理员登记 · Q6</span>
|
||||
<h3 id="ownedReactionAssetsTitle">自有反应图素材</h3>
|
||||
<p>只读核对已登记素材。只有校验通过的素材会参与表情包检索;不会导入聊天图、缓存图或网址。</p>
|
||||
</div>
|
||||
<button id="refreshOwnedReactionAssetsBtn" type="button">刷新状态</button>
|
||||
</header>
|
||||
<div id="ownedReactionAssets" class="owned-reaction-assets-grid"></div>
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,181 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import tempfile
|
||||
from typing import Any
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
if str(ROOT) not in os.sys.path:
|
||||
os.sys.path.insert(0, str(ROOT))
|
||||
|
||||
from owned_reaction_asset_catalog import OwnedReactionAssetCatalog # noqa: E402
|
||||
|
||||
|
||||
def _single_line(value: Any, limit: int = 1000) -> str:
|
||||
return re.sub(r"\s+", " ", str(value or "")).strip()[:limit]
|
||||
|
||||
|
||||
def _path_text(value: Any, limit: int = 1000) -> str:
|
||||
return _single_line(value, limit)
|
||||
|
||||
|
||||
def _safe_float(value: Any, default: float, minimum: float, maximum: float) -> float:
|
||||
try:
|
||||
return max(minimum, min(maximum, float(value)))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _load_reaction_impl() -> Any:
|
||||
source = (ROOT / "llm_tool_actions.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
owner = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "LlmToolActionsMixin")
|
||||
method = next(
|
||||
node for node in owner.body if isinstance(node, ast.AsyncFunctionDef) and node.name == "_pc_find_reaction_image_impl"
|
||||
)
|
||||
namespace: dict[str, Any] = {
|
||||
"Any": Any,
|
||||
"AstrMessageEvent": Any,
|
||||
"json": json,
|
||||
"logger": logging.getLogger("test_req021_q6"),
|
||||
"os": os,
|
||||
"_single_line": _single_line,
|
||||
"_path_text": _path_text,
|
||||
"_safe_float": _safe_float,
|
||||
"PHOTO_TOOL_SILENT_SENTINEL": "sentinel",
|
||||
}
|
||||
module = ast.Module(body=[copy.deepcopy(method)], type_ignores=[])
|
||||
ast.fix_missing_locations(module)
|
||||
exec(compile(module, str(ROOT / "llm_tool_actions.py"), "exec"), namespace)
|
||||
return namespace["_pc_find_reaction_image_impl"]
|
||||
|
||||
|
||||
REACTION_IMPL = _load_reaction_impl()
|
||||
|
||||
|
||||
class OwnedReactionAssetCatalogTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.data_dir = Path(self.temp.name)
|
||||
self.asset_dir = self.data_dir / "owned_reaction_assets"
|
||||
self.asset_dir.mkdir()
|
||||
self.catalog = OwnedReactionAssetCatalog(self.data_dir)
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.temp.cleanup()
|
||||
|
||||
def _entry(self, asset_id: str, name: str, *, tags: list[str], meme_only: bool = True) -> dict[str, Any]:
|
||||
path = self.asset_dir / name
|
||||
path.write_bytes(f"asset:{name}".encode("utf-8"))
|
||||
return {
|
||||
"id": asset_id,
|
||||
"file": name,
|
||||
"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
|
||||
"tags": tags,
|
||||
"meme_only": meme_only,
|
||||
}
|
||||
|
||||
def test_hash_directory_extension_and_projection_are_fail_closed(self) -> None:
|
||||
valid = self._entry("smile-01", "smile.png", tags=["开心", "smile"])
|
||||
invalid = dict(valid, id="outside", file="../outside.png")
|
||||
projection = self.catalog.public_projection([valid, invalid, {"id": "bad", "file": "x.gif"}])
|
||||
|
||||
self.assertEqual("ok", projection["items"][0]["status"])
|
||||
self.assertFalse(projection["items"][1]["valid"])
|
||||
self.assertEqual("outside_managed_directory", projection["items"][1]["status"])
|
||||
self.assertNotIn("file", json.dumps(projection, ensure_ascii=False))
|
||||
self.assertNotIn("sha256", json.dumps(projection, ensure_ascii=False))
|
||||
self.assertIsNone(self.catalog.resolve([invalid], "outside"))
|
||||
|
||||
def test_find_is_stable_and_honors_meme_only(self) -> None:
|
||||
alpha = self._entry("alpha", "alpha.png", tags=["开心"])
|
||||
beta = self._entry("beta", "beta.webp", tags=["开心"], meme_only=False)
|
||||
asset, status, confidence = self.catalog.find([beta, alpha], query="开心", meme_only=True)
|
||||
|
||||
self.assertEqual("ok", status)
|
||||
self.assertEqual("alpha", asset.asset_id if asset else "")
|
||||
self.assertGreater(confidence, 0.0)
|
||||
asset, status, _confidence = self.catalog.find([beta], query="开心", meme_only=True)
|
||||
self.assertIsNone(asset)
|
||||
self.assertEqual("not_found", status)
|
||||
|
||||
|
||||
class _OwnedReactionHost:
|
||||
data: dict[str, Any] = {}
|
||||
|
||||
def __init__(self, path: Path) -> None:
|
||||
self.path = path
|
||||
self.external_calls = 0
|
||||
|
||||
def _mark_smart_imagechat_skip_proactive_emoji(self, _event: object) -> None:
|
||||
pass
|
||||
|
||||
def _find_owned_reaction_asset(self, _query: str, **_kwargs: Any) -> dict[str, Any]:
|
||||
return {
|
||||
"success": True,
|
||||
"source": "owned_reaction_assets",
|
||||
"path": str(self.path),
|
||||
"image_id": "smile-01",
|
||||
"tags": ["开心"],
|
||||
"need": "开心",
|
||||
"reason": "受管素材",
|
||||
"confidence": 1.0,
|
||||
}
|
||||
|
||||
def _smart_imagechat_api(self) -> Any:
|
||||
self.external_calls += 1
|
||||
raise AssertionError("owned match must not query Smart ImageChat")
|
||||
|
||||
def _sanitize_photo_tool_caption(self, value: str, limit: int = 120) -> str:
|
||||
return _single_line(value, limit)
|
||||
|
||||
|
||||
class OwnedReactionToolAndPanelContractTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_owned_match_precedes_smart_imagechat_and_hides_host_path(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
asset = Path(temp) / "smile.png"
|
||||
asset.write_bytes(b"asset")
|
||||
host = _OwnedReactionHost(asset)
|
||||
payload = json.loads(await REACTION_IMPL(host, object(), query="开心", send=False))
|
||||
|
||||
self.assertEqual("owned_reaction_assets", payload["source"])
|
||||
self.assertEqual("smile-01", payload["asset_id"])
|
||||
self.assertNotIn("path", payload)
|
||||
self.assertEqual(0, host.external_calls)
|
||||
|
||||
def test_panel_is_id_only_and_routes_are_read_only(self) -> None:
|
||||
api_source = (ROOT / "page_api.py").read_text(encoding="utf-8")
|
||||
panel_source = (ROOT / "pages" / "陪伴面板" / "app.js").read_text(encoding="utf-8")
|
||||
routes = {
|
||||
(node.elts[0].value, node.elts[2].elts[0].value)
|
||||
for node in ast.walk(ast.parse(api_source))
|
||||
if isinstance(node, ast.Tuple)
|
||||
and len(node.elts) >= 3
|
||||
and isinstance(node.elts[0], ast.Constant)
|
||||
and isinstance(node.elts[0].value, str)
|
||||
and node.elts[0].value.startswith("/reaction_assets/")
|
||||
and isinstance(node.elts[2], ast.List)
|
||||
and node.elts[2].elts
|
||||
and isinstance(node.elts[2].elts[0], ast.Constant)
|
||||
}
|
||||
self.assertEqual(
|
||||
{("/reaction_assets/list", "GET"), ("/reaction_assets/image_data", "GET")},
|
||||
routes,
|
||||
)
|
||||
self.assertIn("/reaction_assets/image_data?id=${encodeURIComponent(assetId)}", panel_source)
|
||||
self.assertIn("不显示路径、哈希或来源", panel_source)
|
||||
self.assertNotIn("reaction_assets/image_data?path=", panel_source)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
正在加载…
添加表格
在新工单中引用