feat: 完成T-302p提示词管理
新增app/prompts.py,支持标题提示词读写、封面模板列表/读取/保存/重命名/删除,以及旧标题、新标题、商品id、店铺变量替换。
Tab②接入标题提示词启动回显和保存,封面模板下拉、新建、保存、另存为、重命名、删除、插入{新标题}与变量预览;本任务仍不调用AI、不写SQLite。
新增tests/test_prompts.py并扩展GUI测试覆盖提示词文件管理和预览;同步任务看板、API、routes、current-state和progress,下一个任务更新为T-303。
This commit is contained in:
+232
-2
@@ -17,6 +17,7 @@ try:
|
||||
QFormLayout,
|
||||
QHBoxLayout,
|
||||
QHeaderView,
|
||||
QInputDialog,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QMainWindow,
|
||||
@@ -77,7 +78,7 @@ QTabBar::tab:hover:!selected {
|
||||
|
||||
|
||||
if QT_IMPORT_ERROR is None:
|
||||
from . import accounts, appconfig, chrome, db, editor, excel
|
||||
from . import accounts, appconfig, chrome, db, editor, excel, prompts
|
||||
from . import config as account_config
|
||||
|
||||
|
||||
@@ -257,6 +258,14 @@ if QT_IMPORT_ERROR is None:
|
||||
return Qt.NoItemFlags
|
||||
return Qt.ItemIsEnabled | Qt.ItemIsSelectable
|
||||
|
||||
def task_at(self, row):
|
||||
if row < 0 or row >= len(self.tasks):
|
||||
return None
|
||||
return self.tasks[row]
|
||||
|
||||
def account_name_for(self, task):
|
||||
return self._account_name(task)
|
||||
|
||||
def _account_name(self, task):
|
||||
account = self.account_by_alias.get(str(task.alias).strip())
|
||||
if account is not None:
|
||||
@@ -291,26 +300,63 @@ if QT_IMPORT_ERROR is None:
|
||||
("已更新", "applied"),
|
||||
]
|
||||
|
||||
def __init__(self, parent=None, db_path=None, config=None, status_callback=None):
|
||||
def __init__(
|
||||
self,
|
||||
parent=None,
|
||||
db_path=None,
|
||||
config=None,
|
||||
status_callback=None,
|
||||
title_prompt_path=None,
|
||||
cover_prompts_dir=None,
|
||||
):
|
||||
super().__init__(parent)
|
||||
self.config = appconfig.load_config() if config is None else config
|
||||
self.db_path = _database_path(db_path, self.config)
|
||||
self.status_callback = status_callback
|
||||
self.title_prompt_path = title_prompt_path or prompts.TITLE_PROMPT_PATH
|
||||
self.cover_prompts_dir = cover_prompts_dir or prompts.COVER_PROMPTS_DIR
|
||||
self.current_cover_template = None
|
||||
|
||||
self.title_prompt_edit = QPlainTextEdit()
|
||||
self.title_prompt_edit.setObjectName("titlePromptEdit")
|
||||
self.title_prompt_edit.setPlaceholderText("标题提示词")
|
||||
self.title_prompt_edit.setPlainText(
|
||||
prompts.load_title_prompt(self.title_prompt_path)
|
||||
)
|
||||
self.save_title_button = QPushButton("保存标题提示词")
|
||||
self.cover_prompt_edit = QPlainTextEdit()
|
||||
self.cover_prompt_edit.setObjectName("coverPromptEdit")
|
||||
self.cover_prompt_edit.setPlaceholderText("封面提示词")
|
||||
self.cover_template_combo = QComboBox()
|
||||
self.cover_template_combo.setObjectName("coverTemplateCombo")
|
||||
self.new_cover_template_button = QPushButton("新建")
|
||||
self.save_cover_template_button = QPushButton("保存")
|
||||
self.save_cover_template_as_button = QPushButton("另存为")
|
||||
self.rename_cover_template_button = QPushButton("重命名")
|
||||
self.delete_cover_template_button = QPushButton("删除")
|
||||
self.insert_title_button = QPushButton("插入标题")
|
||||
self.preview_prompt_button = QPushButton("预览")
|
||||
|
||||
left_panel = QWidget()
|
||||
left_layout = QVBoxLayout(left_panel)
|
||||
left_layout.setContentsMargins(0, 0, 12, 0)
|
||||
left_layout.addWidget(QLabel("标题提示词"))
|
||||
left_layout.addWidget(self.title_prompt_edit, 1)
|
||||
left_layout.addWidget(self.save_title_button)
|
||||
left_layout.addWidget(QLabel("封面提示词"))
|
||||
left_layout.addWidget(self.cover_template_combo)
|
||||
cover_template_layout = QHBoxLayout()
|
||||
cover_template_layout.addWidget(self.new_cover_template_button)
|
||||
cover_template_layout.addWidget(self.save_cover_template_button)
|
||||
cover_template_layout.addWidget(self.save_cover_template_as_button)
|
||||
cover_template_layout.addWidget(self.rename_cover_template_button)
|
||||
cover_template_layout.addWidget(self.delete_cover_template_button)
|
||||
left_layout.addLayout(cover_template_layout)
|
||||
left_layout.addWidget(self.cover_prompt_edit, 2)
|
||||
cover_action_layout = QHBoxLayout()
|
||||
cover_action_layout.addWidget(self.insert_title_button)
|
||||
cover_action_layout.addWidget(self.preview_prompt_button)
|
||||
left_layout.addLayout(cover_action_layout)
|
||||
|
||||
self.batch_filter = QComboBox()
|
||||
self.batch_filter.setObjectName("batchFilter")
|
||||
@@ -363,13 +409,197 @@ if QT_IMPORT_ERROR is None:
|
||||
self.shop_filter.currentIndexChanged.connect(self.refresh_tasks)
|
||||
self.status_filter.currentIndexChanged.connect(self.refresh_tasks)
|
||||
self.refresh_button.clicked.connect(self.refresh_tasks)
|
||||
self.save_title_button.clicked.connect(self.save_title_prompt)
|
||||
self.cover_template_combo.currentIndexChanged.connect(self.load_selected_cover_template)
|
||||
self.new_cover_template_button.clicked.connect(self.new_cover_template)
|
||||
self.save_cover_template_button.clicked.connect(self.save_cover_template)
|
||||
self.save_cover_template_as_button.clicked.connect(self.save_cover_template_as)
|
||||
self.rename_cover_template_button.clicked.connect(self.rename_cover_template)
|
||||
self.delete_cover_template_button.clicked.connect(self.delete_cover_template)
|
||||
self.insert_title_button.clicked.connect(self.insert_title_placeholder)
|
||||
self.preview_prompt_button.clicked.connect(self.preview_cover_prompt)
|
||||
|
||||
self.refresh_cover_templates()
|
||||
self.refresh_tasks()
|
||||
|
||||
def _set_status(self, message):
|
||||
if self.status_callback is not None:
|
||||
self.status_callback(message)
|
||||
|
||||
def save_title_prompt(self, checked=False):
|
||||
try:
|
||||
prompts.save_title_prompt(
|
||||
self.title_prompt_edit.toPlainText(),
|
||||
self.title_prompt_path,
|
||||
)
|
||||
except Exception as exc:
|
||||
self._show_prompt_error(exc)
|
||||
return
|
||||
self._set_status("标题提示词已保存")
|
||||
|
||||
def refresh_cover_templates(self, selected=None):
|
||||
try:
|
||||
template_names = prompts.list_cover_templates(self.cover_prompts_dir)
|
||||
except Exception as exc:
|
||||
template_names = []
|
||||
self._show_prompt_error(exc)
|
||||
current = selected if selected is not None else self.current_cover_template
|
||||
self.cover_template_combo.blockSignals(True)
|
||||
self.cover_template_combo.clear()
|
||||
if template_names:
|
||||
for name in template_names:
|
||||
self.cover_template_combo.addItem(name, name)
|
||||
index = self.cover_template_combo.findData(current)
|
||||
self.cover_template_combo.setCurrentIndex(index if index >= 0 else 0)
|
||||
else:
|
||||
self.cover_template_combo.addItem("默认", None)
|
||||
self.cover_template_combo.setCurrentIndex(0)
|
||||
self.cover_template_combo.blockSignals(False)
|
||||
self.load_selected_cover_template()
|
||||
|
||||
def load_selected_cover_template(self, index=None):
|
||||
name = self.cover_template_combo.currentData()
|
||||
self.current_cover_template = name
|
||||
if name is None:
|
||||
self.cover_prompt_edit.setPlainText("")
|
||||
return
|
||||
try:
|
||||
self.cover_prompt_edit.setPlainText(
|
||||
prompts.load_cover_template(name, self.cover_prompts_dir)
|
||||
)
|
||||
except Exception as exc:
|
||||
self.cover_prompt_edit.setPlainText("")
|
||||
self._show_prompt_error(exc)
|
||||
|
||||
def new_cover_template(self, checked=False):
|
||||
name = self._ask_template_name("新建封面提示词模板")
|
||||
if not name:
|
||||
return
|
||||
try:
|
||||
prompts.save_cover_template(name, "", self.cover_prompts_dir)
|
||||
except Exception as exc:
|
||||
self._show_prompt_error(exc)
|
||||
return
|
||||
self.refresh_cover_templates(selected=name)
|
||||
self._set_status(f"封面提示词模板已新建:{name}")
|
||||
|
||||
def save_cover_template(self, checked=False):
|
||||
name = self.current_cover_template
|
||||
if name is None:
|
||||
self.save_cover_template_as()
|
||||
return
|
||||
try:
|
||||
prompts.save_cover_template(
|
||||
name,
|
||||
self.cover_prompt_edit.toPlainText(),
|
||||
self.cover_prompts_dir,
|
||||
)
|
||||
except Exception as exc:
|
||||
self._show_prompt_error(exc)
|
||||
return
|
||||
self._set_status(f"封面提示词模板已保存:{name}")
|
||||
|
||||
def save_cover_template_as(self, checked=False):
|
||||
name = self._ask_template_name("另存封面提示词模板")
|
||||
if not name:
|
||||
return
|
||||
try:
|
||||
prompts.save_cover_template(
|
||||
name,
|
||||
self.cover_prompt_edit.toPlainText(),
|
||||
self.cover_prompts_dir,
|
||||
)
|
||||
except Exception as exc:
|
||||
self._show_prompt_error(exc)
|
||||
return
|
||||
self.refresh_cover_templates(selected=name)
|
||||
self._set_status(f"封面提示词模板已另存为:{name}")
|
||||
|
||||
def rename_cover_template(self, checked=False):
|
||||
old_name = self.current_cover_template
|
||||
if old_name is None:
|
||||
self._set_status("没有可重命名的封面提示词模板")
|
||||
return
|
||||
new_name = self._ask_template_name("重命名封面提示词模板", text=old_name)
|
||||
if not new_name or new_name == old_name:
|
||||
return
|
||||
try:
|
||||
prompts.rename_cover_template(old_name, new_name, self.cover_prompts_dir)
|
||||
except Exception as exc:
|
||||
self._show_prompt_error(exc)
|
||||
return
|
||||
self.refresh_cover_templates(selected=new_name)
|
||||
self._set_status(f"封面提示词模板已重命名:{new_name}")
|
||||
|
||||
def delete_cover_template(self, checked=False):
|
||||
name = self.current_cover_template
|
||||
if name is None:
|
||||
self._set_status("没有可删除的封面提示词模板")
|
||||
return
|
||||
choice = QMessageBox.question(
|
||||
self,
|
||||
"删除封面提示词模板",
|
||||
f"确定删除「{name}」吗?",
|
||||
)
|
||||
if choice != QMessageBox.Yes:
|
||||
return
|
||||
try:
|
||||
prompts.delete_cover_template(name, self.cover_prompts_dir)
|
||||
except Exception as exc:
|
||||
self._show_prompt_error(exc)
|
||||
return
|
||||
self.refresh_cover_templates()
|
||||
self._set_status(f"封面提示词模板已删除:{name}")
|
||||
|
||||
def insert_title_placeholder(self, checked=False):
|
||||
self.cover_prompt_edit.insertPlainText("{新标题}")
|
||||
|
||||
def preview_cover_prompt(self, checked=False):
|
||||
task = self._selected_task()
|
||||
if task is None:
|
||||
self._set_status("没有可预览的任务")
|
||||
return
|
||||
rendered = prompts.render_prompt(
|
||||
self.cover_prompt_edit.toPlainText(),
|
||||
self._prompt_context(task),
|
||||
)
|
||||
QMessageBox.information(self, "封面提示词预览", rendered)
|
||||
self._set_status("封面提示词预览已生成")
|
||||
|
||||
def _selected_task(self):
|
||||
index = self.task_table.currentIndex()
|
||||
if index.isValid():
|
||||
return self.model.task_at(index.row())
|
||||
if self.model.rowCount() > 0:
|
||||
return self.model.task_at(0)
|
||||
return None
|
||||
|
||||
def _prompt_context(self, task):
|
||||
return {
|
||||
"old_title": task.old_title,
|
||||
"new_title": task.new_title,
|
||||
"item_id": task.item_id,
|
||||
"account_name": self.model.account_name_for(task),
|
||||
"alias": task.alias,
|
||||
}
|
||||
|
||||
def _ask_template_name(self, title, text=""):
|
||||
value, ok = QInputDialog.getText(
|
||||
self,
|
||||
title,
|
||||
"模板名",
|
||||
QLineEdit.Normal,
|
||||
text,
|
||||
)
|
||||
if not ok:
|
||||
return None
|
||||
return str(value).strip()
|
||||
|
||||
def _show_prompt_error(self, error):
|
||||
message = str(error)
|
||||
QMessageBox.warning(self, "提示词管理", message)
|
||||
self._set_status(message)
|
||||
|
||||
def refresh_tasks(self, checked=False):
|
||||
try:
|
||||
db.init_db(self.db_path)
|
||||
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
"""Prompt file management and variable rendering."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
|
||||
TITLE_PROMPT_PATH = "title_prompt.txt"
|
||||
COVER_PROMPTS_DIR = os.path.join("prompts", "cover")
|
||||
TEMPLATE_EXT = ".txt"
|
||||
INVALID_NAME_CHARS = set('\\/:*?"<>|')
|
||||
|
||||
|
||||
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 ""))
|
||||
|
||||
|
||||
def list_cover_templates(directory=COVER_PROMPTS_DIR):
|
||||
"""Return cover template names sorted by display name."""
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def load_cover_template(name, directory=COVER_PROMPTS_DIR) -> str:
|
||||
"""Load one cover prompt template."""
|
||||
|
||||
path = _template_path(name, directory)
|
||||
if not os.path.exists(path):
|
||||
raise PromptError(f"封面提示词模板不存在: {_normalize_name(name)}")
|
||||
with open(path, "r", encoding="utf-8") as fh:
|
||||
return fh.read()
|
||||
|
||||
|
||||
def save_cover_template(name, text, directory=COVER_PROMPTS_DIR) -> None:
|
||||
"""Save one cover prompt template as UTF-8."""
|
||||
|
||||
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 ""))
|
||||
|
||||
|
||||
def rename_cover_template(old, new, directory=COVER_PROMPTS_DIR) -> None:
|
||||
"""Rename a cover prompt template with duplicate-name protection."""
|
||||
|
||||
old_path = _template_path(old, directory)
|
||||
new_path = _template_path(new, directory)
|
||||
if not os.path.exists(old_path):
|
||||
raise PromptError(f"封面提示词模板不存在: {_normalize_name(old)}")
|
||||
if os.path.exists(new_path):
|
||||
raise PromptError(f"封面提示词模板已存在: {_normalize_name(new)}")
|
||||
os.makedirs(os.path.dirname(new_path), exist_ok=True)
|
||||
os.replace(old_path, new_path)
|
||||
|
||||
|
||||
def delete_cover_template(name, directory=COVER_PROMPTS_DIR) -> None:
|
||||
"""Delete one cover prompt template."""
|
||||
|
||||
path = _template_path(name, directory)
|
||||
if not os.path.exists(path):
|
||||
raise PromptError(f"封面提示词模板不存在: {_normalize_name(name)}")
|
||||
os.remove(path)
|
||||
|
||||
|
||||
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:
|
||||
raise PromptError("封面提示词模板名不能为空")
|
||||
if value in {".", ".."} or any(char in INVALID_NAME_CHARS for char in value):
|
||||
raise PromptError(f"封面提示词模板名非法: {value}")
|
||||
if os.path.basename(value) != value:
|
||||
raise PromptError(f"封面提示词模板名非法: {value}")
|
||||
return value
|
||||
+1
-1
@@ -61,7 +61,7 @@
|
||||
| --- | --- | --- | --- | --- |
|
||||
| T-301 | 确定 AI 服务商/模型并接入 `app/ai.py`(`gen_title`/`gen_cover`,带重试/分辨率/jpg质量) | T-005 | 从 `config/ai_models.json` 读取模型与本地明文 Key;`gen_cover` 支持 resolution+jpg_quality;失败按 retry 重试;错误明确;日志脱敏 | DONE |
|
||||
| T-302 | Tab② 左右布局:左提示词(标题/封面),右按批次/店铺/状态筛选 + 任务列表 | T-301, T-203 | 左 ~1/4 提示词多行;右筛选+列表(店铺/商品id/旧标题/新标题/状态) | DONE |
|
||||
| T-302p | `app/prompts.py` + Tab② 提示词管理 | T-302 | 标题保存/启动回显 title_prompt.txt;封面多模板(下拉+新建/保存/另存为/重命名/删除,存 prompts/cover/);插入 `{新标题}`;预览变量替换;render_prompt 接入生成 | TODO |
|
||||
| T-302p | `app/prompts.py` + Tab② 提示词管理 | T-302 | 标题保存/启动回显 title_prompt.txt;封面多模板(下拉+新建/保存/另存为/重命名/删除,存 prompts/cover/);插入 `{新标题}`;预览变量替换;render_prompt 接入生成 | DONE |
|
||||
| T-303 | Tab② 开始生成(单按钮)+ 停止 + 进度:**先并发标题再并发图片** | T-302, T-104b | `generate_batch` 先 title_concurrency 并发标题、再 image_concurrency 并发图片;worker/signal 回传进度;每条 set_generated 立即写库;停止可取消未开始项;进度 标题/封面/失败 计数;双击弹窗看新旧封面 | TODO |
|
||||
|
||||
## Phase 4 · 更新 shopee(③)
|
||||
|
||||
+16
-9
@@ -247,19 +247,21 @@ generate_batch(tasks, prompts, ai_cfg, on_progress, should_stop) -> None
|
||||
- 调用有成本与失败可能:超时、限流、内容安全拒绝都要返回明确错误。
|
||||
- 生成结果**直接进入 ③ 更新候选**;③ 点击「开始更新」后弹窗批量确认,确认后提交线上。本地留档 + 回写 Excel 供追溯。
|
||||
|
||||
## prompts 模块(`app/prompts.py`,待建)
|
||||
## prompts 模块(`app/prompts.py`,已建)
|
||||
|
||||
```python
|
||||
class PromptError(RuntimeError): ...
|
||||
|
||||
# 标题提示词:单文件
|
||||
load_title_prompt(path="title_prompt.txt") -> str # 启动回显;缺失返回 ""
|
||||
save_title_prompt(text, path="title_prompt.txt") -> None # 「保存」按钮
|
||||
|
||||
# 封面提示词:多模板(prompts/cover/<名称>.txt)
|
||||
list_cover_templates() -> list[str] # 模板名列表(下拉用)
|
||||
load_cover_template(name) -> str
|
||||
save_cover_template(name, text) -> None # 保存 / 另存为
|
||||
rename_cover_template(old, new) -> None # 重名校验,重复则报错
|
||||
delete_cover_template(name) -> None # 删除(二次确认由 GUI 负责)
|
||||
list_cover_templates(directory="prompts/cover") -> list[str] # 模板名列表(下拉用)
|
||||
load_cover_template(name, directory="prompts/cover") -> str
|
||||
save_cover_template(name, text, directory="prompts/cover") -> None
|
||||
rename_cover_template(old, new, directory="prompts/cover") -> None
|
||||
delete_cover_template(name, directory="prompts/cover") -> None
|
||||
|
||||
# 变量替换
|
||||
render_prompt(template_text, task) -> str
|
||||
@@ -271,6 +273,8 @@ render_prompt(template_text, task) -> str
|
||||
- 「插入标题」在封面提示词光标处插入 `{新标题}`;「预览」对选中任务调用 `render_prompt` 后展示。
|
||||
- 生成封面时 `gen_cover` 的 prompt = `render_prompt(当前封面模板, task)`。
|
||||
- 模板与 `title_prompt.txt` 均为可手改的纯文本文件。
|
||||
- `list_cover_templates()` 不会在启动时创建文件;只有保存/新建/另存为才写 `prompts/cover/*.txt`。
|
||||
- 模板名不可为空,不允许路径分隔符、`..` 或 Windows 非法文件名字符;重命名时目标重名会报错。
|
||||
|
||||
## gui 模块(`app/gui.py`,已建,PySide6)
|
||||
|
||||
@@ -279,7 +283,7 @@ render_prompt(template_text, task) -> str
|
||||
main() -> int # 创建 QApplication + MainWindow
|
||||
class MainWindow(QMainWindow) # QTabWidget: ①②③④⑤;支持注入 db_path/config 便于测试
|
||||
class CollectTab(QWidget) # ① 导入采集:导入 Excel + 汇总栏 + QTableView 任务列表 + 未匹配略过标记
|
||||
class GenerateTab(QWidget) # ② AI生成:左标题/封面提示词,右批次/店铺/状态筛选 + 任务列表
|
||||
class GenerateTab(QWidget) # ② AI生成:提示词管理 + 批次/店铺/状态筛选 + 任务列表
|
||||
class CollectWorker(BaseWorker) # ① 后台采集:账号就绪预检 -> editor.collect -> db.set_collected/mark_skipped/mark_failed
|
||||
class WriteBackWorker(BaseWorker) # ① 后台回写:excel.write_back(batch_id) 写旧标题/旧封面到原 Excel
|
||||
class TaskTableModel(QAbstractTableModel) # 任务表格模型:账号/别名/商品ID/阶段;未匹配别名显示“略过”
|
||||
@@ -313,12 +317,15 @@ TAB_STYLE: str # 顶层 Tab 栏防误点样式:
|
||||
- 「回写旧数据到 Excel」通过 `WriteBackWorker` 后台调用 `excel.write_back()`,把已采集旧标题/旧封面路径按原 Excel 行定位写回;该按钮主要作为自动回写失败后的手动重试入口。原文件被占用时弹窗提示关闭后重试,SQLite 采集结果不回滚。
|
||||
- 采集前由 `CollectWorker` 做账号就绪预检:无账号、当前批次匹配账号未启动 CDP 端口或未登录时,返回 `blocked=True`,GUI 弹窗汇总并跳转/引导去④账号管理;不无提示批量启动所有账号 Chrome。匹配账号未登录属于预检阻断,不是逐条 skipped。
|
||||
|
||||
② AI生成当前要点(T-302):
|
||||
② AI生成当前要点(T-302/T-302p):
|
||||
|
||||
- 左右 `QSplitter`:左侧约 1/4 为标题提示词、封面提示词两个多行输入;右侧为筛选栏 + 任务列表。
|
||||
- 标题提示词启动时从 `title_prompt.txt` 回显;点击「保存标题提示词」写回该文件。
|
||||
- 封面提示词模板下拉读取 `prompts/cover/*.txt`;支持新建、保存、另存为、重命名、删除。删除由 GUI 二次确认,删空后下拉显示内存态“默认”,不会自动建文件。
|
||||
- 「插入标题」在封面提示词光标处插入 `{新标题}`;「预览」使用当前选中任务(无选择则用第一条)调用 `prompts.render_prompt()` 并弹窗展示。
|
||||
- 筛选栏包含:批次、店铺、状态、刷新。批次来自 `db.list_batches()`;店铺来自当前任务别名并优先显示匹配账号名;状态支持全部/待生成/已生成/失败/略过/已更新。
|
||||
- 任务列表使用 `QTableView + GenerateTaskTableModel`,列为:店铺、商品ID、旧标题、新标题、状态。`stage=collected` 显示“待生成”,`stage=generated` 显示“已生成”,`status=failed/skipped/running` 优先显示对应状态。
|
||||
- T-302 只实现布局与只读列表筛选,不调用 `app.ai`、不写 SQLite;提示词保存/模板管理留给 T-302p,开始生成/停止/进度与 `set_generated()` 留给 T-303。
|
||||
- T-302/T-302p 不调用 `app.ai`、不写 SQLite;开始生成/停止/进度与 `set_generated()` 留给 T-303。
|
||||
|
||||
## workers 模块(`app/workers.py`,已建,PySide6)
|
||||
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
## 当前快照
|
||||
|
||||
- 日期:2026-06-27
|
||||
- 阶段:V0 单账号 CDP 流程已验证;V1 已完成 T-000 正式代码包结构、T-001 `app/editor.py` 模块化、T-002 `app/appconfig.py` 应用配置、T-003 SQLite 持久化地基、T-004 本地数据忽略规则、T-005 AI 模型清单后端、T-006 单元测试基座、T-101 账号 user-data-dir 工具、T-102 Chrome 启动器、T-103 登录保活与检测、T-104 PySide6 主窗口骨架、T-104b PySide6 worker 基座、T-105 Tab④ 账号管理、T-106 账号快捷方式、T-201 Excel 导入入库、T-202 Tab① 任务列表与导入按钮、T-202b Tab① 导入汇总栏、T-203 采集旧标题旧封面、T-204 回写旧字段到原 Excel、T-204b 采集完成自动回写、T-205 首次未配账号/Chrome 未启动/未登录引导保护、T-301 AI 生成接口、T-302 Tab② AI 生成布局与任务列表。
|
||||
- 阶段:V0 单账号 CDP 流程已验证;V1 已完成 T-000 正式代码包结构、T-001 `app/editor.py` 模块化、T-002 `app/appconfig.py` 应用配置、T-003 SQLite 持久化地基、T-004 本地数据忽略规则、T-005 AI 模型清单后端、T-006 单元测试基座、T-101 账号 user-data-dir 工具、T-102 Chrome 启动器、T-103 登录保活与检测、T-104 PySide6 主窗口骨架、T-104b PySide6 worker 基座、T-105 Tab④ 账号管理、T-106 账号快捷方式、T-201 Excel 导入入库、T-202 Tab① 任务列表与导入按钮、T-202b Tab① 导入汇总栏、T-203 采集旧标题旧封面、T-204 回写旧字段到原 Excel、T-204b 采集完成自动回写、T-205 首次未配账号/Chrome 未启动/未登录引导保护、T-301 AI 生成接口、T-302 Tab② AI 生成布局与任务列表、T-302p 提示词管理。
|
||||
- 技术栈:Python 3.10+,自研 CDP(websocket-client + requests),SQLite(sqlite3)+ `config.json` + openpyxl + AI(`config/ai_models.json` 通用 HTTP,chat JSON / images_edits),GUI PySide6 5 Tab(已定)。
|
||||
- 生产代码:已建立 `app/` 包 + 根入口 `main.py`;`app/cdp.py` 为已验证 CDP 底座;`app/editor.py` 已封装登录状态检测、标题/封面/采集/更新按钮能力;`app/appconfig.py` 已实现 `config.json` 默认值/读写/更新、AI 参数与端口读取,以及 `config/ai_models.json` 模型清单 CRUD/过滤/打码/测试连接;`app/ai.py` 已实现 `gen_title()`/`gen_cover()`,按默认文本/图片模型发起通用 HTTP 调用,支持重试、错误脱敏、图片 URL/base64 解析、resolution resize 与 jpg_quality 保存;`app/db.py` 已实现 SQLite schema、连接 PRAGMA、批次/账号/任务与阶段写库函数;`app/excel.py` 已实现多 Excel 输入列解析、整文件列校验、脏行统计跳过、导入批次与任务入库、别名匹配统计、旧标题/旧封面路径回写原 Excel 与另存副本;`app/config.py` 已实现账号 slug 与 user-data-dir 创建;`app/accounts.py` 已实现账号 CRUD 服务、端口默认分配、启动登录、检测登录、生成快捷方式;`app/chrome.py` 已实现 Chrome 参数拼装、启动、CDP 端口探测、PowerShell `.lnk` 快捷方式生成;`app/gui.py` 已实现 PySide6 `MainWindow`、五 Tab、顶部 Tab 栏防误点样式、① 导入采集的 Excel 导入按钮/导入汇总栏/QTableView 任务列表/未匹配筛选与略过标记/采集旧标题旧封面 worker/采集前账号就绪预检与④引导/采集完成自动回写/旧数据回写重试按钮与 worker、② AI生成左右布局/标题与封面提示词多行输入/批次店铺状态筛选/任务列表、④ 账号管理表格/弹窗/按钮/快捷方式与状态栏;`app/workers.py` 已实现 `BaseWorker`、通用 signals、取消标记和 `QThread` 启动包装。
|
||||
- 测试:`tests/` 已建立;T-006 后纯逻辑改动必须运行 `python -m unittest discover -s tests`,当前覆盖 appconfig/db/config/accounts/chrome 启动与快捷方式/editor 登录检测/excel 导入/ai 标题与封面 HTTP 解析/gui ① 导入采集/gui ② AI生成布局与筛选/gui ④ 账号管理/worker signal 与线程包装,并对尚未实现的 app.prompts 做契约占位 skip;CDP/Shopee 改动仍需测试商品手动验证。
|
||||
- 生产代码:已建立 `app/` 包 + 根入口 `main.py`;`app/cdp.py` 为已验证 CDP 底座;`app/editor.py` 已封装登录状态检测、标题/封面/采集/更新按钮能力;`app/appconfig.py` 已实现 `config.json` 默认值/读写/更新、AI 参数与端口读取,以及 `config/ai_models.json` 模型清单 CRUD/过滤/打码/测试连接;`app/ai.py` 已实现 `gen_title()`/`gen_cover()`,按默认文本/图片模型发起通用 HTTP 调用,支持重试、错误脱敏、图片 URL/base64 解析、resolution resize 与 jpg_quality 保存;`app/prompts.py` 已实现标题提示词读写、封面模板 CRUD 与变量替换;`app/db.py` 已实现 SQLite schema、连接 PRAGMA、批次/账号/任务与阶段写库函数;`app/excel.py` 已实现多 Excel 输入列解析、整文件列校验、脏行统计跳过、导入批次与任务入库、别名匹配统计、旧标题/旧封面路径回写原 Excel 与另存副本;`app/config.py` 已实现账号 slug 与 user-data-dir 创建;`app/accounts.py` 已实现账号 CRUD 服务、端口默认分配、启动登录、检测登录、生成快捷方式;`app/chrome.py` 已实现 Chrome 参数拼装、启动、CDP 端口探测、PowerShell `.lnk` 快捷方式生成;`app/gui.py` 已实现 PySide6 `MainWindow`、五 Tab、顶部 Tab 栏防误点样式、① 导入采集的 Excel 导入按钮/导入汇总栏/QTableView 任务列表/未匹配筛选与略过标记/采集旧标题旧封面 worker/采集前账号就绪预检与④引导/采集完成自动回写/旧数据回写重试按钮与 worker、② AI生成左右布局/标题与封面提示词管理/批次店铺状态筛选/任务列表/变量预览、④ 账号管理表格/弹窗/按钮/快捷方式与状态栏;`app/workers.py` 已实现 `BaseWorker`、通用 signals、取消标记和 `QThread` 启动包装。
|
||||
- 测试:`tests/` 已建立;T-006 后纯逻辑改动必须运行 `python -m unittest discover -s tests`,当前覆盖 appconfig/db/config/accounts/chrome 启动与快捷方式/editor 登录检测/excel 导入/ai 标题与封面 HTTP 解析/prompts 读写与渲染/gui ① 导入采集/gui ② AI生成布局筛选与提示词管理/gui ④ 账号管理/worker signal 与线程包装;CDP/Shopee 改动仍需测试商品手动验证。
|
||||
- 数据:`config.json`、`config/ai_models.json`、`cmshopee.db`、`chrome_user_data_dir/`、`images/` 已由 `.gitignore` 排除;运营填写后的 Excel 业务文件默认忽略,标准空模板 `shopee待处理任务模板.xlsx` 可提交;`app/appconfig.py` 首次读取缺失的 `config.json` 时会在本地写默认配置,`app/db.py` 调用 `init_db()` 时会在本地创建 SQLite DB。
|
||||
|
||||
## 既定设计要点(文档已定)
|
||||
@@ -32,16 +32,17 @@
|
||||
| `prototypes/` | 已有 | 已验证原型/探查脚本(demo/set_title/set_cover/get_title/cookies/inspect_images/grab/1.py),保留作人工回归与探查参考;见 `prototypes/README.md` |
|
||||
| `chrome-remote-debug-lan.md` | 已有 | WSL→Windows CDP 转发排查记录 |
|
||||
| `app/__init__.py` / `app/__main__.py` / `main.py` | 已有 | 正式包与启动入口;`python main.py` / `python -m app` 可运行占位入口 |
|
||||
| `app/gui.py` | 已有 | T-104/T-105/T-106/T-202/T-202b/T-203/T-204/T-204b/T-205/T-302 产出:PySide6 `QMainWindow` + 五 Tab;顶部 Tab 栏防误点样式;① 导入采集导入按钮、导入汇总栏、`QTableView` 任务列表、未匹配筛选与略过标记、采集旧标题旧封面 worker、采集前账号就绪预检与④引导、采集完成自动回写与手动重试;② AI生成左右布局、提示词多行输入、筛选栏和任务列表;④ 账号管理表格、账号弹窗、启动登录、检测登录、快捷方式 |
|
||||
| `app/gui.py` | 已有 | T-104/T-105/T-106/T-202/T-202b/T-203/T-204/T-204b/T-205/T-302/T-302p 产出:PySide6 `QMainWindow` + 五 Tab;顶部 Tab 栏防误点样式;① 导入采集导入按钮、导入汇总栏、`QTableView` 任务列表、未匹配筛选与略过标记、采集旧标题旧封面 worker、采集前账号就绪预检与④引导、采集完成自动回写与手动重试;② AI生成左右布局、提示词管理、筛选栏和任务列表;④ 账号管理表格、账号弹窗、启动登录、检测登录、快捷方式 |
|
||||
| `app/workers.py` | 已有 | T-104b 产出:`BaseWorker` + 通用 signals + 取消标记 + `run_worker()` QThread 包装 |
|
||||
| `app/accounts.py` | 已有 | T-105/T-106 产出:账号 CRUD 服务、目录创建、端口分配、启动登录、检测登录、快捷方式 |
|
||||
| `app/editor.py` | 已有 | T-001/T-103 产出:登录状态检测、打开商品页、读/写标题、读/下载封面、上传拖封面、更新按钮、apply_task |
|
||||
| `app/appconfig.py` | 已有 | T-002 产出:`config.json` 默认值、读写、更新、路径/端口/AI 参数读取;拒绝敏感字段写入 |
|
||||
| `app/ai.py` | 已有 | T-301 产出:`gen_title()`/`gen_cover()`;读取默认模型;通用 HTTP 调用;失败重试;错误脱敏;封面按 resolution/jpg_quality 保存 |
|
||||
| `app/prompts.py` | 已有 | T-302p 产出:标题提示词读写、封面模板列表/读取/保存/重命名/删除、变量替换 |
|
||||
| `app/db.py` | 已有 | T-003 产出:batches/accounts/tasks schema;WAL/busy_timeout/foreign_keys;账号/批次/任务与 set_* 阶段写库 |
|
||||
| `app/config.py` | 已有 | T-101 产出:别名→稳定 slug;创建并返回绝对 user-data-dir |
|
||||
| `app/chrome.py` | 已有 | T-102/T-106 产出:Chrome 启动参数、`subprocess.Popen` 启动、`/json/version` 端口探测、PowerShell `.lnk` 快捷方式 |
|
||||
| `tests/` | 已有 | T-006/T-201/T-202/T-202b/T-203/T-204/T-204b/T-205/T-301/T-302 产出:stdlib unittest 基座;覆盖 appconfig/db/config/accounts/chrome/editor/excel/ai/gui/workers;prompts 模块契约占位测试 |
|
||||
| `tests/` | 已有 | T-006/T-201/T-202/T-202b/T-203/T-204/T-204b/T-205/T-301/T-302/T-302p 产出:stdlib unittest 基座;覆盖 appconfig/db/config/accounts/chrome/editor/excel/ai/prompts/gui/workers |
|
||||
| `app/excel.py` | 已有 | T-201/T-204 产出:多文件 Excel 输入列解析、必需列整文件拒绝、脏行逐行跳过、批次/任务入库、匹配统计;按源文件/工作表/行号回写旧标题与旧封面路径;支持原文件被占用时另存副本 |
|
||||
| `shopee待处理任务模板.xlsx` | 已有,已提交 | 标准空 Excel 模板;单工作表 `待处理任务`,表头 `账号名 | 别名 | 商品id | 旧标题 | 旧封面图片路径 | 新标题 | 新封面图片路径 | 更新状态`;运营复制后填写,填写副本不提交 |
|
||||
| `config.json` / `config/ai_models.json` / `cmshopee.db` / `chrome_user_data_dir/` / `images/` | 本地存在或按需生成,已忽略 | 含配置、密钥、业务、登录态、图片,不提交版本库 |
|
||||
@@ -59,9 +60,9 @@
|
||||
|
||||
任务状态以 [`06-tasks.md`](06-tasks.md) 为准,历史记录见 [`../progress.md`](../progress.md)。
|
||||
|
||||
- 已完成:T-000(正式代码包结构)、T-001(`app/editor.py` 模块化)、T-002(`app/appconfig.py` + `config.json`)、T-003(SQLite 建表)、T-004(本地数据 gitignore)、T-005(AI 模型清单后端)、T-006(单元测试基座)、T-101(账号 slug/user-data-dir)、T-102(Chrome 启动器)、T-103(登录保活与检测)、T-104(PySide6 五 Tab 主窗口骨架)、T-104b(PySide6 worker 基座)、T-105(Tab④ 账号管理)、T-106(账号快捷方式)、T-201(Excel 导入:解析多文件输入列入库)、T-202(Tab① 任务列表 + 导入按钮 + 别名匹配标记)、T-202b(Tab① 导入汇总栏)、T-203(采集旧标题+旧封面)、T-204(回写旧字段到原 Excel)、T-204b(采集完成自动回写旧字段)、T-205(首次未配账号 / Chrome 未启动 / 未登录引导保护)、T-301(AI 生成接口)、T-302(Tab② 左右布局与任务列表)。
|
||||
- 已完成:T-000(正式代码包结构)、T-001(`app/editor.py` 模块化)、T-002(`app/appconfig.py` + `config.json`)、T-003(SQLite 建表)、T-004(本地数据 gitignore)、T-005(AI 模型清单后端)、T-006(单元测试基座)、T-101(账号 slug/user-data-dir)、T-102(Chrome 启动器)、T-103(登录保活与检测)、T-104(PySide6 五 Tab 主窗口骨架)、T-104b(PySide6 worker 基座)、T-105(Tab④ 账号管理)、T-106(账号快捷方式)、T-201(Excel 导入:解析多文件输入列入库)、T-202(Tab① 任务列表 + 导入按钮 + 别名匹配标记)、T-202b(Tab① 导入汇总栏)、T-203(采集旧标题+旧封面)、T-204(回写旧字段到原 Excel)、T-204b(采集完成自动回写旧字段)、T-205(首次未配账号 / Chrome 未启动 / 未登录引导保护)、T-301(AI 生成接口)、T-302(Tab② 左右布局与任务列表)、T-302p(提示词管理)。
|
||||
- 正在进行:无。
|
||||
- 下一个可领取任务:**T-302p(`app/prompts.py` + Tab② 提示词管理)**。
|
||||
- 下一个可领取任务:**T-303(Tab② 开始生成 + 停止 + 进度)**。
|
||||
|
||||
## 当前已知限制
|
||||
|
||||
|
||||
+1
-1
@@ -148,7 +148,7 @@
|
||||
| --- | --- | --- |
|
||||
| `MainWindow(QMainWindow)` | 根窗口 | 持有 `QTabWidget`、状态栏、全局消息 |
|
||||
| `CollectTab(QWidget)` | ① | 导入、任务表、采集、回写 |
|
||||
| `GenerateTab(QWidget)` | ② | 左提示词 + 右筛选/任务列表;双击看图与开始生成由后续 T-303 接入 |
|
||||
| `GenerateTab(QWidget)` | ② | 左提示词管理 + 右筛选/任务列表;双击看图与开始生成由后续 T-303 接入 |
|
||||
| `ApplyTab(QWidget)` | ③ | 已生成任务、开始更新确认、换标题+封面+提交、回写 |
|
||||
| `AccountsTab(QWidget)` | ④ | 账号增删改、启动登录、检测登录、生成快捷方式 |
|
||||
| `SettingsTab(QWidget)` | ⑤ | AI/目录/Chrome 配置 |
|
||||
|
||||
@@ -490,3 +490,12 @@
|
||||
- 测试:`tests/test_gui.py` 增加 MainWindow 挂载②、提示词多行输入、任务列表展示,以及按批次/店铺/状态筛选的覆盖。
|
||||
- 文档:`docs/06-tasks.md` 将 T-302 标为 DONE;同步 `docs/api.md`、`docs/current-state.md`,下一个可领取任务更新为 T-302p。
|
||||
- 验证:`python -m unittest discover -s tests -p "test_gui.py"` 通过(20 tests);`python -m compileall app main.py tests` 通过;`python -m unittest discover -s tests` 通过(65 tests,skipped=1);`py -3 -m compileall app main.py tests` 通过;`py -3 -m unittest discover -s tests` 通过(37 tests,skipped=5,py -3 环境缺 openpyxl/PySide6/Pillow,相关测试按设计跳过)。
|
||||
|
||||
## 【2026-06-27】T-302p Tab② 提示词管理
|
||||
|
||||
- 状态:DONE
|
||||
- 变更:新增 `app/prompts.py`,实现标题提示词 `title_prompt.txt` 读写、封面模板 `prompts/cover/*.txt` 列表/读取/保存/重命名/删除,以及 `{旧标题}`、`{新标题}`、`{商品id}`、`{店铺}` 变量替换。模板名做空值、路径分隔符、`..` 与 Windows 非法字符校验;列表读取不自动创建文件。
|
||||
- GUI:`GenerateTab` 启动时回显标题提示词;封面提示词增加模板下拉、新建、保存、另存为、重命名、删除、插入 `{新标题}`、预览。预览使用选中任务渲染变量并弹窗展示;删除模板先二次确认。T-302p 仍不调用 AI、不写 SQLite,生成执行留给 T-303。
|
||||
- 测试:新增 `tests/test_prompts.py`;`tests/test_gui.py` 覆盖标题回显/保存、封面模板另存/重命名/删除、插入标题与变量预览。
|
||||
- 文档:`docs/06-tasks.md` 将 T-302p 标为 DONE;同步 `docs/api.md`、`docs/routes.md`、`docs/current-state.md`,下一个可领取任务更新为 T-303。
|
||||
- 验证:`python -m unittest discover -s tests -p "test_prompts.py"` 通过(3 tests);`python -m unittest discover -s tests -p "test_gui.py"` 通过(21 tests);`python -m compileall app main.py tests` 通过;`python -m unittest discover -s tests` 通过(69 tests);`py -3 -m compileall app main.py tests` 通过;`py -3 -m unittest discover -s tests` 通过(40 tests,skipped=4,py -3 环境缺 openpyxl/PySide6/Pillow,相关测试按设计跳过)。
|
||||
|
||||
+85
-2
@@ -9,11 +9,12 @@ sys.path.insert(0, os.path.dirname(__file__))
|
||||
from _helpers import TempDirMixin
|
||||
|
||||
from app import gui
|
||||
from app import accounts, db
|
||||
from app import accounts, db, prompts
|
||||
|
||||
if gui.QT_IMPORT_ERROR is not None:
|
||||
raise unittest.SkipTest("PySide6 未安装")
|
||||
|
||||
from PySide6.QtGui import QTextCursor
|
||||
from PySide6.QtWidgets import QApplication, QLineEdit, QPlainTextEdit, QTableView
|
||||
|
||||
from app.gui import (
|
||||
@@ -75,7 +76,13 @@ class GuiTests(TempDirMixin, unittest.TestCase):
|
||||
|
||||
def test_generate_tab_has_prompt_editors_and_task_table(self):
|
||||
with self.make_temp_dir() as temp_dir:
|
||||
tab = GenerateTab(config=self.make_config(temp_dir))
|
||||
title_prompt_path = os.path.join(temp_dir, "title_prompt.txt")
|
||||
cover_prompts_dir = os.path.join(temp_dir, "prompts", "cover")
|
||||
tab = GenerateTab(
|
||||
config=self.make_config(temp_dir),
|
||||
title_prompt_path=title_prompt_path,
|
||||
cover_prompts_dir=cover_prompts_dir,
|
||||
)
|
||||
self.addCleanup(tab.close)
|
||||
|
||||
self.assertIsInstance(tab.title_prompt_edit, QPlainTextEdit)
|
||||
@@ -83,11 +90,87 @@ class GuiTests(TempDirMixin, unittest.TestCase):
|
||||
self.assertIsInstance(tab.task_table, QTableView)
|
||||
self.assertEqual("标题提示词", tab.title_prompt_edit.placeholderText())
|
||||
self.assertEqual("封面提示词", tab.cover_prompt_edit.placeholderText())
|
||||
self.assertEqual("保存标题提示词", tab.save_title_button.text())
|
||||
self.assertEqual("默认", tab.cover_template_combo.currentText())
|
||||
self.assertEqual(["店铺", "商品ID", "旧标题", "新标题", "状态"], tab.model.HEADERS)
|
||||
self.assertEqual("任务 0/0 条", tab.summary_label.text())
|
||||
|
||||
self.assert_removed(temp_dir)
|
||||
|
||||
def test_generate_tab_manages_prompt_files_and_preview(self):
|
||||
with self.make_temp_dir() as temp_dir:
|
||||
cfg = self.make_config(temp_dir)
|
||||
title_prompt_path = os.path.join(temp_dir, "title_prompt.txt")
|
||||
cover_prompts_dir = os.path.join(temp_dir, "prompts", "cover")
|
||||
prompts.save_title_prompt("标题启动回显", title_prompt_path)
|
||||
prompts.save_cover_template(
|
||||
"基础",
|
||||
"把{旧标题}变成{新标题},商品{商品id},店铺{店铺}",
|
||||
cover_prompts_dir,
|
||||
)
|
||||
accounts.create_account("主店", "alias-a", debug_port=9222, config=cfg)
|
||||
batch_id = db.create_batch(["input.xlsx"], path=cfg["db_path"])
|
||||
db.insert_tasks(
|
||||
batch_id,
|
||||
[
|
||||
{
|
||||
"source_file_abs": os.path.join(temp_dir, "input.xlsx"),
|
||||
"source_sheet": "商品",
|
||||
"source_row": 2,
|
||||
"account_name": "Excel主店",
|
||||
"alias": "alias-a",
|
||||
"item_id": "51100639510",
|
||||
}
|
||||
],
|
||||
path=cfg["db_path"],
|
||||
)
|
||||
task = db.list_tasks(batch_id=batch_id, path=cfg["db_path"])[0]
|
||||
db.set_collected(task.id, "旧标题", "old.jpg", path=cfg["db_path"])
|
||||
db.set_generated(task.id, "新标题", "new.jpg", path=cfg["db_path"])
|
||||
statuses = []
|
||||
tab = GenerateTab(
|
||||
config=cfg,
|
||||
status_callback=statuses.append,
|
||||
title_prompt_path=title_prompt_path,
|
||||
cover_prompts_dir=cover_prompts_dir,
|
||||
)
|
||||
self.addCleanup(tab.close)
|
||||
|
||||
self.assertEqual("标题启动回显", tab.title_prompt_edit.toPlainText())
|
||||
self.assertEqual("基础", tab.cover_template_combo.currentText())
|
||||
self.assertIn("{旧标题}", tab.cover_prompt_edit.toPlainText())
|
||||
|
||||
tab.title_prompt_edit.setPlainText("新标题提示词")
|
||||
tab.save_title_prompt()
|
||||
self.assertEqual("新标题提示词", prompts.load_title_prompt(title_prompt_path))
|
||||
|
||||
tab.cover_prompt_edit.setPlainText("另存模板 {新标题}")
|
||||
with mock.patch("app.gui.QInputDialog.getText", return_value=("另存", True)):
|
||||
tab.save_cover_template_as()
|
||||
self.assertEqual("另存", tab.cover_template_combo.currentText())
|
||||
self.assertEqual("另存模板 {新标题}", prompts.load_cover_template("另存", cover_prompts_dir))
|
||||
|
||||
with mock.patch("app.gui.QInputDialog.getText", return_value=("改名", True)):
|
||||
tab.rename_cover_template()
|
||||
self.assertEqual("改名", tab.cover_template_combo.currentText())
|
||||
self.assertIn("改名", prompts.list_cover_templates(cover_prompts_dir))
|
||||
|
||||
tab.cover_prompt_edit.setPlainText("预览 {旧标题} {新标题} {商品id} {店铺}")
|
||||
tab.task_table.selectRow(0)
|
||||
with mock.patch("app.gui.QMessageBox.information") as info:
|
||||
tab.preview_cover_prompt()
|
||||
self.assertIn("预览 旧标题 新标题 51100639510 主店", info.call_args[0][2])
|
||||
|
||||
tab.cover_prompt_edit.moveCursor(QTextCursor.End)
|
||||
tab.insert_title_placeholder()
|
||||
self.assertTrue(tab.cover_prompt_edit.toPlainText().endswith("{新标题}"))
|
||||
|
||||
with mock.patch("app.gui.QMessageBox.question", return_value=gui.QMessageBox.Yes):
|
||||
tab.delete_cover_template()
|
||||
self.assertNotIn("改名", prompts.list_cover_templates(cover_prompts_dir))
|
||||
|
||||
self.assert_removed(temp_dir)
|
||||
|
||||
def test_generate_tab_lists_tasks_and_filters_by_shop_status_and_batch(self):
|
||||
with self.make_temp_dir() as temp_dir:
|
||||
cfg = self.make_config(temp_dir)
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
|
||||
from _helpers import TempDirMixin
|
||||
|
||||
from app import prompts
|
||||
|
||||
|
||||
class PromptTests(TempDirMixin, unittest.TestCase):
|
||||
def test_title_prompt_load_missing_and_save(self):
|
||||
with self.make_temp_dir() as temp_dir:
|
||||
path = os.path.join(temp_dir, "title_prompt.txt")
|
||||
|
||||
self.assertEqual("", prompts.load_title_prompt(path))
|
||||
prompts.save_title_prompt("标题规则", path)
|
||||
|
||||
self.assertEqual("标题规则", prompts.load_title_prompt(path))
|
||||
|
||||
self.assert_removed(temp_dir)
|
||||
|
||||
def test_cover_template_crud_and_validation(self):
|
||||
with self.make_temp_dir() as temp_dir:
|
||||
directory = os.path.join(temp_dir, "prompts", "cover")
|
||||
|
||||
self.assertEqual([], prompts.list_cover_templates(directory))
|
||||
prompts.save_cover_template("韩版女装", "封面规则", directory)
|
||||
prompts.save_cover_template("基础", "基础规则", directory)
|
||||
|
||||
self.assertEqual(["基础", "韩版女装"], prompts.list_cover_templates(directory))
|
||||
self.assertEqual("封面规则", prompts.load_cover_template("韩版女装", directory))
|
||||
|
||||
prompts.rename_cover_template("基础", "基础2", directory)
|
||||
self.assertEqual(["基础2", "韩版女装"], prompts.list_cover_templates(directory))
|
||||
|
||||
with self.assertRaises(prompts.PromptError):
|
||||
prompts.rename_cover_template("基础2", "韩版女装", directory)
|
||||
with self.assertRaises(prompts.PromptError):
|
||||
prompts.save_cover_template("../bad", "x", directory)
|
||||
|
||||
prompts.delete_cover_template("基础2", directory)
|
||||
self.assertEqual(["韩版女装"], prompts.list_cover_templates(directory))
|
||||
|
||||
self.assert_removed(temp_dir)
|
||||
|
||||
def test_render_prompt_replaces_known_variables(self):
|
||||
task = {
|
||||
"old_title": "舊T恤",
|
||||
"new_title": "新T恤",
|
||||
"item_id": "51100639510",
|
||||
"account_name": "主店",
|
||||
}
|
||||
|
||||
rendered = prompts.render_prompt(
|
||||
"用{旧标题}生成{新标题},商品{商品id},店铺{店铺},未知{不存在}",
|
||||
task,
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
"用舊T恤生成新T恤,商品51100639510,店铺主店,未知{不存在}",
|
||||
rendered,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user