Files
cmshoppe/app/prompts.py
T

301 lines
9.3 KiB
Python
Raw Normal View History

2026-06-27 16:10:50 +08:00
"""Prompt file management and variable rendering."""
from __future__ import annotations
import os
2026-07-10 09:00:06 +08:00
from importlib import resources
2026-06-27 16:10:50 +08:00
from . import appconfig
2026-06-27 16:10:50 +08:00
TITLE_PROMPT_PATH = appconfig.title_prompt_path()
2026-07-10 11:43:35 +08:00
TITLE_TEMPLATES_DIR = appconfig.title_templates_dir()
COVER_PROMPTS_DIR = appconfig.cover_prompts_dir()
IMAGE_STUDIO_PROMPTS_DIR = appconfig.image_studio_prompts_dir()
2026-06-27 16:10:50 +08:00
TEMPLATE_EXT = ".txt"
INVALID_NAME_CHARS = set('\\/:*?"<>|')
2026-07-10 09:00:06 +08:00
DEFAULT_PROMPTS_PACKAGE = "app.default_prompts"
DEFAULT_COVER_PROMPTS_PACKAGE = "app.default_prompts.cover"
2026-06-27 16:10:50 +08:00
class PromptError(RuntimeError):
"""Raised when prompt files or template names are invalid."""
def load_title_prompt(path=TITLE_PROMPT_PATH) -> str:
"""Load the title prompt text. Missing file means an empty prompt."""
if not os.path.exists(path):
return ""
with open(path, "r", encoding="utf-8") as fh:
return fh.read()
def save_title_prompt(text, path=TITLE_PROMPT_PATH) -> None:
"""Save the title prompt text as UTF-8."""
directory = os.path.dirname(os.path.abspath(path))
if directory:
os.makedirs(directory, exist_ok=True)
with open(path, "w", encoding="utf-8") as fh:
fh.write(str(text or ""))
2026-07-10 09:00:06 +08:00
def ensure_default_prompts(
title_prompt_path=TITLE_PROMPT_PATH,
cover_prompts_dir=COVER_PROMPTS_DIR,
2026-07-10 11:43:35 +08:00
title_templates_dir=None,
2026-07-10 09:00:06 +08:00
) -> None:
"""Seed bundled default prompts into an empty user data directory.
Existing user prompts are never overwritten. Defaults live in the packaged
app and are copied into data/ only when the corresponding user files are
missing, or the title prompt file is blank.
"""
if not _has_non_empty_file(title_prompt_path):
default_title = _read_default_prompt_text("title_prompt.txt")
if default_title:
save_title_prompt(default_title, title_prompt_path)
2026-07-10 11:43:35 +08:00
if title_templates_dir is None:
title_templates_dir = _title_templates_dir_for_prompt_path(title_prompt_path)
if not list_templates(title_templates_dir):
default_title = _read_default_prompt_text("title_prompt.txt")
if default_title:
save_template("默认", default_title, title_templates_dir)
2026-07-10 09:00:06 +08:00
if not list_cover_templates(cover_prompts_dir):
for name, text in _iter_default_cover_templates():
save_cover_template(name, text, cover_prompts_dir)
2026-07-10 11:43:35 +08:00
def list_templates(directory):
"""Return prompt template names sorted by display name."""
2026-06-27 16:10:50 +08:00
if not os.path.isdir(directory):
return []
names = []
for filename in os.listdir(directory):
if filename.lower().endswith(TEMPLATE_EXT):
names.append(filename[: -len(TEMPLATE_EXT)])
return sorted(names, key=str.casefold)
2026-07-10 11:43:35 +08:00
def load_template(name, directory) -> str:
"""Load one prompt template."""
2026-06-27 16:10:50 +08:00
path = _template_path(name, directory)
if not os.path.exists(path):
2026-07-10 11:43:35 +08:00
raise PromptError(f"提示词模板不存在: {_normalize_name(name)}")
2026-06-27 16:10:50 +08:00
with open(path, "r", encoding="utf-8") as fh:
return fh.read()
2026-07-10 11:43:35 +08:00
def save_template(name, text, directory) -> None:
"""Save one prompt template as UTF-8."""
2026-06-27 16:10:50 +08:00
path = _template_path(name, directory)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as fh:
fh.write(str(text or ""))
2026-07-10 11:43:35 +08:00
def rename_template(old, new, directory) -> None:
"""Rename a prompt template with duplicate-name protection."""
2026-06-27 16:10:50 +08:00
old_path = _template_path(old, directory)
new_path = _template_path(new, directory)
if not os.path.exists(old_path):
2026-07-10 11:43:35 +08:00
raise PromptError(f"提示词模板不存在: {_normalize_name(old)}")
2026-06-27 16:10:50 +08:00
if os.path.exists(new_path):
2026-07-10 11:43:35 +08:00
raise PromptError(f"提示词模板已存在: {_normalize_name(new)}")
2026-06-27 16:10:50 +08:00
os.makedirs(os.path.dirname(new_path), exist_ok=True)
os.replace(old_path, new_path)
2026-07-10 11:43:35 +08:00
def delete_template(name, directory) -> None:
"""Delete one prompt template."""
path = _template_path(name, directory)
if not os.path.exists(path):
raise PromptError(f"提示词模板不存在: {_normalize_name(name)}")
os.remove(path)
def list_title_templates(directory=TITLE_TEMPLATES_DIR):
"""Return title prompt template names sorted by display name."""
return list_templates(directory)
def load_title_template(name, directory=TITLE_TEMPLATES_DIR) -> str:
"""Load one title prompt template."""
return load_template(name, directory)
def save_title_template(name, text, directory=TITLE_TEMPLATES_DIR) -> None:
"""Save one title prompt template as UTF-8."""
save_template(name, text, directory)
def rename_title_template(old, new, directory=TITLE_TEMPLATES_DIR) -> None:
"""Rename a title prompt template with duplicate-name protection."""
rename_template(old, new, directory)
def delete_title_template(name, directory=TITLE_TEMPLATES_DIR) -> None:
"""Delete one title prompt template."""
delete_template(name, directory)
def list_image_studio_templates(directory=IMAGE_STUDIO_PROMPTS_DIR):
"""Return AI studio prompt template names sorted by display name."""
return list_templates(directory)
def load_image_studio_template(name, directory=IMAGE_STUDIO_PROMPTS_DIR) -> str:
"""Load one AI studio prompt template as raw text."""
return load_template(name, directory)
def save_image_studio_template(name, text, directory=IMAGE_STUDIO_PROMPTS_DIR) -> None:
"""Save one AI studio prompt template as raw UTF-8 text."""
save_template(name, text, directory)
def rename_image_studio_template(old, new, directory=IMAGE_STUDIO_PROMPTS_DIR) -> None:
"""Rename an AI studio prompt template with duplicate-name protection."""
rename_template(old, new, directory)
def delete_image_studio_template(name, directory=IMAGE_STUDIO_PROMPTS_DIR) -> None:
"""Delete one AI studio prompt template."""
delete_template(name, directory)
2026-07-10 11:43:35 +08:00
def list_cover_templates(directory=COVER_PROMPTS_DIR):
"""Return cover template names sorted by display name."""
return list_templates(directory)
def load_cover_template(name, directory=COVER_PROMPTS_DIR) -> str:
"""Load one cover prompt template."""
return load_template(name, directory)
def save_cover_template(name, text, directory=COVER_PROMPTS_DIR) -> None:
"""Save one cover prompt template as UTF-8."""
save_template(name, text, directory)
def rename_cover_template(old, new, directory=COVER_PROMPTS_DIR) -> None:
"""Rename a cover prompt template with duplicate-name protection."""
rename_template(old, new, directory)
2026-06-27 16:10:50 +08:00
def delete_cover_template(name, directory=COVER_PROMPTS_DIR) -> None:
"""Delete one cover prompt template."""
2026-07-10 11:43:35 +08:00
delete_template(name, directory)
2026-06-27 16:10:50 +08:00
def render_prompt(template_text, task) -> str:
"""Render known task variables in a prompt template."""
values = {
"旧标题": _task_value(task, "old_title", "旧标题"),
"新标题": _task_value(task, "new_title", "新标题"),
"商品id": _task_value(task, "item_id", "商品id", "商品ID"),
"店铺": _task_value(task, "shop", "account_name", "店铺", "alias"),
}
rendered = str(template_text or "")
for name, value in values.items():
rendered = rendered.replace("{" + name + "}", value)
return rendered
def _task_value(task, *names) -> str:
for name in names:
value = None
if isinstance(task, dict):
value = task.get(name)
else:
value = getattr(task, name, None)
if value is not None:
return str(value)
return ""
def _template_path(name, directory) -> str:
normalized = _normalize_name(name)
return os.path.abspath(os.path.join(directory, normalized + TEMPLATE_EXT))
def _normalize_name(name) -> str:
value = str(name or "").strip()
if value.lower().endswith(TEMPLATE_EXT):
value = value[: -len(TEMPLATE_EXT)]
value = value.strip()
if not value:
2026-07-10 11:43:35 +08:00
raise PromptError("提示词模板名不能为空")
2026-06-27 16:10:50 +08:00
if value in {".", ".."} or any(char in INVALID_NAME_CHARS for char in value):
2026-07-10 11:43:35 +08:00
raise PromptError(f"提示词模板名非法: {value}")
2026-06-27 16:10:50 +08:00
if os.path.basename(value) != value:
2026-07-10 11:43:35 +08:00
raise PromptError(f"提示词模板名非法: {value}")
2026-06-27 16:10:50 +08:00
return value
2026-07-10 09:00:06 +08:00
2026-07-10 11:43:35 +08:00
def _title_templates_dir_for_prompt_path(title_prompt_path) -> str:
data_root = os.path.dirname(os.path.abspath(title_prompt_path))
return os.path.join(data_root, "prompts", "title")
2026-07-10 09:00:06 +08:00
def _has_non_empty_file(path) -> bool:
try:
if not os.path.exists(path):
return False
with open(path, "r", encoding="utf-8") as fh:
return bool(fh.read().strip())
except OSError:
return False
def _read_default_prompt_text(filename) -> str:
try:
return (
resources.files(DEFAULT_PROMPTS_PACKAGE)
.joinpath(filename)
.read_text(encoding="utf-8")
)
except (FileNotFoundError, ModuleNotFoundError, OSError):
return ""
def _iter_default_cover_templates():
try:
root = resources.files(DEFAULT_COVER_PROMPTS_PACKAGE)
except (ModuleNotFoundError, OSError):
return
for entry in root.iterdir():
if not entry.is_file() or not entry.name.lower().endswith(TEMPLATE_EXT):
continue
name = entry.name[: -len(TEMPLATE_EXT)]
try:
text = entry.read_text(encoding="utf-8")
except OSError:
continue
yield name, text