feat(deep-research): 强化任务链路可靠性并接入 agentfx 报告助手种子
功能说明:\n- 重构 Deep Research 调度与执行链,补齐 dispatcher、executor、live hub 与依赖注入入口,提升任务下发、执行、回调的稳定性\n- 增强运行时持久化与恢复能力,接入业务映射、任务来源与任务事件日志模型,覆盖持久化与执行可靠性关键路径测试\n- 新增 agentfx 报告助手 seed 与任务报告导入脚本配置,支持离线环境快速初始化与任务流模板回填\n- 完善 deep-research 与 thread_runs 路由参数编排,兼容不同业务映射与运行入口的前后端联动\n- 补充前端 agentfx deep-link 解析,保证 deep-research 场景下的登录跳转与任务上下文一致
This commit is contained in:
1 parent
438772f0b7
commit
5c75e1af16
36 files changed
+3163
-312
No files matched your search
@@ -191,14 +191,14 @@ class RunManager:
|
||||
action: "interrupt" keeps checkpoint, "rollback" reverts to pre-run state.
|
||||
|
||||
Sets the abort event with the action reason and cancels the asyncio task.
|
||||
Returns ``True`` if the run was in-flight and cancellation was initiated.
|
||||
Returns ``True`` if cancellation was initiated or the run was already stopped.
|
||||
"""
|
||||
async with self._lock:
|
||||
record = self._runs.get(run_id)
|
||||
if record is None:
|
||||
return False
|
||||
return True
|
||||
if record.status not in (RunStatus.pending, RunStatus.running):
|
||||
return False
|
||||
return True
|
||||
record.abort_action = action
|
||||
record.abort_event.set()
|
||||
if record.task is not None and not record.task.done():
|
||||
|
||||
+96
-31
@@ -1389,17 +1389,40 @@ class ScheduledTaskService:
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _build_conversion_prompt(skeleton_json: str, source: str, embedded_json: Any | None = None) -> str:
|
||||
def _build_conversion_prompt(
|
||||
skeleton_json: str,
|
||||
source: str,
|
||||
embedded_json: Any | None = None,
|
||||
instructions: str | None = None,
|
||||
) -> str:
|
||||
parts = [
|
||||
"请把下面的【源数据】转换为【目标结构】要求的 JSON。",
|
||||
"请把下面的【源数据】转换成【目标结构】要求的 JSON,用于填充一个 HTML 展示模板。",
|
||||
"模板只是一层**样式外壳**:它的字段名固定(页面脚本按字段名读取,绝不能改),"
|
||||
"但每个字段的**含义要按源数据的主题重新解释**——把主题内容语义映射进各分区,"
|
||||
"例如:总览指标填主题的核心数字;分组/区域类列表填主题的分区、品类或阵营;"
|
||||
"组织/单位类列表填主题的机构、厂商或层级体系;装备/条目类列表填主题的产品、"
|
||||
"技术或关键要素;事件/项目类列表填主题的时间线事项。内容必须全部来自【源数据】"
|
||||
"的主题,不要被模板原有示例的领域限制住。",
|
||||
"源数据可能是一段 JSON、一段纯文本、或包含 JSON 的文本——"
|
||||
"其中若有结构化 JSON 以 JSON 内容为准;若是纯文本请理解其语义后据实填充;"
|
||||
"源里没有对应内容的字段按其类型留空(\"\" / [] / null),不要臆造。",
|
||||
"若下面的【任务要求】里带有对页面的明确修改指示(如“标题改为…”“只更新某部分”),"
|
||||
"优先满足这些指示,其余字段可留空(页面将沿用模板现有内容);"
|
||||
"没有指示到的部分按源数据自由发挥,尽量把各分区填满。",
|
||||
"字段名必须与【目标结构】逐字一致(包括中文键名,原样复制),"
|
||||
"严禁自造、翻译或改写字段名;数组元素的字段集合必须与样例元素相同,"
|
||||
"源里没有的字段按类型留空即可,绝不能用自造的字段名顶替,也不要照抄任何示例值。",
|
||||
"另外请在输出的 JSON 里额外携带两个顶层字符串字段:「页面标题」(按主题拟一个"
|
||||
"页面大标题;若任务要求里明确给了标题,就用它)和「页面副标题」(一句话副标题)。",
|
||||
"",
|
||||
"【目标结构】(展示了完整字段与类型,其中数组只示意 1 个样例元素,实际请按源数据填充全部元素):",
|
||||
"【目标结构】(字段与类型的空占位骨架,数组只示意 1 个样例元素,实际按源数据填充全部元素):",
|
||||
"```json\n" + skeleton_json + "\n```",
|
||||
"",
|
||||
]
|
||||
if instructions and instructions.strip():
|
||||
parts.append("【任务要求】(用户对本次页面的要求/修改指示,优先级最高):")
|
||||
parts.append(instructions.strip())
|
||||
parts.append("")
|
||||
if embedded_json is not None:
|
||||
# 已从源数据里识别出结构化 JSON,单独标注帮助(尤其弱)模型对齐。
|
||||
parts.append("【从源数据中识别到的结构化数据】(优先以此为准):")
|
||||
@@ -1410,14 +1433,14 @@ class ScheduledTaskService:
|
||||
parts.append("【源数据】:")
|
||||
parts.append(source)
|
||||
parts.append("")
|
||||
parts.append("只输出一个 ```json 代码块,内含填充好的完整目标 JSON,不要任何解释文字。")
|
||||
parts.append("只输出一个 ```json 代码块,内含填充好的完整目标 JSON(含「页面标题」「页面副标题」),不要任何解释文字。")
|
||||
return "\n".join(parts)
|
||||
|
||||
@staticmethod
|
||||
def _build_retry_prompt(base_prompt: str, errors: list[str], gaps: list[str]) -> str:
|
||||
def _build_retry_prompt(base_prompt: str, problems: list[str], gaps: list[str]) -> str:
|
||||
lines = [base_prompt, "\n\n上一轮转换结果未通过校验,请严格修正后重新输出**完整**的目标 JSON:"]
|
||||
if errors:
|
||||
lines.append("- 结构错误:" + ";".join(errors[:12]))
|
||||
if problems:
|
||||
lines.append("- " + ";".join(problems[:12]))
|
||||
if gaps:
|
||||
lines.append("- 字段缺失(请补齐):" + "、".join(gaps[:30]))
|
||||
return "\n".join(lines)
|
||||
@@ -1474,36 +1497,51 @@ class ScheduledTaskService:
|
||||
model_name: str | None,
|
||||
soul: str | None,
|
||||
run_id: str,
|
||||
instructions: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""把源数据(JSON/文本/含JSON文本)转换成模板的 DATA 结构,校验+回喂重试。
|
||||
|
||||
成功返回校验通过的对象;全部尝试失败抛 :class:`TemplateFillError`。
|
||||
通过(结构+字段对齐)返回校验过的对象;重试耗尽时**尽力而为**——只要解析
|
||||
出过 JSON 对象就返回最后一个(缺顶层键/字段错位的分支由随后的
|
||||
``merge_with_reference`` 回退模板默认数据,抽多少用多少);只有全程没解析
|
||||
出 JSON 才抛 :class:`TemplateFillError`(由调用方兜底为默认数据,不让
|
||||
run 失败)。
|
||||
"""
|
||||
skeleton = template_fill.schema_skeleton_json(template_id)
|
||||
# 源数据可能是纯 JSON / 纯文本 / 含 JSON 的文本:先尽力抽出内嵌 JSON 单独标注。
|
||||
embedded_json = template_fill.extract_embedded_json(source)
|
||||
base_prompt = self._build_conversion_prompt(skeleton, source, embedded_json)
|
||||
last_errors: list[str] = []
|
||||
base_prompt = self._build_conversion_prompt(skeleton, source, embedded_json, instructions=instructions)
|
||||
last_problems: list[str] = []
|
||||
prompt = base_prompt
|
||||
candidate: dict[str, Any] | None = None
|
||||
for attempt in range(_MAX_TEMPLATE_FILL_RETRIES + 1):
|
||||
raw = await self._invoke_conversion_model(model_name, soul, prompt)
|
||||
candidate = html_page_utils.extract_json_object(raw)
|
||||
if candidate is None:
|
||||
last_errors = ["模型未返回可解析的 JSON 对象"]
|
||||
parsed = html_page_utils.extract_json_object(raw)
|
||||
if parsed is None:
|
||||
last_problems = ["模型未返回可解析的 JSON 对象"]
|
||||
else:
|
||||
errors = template_fill.validate_data(template_id, candidate)
|
||||
if not errors:
|
||||
candidate = parsed # 记住最后一个可解析结果,供重试耗尽时尽力返回
|
||||
errors = [f"结构错误:{e}" for e in template_fill.validate_data(template_id, candidate)]
|
||||
mismatches = [f"字段错位:{m}" for m in template_fill.shape_mismatches(template_id, candidate)]
|
||||
if not errors and not mismatches:
|
||||
return candidate
|
||||
last_errors = errors
|
||||
last_problems = errors + mismatches
|
||||
gaps = template_fill.field_coverage_gaps(template_id, candidate)
|
||||
prompt = self._build_retry_prompt(base_prompt, errors, gaps)
|
||||
prompt = self._build_retry_prompt(base_prompt, last_problems, gaps)
|
||||
logger.info(
|
||||
"模板填充[run=%s]第 %d 次校验未通过:%s",
|
||||
run_id,
|
||||
attempt + 1,
|
||||
";".join(last_errors[:5]),
|
||||
";".join(last_problems[:5]),
|
||||
)
|
||||
raise TemplateFillError("转换结果未通过结构校验:" + ";".join(last_errors[:8]))
|
||||
if candidate is not None:
|
||||
logger.warning(
|
||||
"模板填充[run=%s]重试耗尽仍未通过校验,尽力返回待兜底:%s",
|
||||
run_id,
|
||||
";".join(last_problems[:5]),
|
||||
)
|
||||
return candidate
|
||||
raise TemplateFillError("转换结果未通过结构校验:" + ";".join(last_problems[:8]))
|
||||
|
||||
async def _finalize_template_html(
|
||||
self,
|
||||
@@ -1647,14 +1685,21 @@ class ScheduledTaskService:
|
||||
# HTML 数据来源:抽取(开关开 + 有数据)→ 转换填充;否则用模板默认数据(子页面齐全)。
|
||||
source = (data_text or "").strip()
|
||||
used_default = True
|
||||
page_title: str | None = None
|
||||
page_subtitle: str | None = None
|
||||
if do_extract and source:
|
||||
# 转换阶段同样带上任务所选智能体:SOUL 提供领域口径,未显式选模型时
|
||||
# 兜底用该智能体配置的模型(与模板填充模式一致)。
|
||||
soul, conv_model = await self._agent_soul_and_model(task, model_name)
|
||||
# 任务的描述/prompt 作为「任务要求」注入:用户对页面的修改指示(如
|
||||
# "标题改为…"、"只更新某部分")优先级最高,没指示就按检索内容自由发挥。
|
||||
instructions = "\n".join(part for part in (description, prompt) if part)
|
||||
try:
|
||||
converted = await self._convert_to_template_data(
|
||||
tpl_id, source, model_name=conv_model, soul=soul, run_id=run_id
|
||||
tpl_id, source, model_name=conv_model, soul=soul, run_id=run_id, instructions=instructions or None
|
||||
)
|
||||
# 页面标题/副标题是额外键,摘出来替换页头,不进 DATA。
|
||||
page_title, page_subtitle = template_fill.pop_page_titles(converted)
|
||||
# 子页面没抽到有效内容的,回退模板原有数据,避免子页面空白。
|
||||
data_obj = template_fill.merge_with_reference(tpl_id, converted)
|
||||
content = f"已检索数据并套用模板「{spec.name}」(空子页面回退原数据,含全部子页面)"
|
||||
@@ -1672,7 +1717,9 @@ class ScheduledTaskService:
|
||||
)
|
||||
|
||||
try:
|
||||
html = template_fill.fill_template(tpl_id, data_obj, update_date=local_time.date())
|
||||
html = template_fill.fill_template(
|
||||
tpl_id, data_obj, update_date=local_time.date(), title=page_title, subtitle=page_subtitle
|
||||
)
|
||||
except template_fill.TemplateError as exc:
|
||||
raise HtmlGenerationError(f"模板填充失败:{exc}") from exc
|
||||
return await self._finalize_template_html(
|
||||
@@ -1701,8 +1748,9 @@ class ScheduledTaskService:
|
||||
Pipeline: 取源 JSON(任务 prompt) → 用内置「模板数据转换器」agent 的 SOUL +
|
||||
模型把它映射成目标结构 → 结构校验(不过则回喂错误重试) → 填充模板 → 归档
|
||||
``index.html`` + 持久化 ``scheduled_html_pages`` → 返回 ``format: "html"``
|
||||
结果(复用现有 HTML 预览)。任一步彻底失败抛 :class:`TemplateFillError`,
|
||||
run 记为 failed。
|
||||
结果(复用现有 HTML 预览)。转换质量问题一律**不失败**:抽不到/抽错的分支由
|
||||
``merge_with_reference`` 回退模板原有数据,转换彻底失败则整页用模板默认数据;
|
||||
只有模板文件本身缺失/损坏才抛 :class:`TemplateFillError` 让 run 失败。
|
||||
"""
|
||||
template_id = _task_template_id(task)
|
||||
spec = template_fill.get_template(template_id) if template_id else None
|
||||
@@ -1726,6 +1774,8 @@ class ScheduledTaskService:
|
||||
used_default=True,
|
||||
)
|
||||
|
||||
page_title: str | None = None
|
||||
page_subtitle: str | None = None
|
||||
if not source:
|
||||
# 未提供源数据 → 用模板自带默认数据(不调模型、不校验)。
|
||||
data_obj = template_fill.reference_data(template_id)
|
||||
@@ -1740,18 +1790,33 @@ class ScheduledTaskService:
|
||||
model_name = str(tcfg.get("model_name") or "").strip() or None
|
||||
soul, model_name = await self._agent_soul_and_model(task, model_name)
|
||||
|
||||
converted = await self._convert_to_template_data(
|
||||
template_id, source, model_name=model_name, soul=soul, run_id=run_id
|
||||
)
|
||||
# 子页面没抽到有效内容的,回退模板原有数据,避免子页面空白。
|
||||
data_obj = template_fill.merge_with_reference(template_id, converted)
|
||||
content = f"已根据源数据填充模板「{spec.name}」生成页面"
|
||||
used_default = False
|
||||
try:
|
||||
converted = await self._convert_to_template_data(
|
||||
template_id, source, model_name=model_name, soul=soul, run_id=run_id
|
||||
)
|
||||
except TemplateFillError:
|
||||
# 转换彻底失败(全程没解析出 JSON)→ 也不让 run 失败:用模板默认
|
||||
# 数据出页,与 require_html 模板参考路径的兜底一致。
|
||||
logger.warning(
|
||||
"模板填充转换失败,回退默认数据 run=%s tpl=%s", run_id, template_id, exc_info=True
|
||||
)
|
||||
data_obj = template_fill.reference_data(template_id)
|
||||
content = f"数据转换未通过,已用模板「{spec.name}」的默认数据生成页面(含全部子页面)"
|
||||
used_default = True
|
||||
else:
|
||||
# 页面标题/副标题是额外键,摘出来替换页头,不进 DATA。
|
||||
page_title, page_subtitle = template_fill.pop_page_titles(converted)
|
||||
# 抽不到/抽错的子页面与字段回退模板原有数据,避免子页面空白或 undefined。
|
||||
data_obj = template_fill.merge_with_reference(template_id, converted)
|
||||
content = f"已根据源数据填充模板「{spec.name}」生成页面(抽取不到的部分沿用模板原有数据)"
|
||||
used_default = False
|
||||
|
||||
task_tz = ZoneInfo(task.get("timezone") or "UTC")
|
||||
local_time = scheduled_for.astimezone(task_tz)
|
||||
try:
|
||||
html = template_fill.fill_template(template_id, data_obj, update_date=local_time.date())
|
||||
html = template_fill.fill_template(
|
||||
template_id, data_obj, update_date=local_time.date(), title=page_title, subtitle=page_subtitle
|
||||
)
|
||||
except template_fill.TemplateError as exc:
|
||||
raise TemplateFillError(f"模板填充失败:{exc}") from exc
|
||||
return await self._finalize_template_html(
|
||||
|
||||
+202
-9
@@ -17,7 +17,8 @@ HTML 模板需要的 ``DATA`` 结构后,本模块负责把数据**填充**进模
|
||||
* **harness 层、零 app.* 依赖**:可被调度器(harness)与 Gateway 路由(app)共同 import。
|
||||
|
||||
公开入口:``list_templates`` / ``get_template`` / ``reference_data`` /
|
||||
``schema_skeleton_json`` / ``validate_data`` / ``field_coverage_gaps`` / ``fill_template``。
|
||||
``schema_skeleton_json`` / ``validate_data`` / ``field_coverage_gaps`` /
|
||||
``shape_mismatches`` / ``fill_template``。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -406,25 +407,33 @@ def reference_data(template_id: str) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _skeleton(value: Any, *, list_sample: int = 1, depth: int = 0, max_depth: int = 6) -> Any:
|
||||
"""把一份具体数据压成「结构骨架」:保留全部字段与类型,每个数组只留前 N 个样例。
|
||||
"""把一份具体数据压成「空占位骨架」:保留全部字段名与类型,值一律抹空。
|
||||
|
||||
数组元素同构,留 1 个样例即可暴露该元素的完整字段集,既完整又紧凑——正好做大模型
|
||||
的「目标格式说明」。
|
||||
模板只是样式外壳,**示例值(模板自带的模拟内容)绝不能进入转换 prompt**——
|
||||
否则大模型会照抄示例内容、或被其领域(如台海防卫)限制住,不肯把用户主题的
|
||||
内容映射进来。叶子按类型给空占位:字符串→\"\"、数字→0、布尔→false、
|
||||
其它→null;数组元素同构,留 1 个抹空样例即可暴露该元素的完整字段集。
|
||||
"""
|
||||
if depth >= max_depth:
|
||||
return "…"
|
||||
return None
|
||||
if isinstance(value, dict):
|
||||
return {k: _skeleton(v, list_sample=list_sample, depth=depth + 1, max_depth=max_depth) for k, v in value.items()}
|
||||
if isinstance(value, list):
|
||||
if not value:
|
||||
return []
|
||||
return [_skeleton(v, list_sample=list_sample, depth=depth + 1, max_depth=max_depth) for v in value[:list_sample]]
|
||||
return value
|
||||
if isinstance(value, bool):
|
||||
return False
|
||||
if isinstance(value, (int, float)):
|
||||
return 0
|
||||
if isinstance(value, str):
|
||||
return ""
|
||||
return None
|
||||
|
||||
|
||||
@lru_cache(maxsize=16)
|
||||
def schema_skeleton_json(template_id: str) -> str:
|
||||
"""目标格式的结构骨架(JSON 字符串),注入到大模型的转换 prompt 里。"""
|
||||
"""目标格式的空占位骨架(JSON 字符串),注入到大模型的转换 prompt 里。"""
|
||||
skeleton = _skeleton(reference_data(template_id))
|
||||
return json.dumps(skeleton, ensure_ascii=False, indent=1)
|
||||
|
||||
@@ -509,11 +518,134 @@ def _has_content(value: Any) -> bool:
|
||||
return True # 数字 / 布尔 / 其它标量
|
||||
|
||||
|
||||
# 元素字段中至少要有这个比例能在模板参考数据的元素字段里找到,否则视为「自造字段」。
|
||||
_LIST_FIELD_OVERLAP_MIN = 0.5
|
||||
# 元素字段至少要覆盖模板参考元素字段的这个比例:低于它意味着大部分展示字段缺失
|
||||
# (卡片大面积空白/undefined),不如整支回退模板原数据。
|
||||
_LIST_FIELD_RECALL_MIN = 0.4
|
||||
|
||||
|
||||
def _list_misaligned(got: Any, ref_val: Any) -> bool:
|
||||
"""非空列表与模板参考列表是否「无法有效渲染」。
|
||||
|
||||
顶层校验挡不住这种情况:转换结果键齐全、类型也对,但列表元素的**字段**不对,
|
||||
填进模板后 JS 读不到字段,页面满屏 ``undefined``。判定(满足其一即错位):
|
||||
|
||||
* 模板元素是对象而转换给了非对象(字符串/数字读不出属性);
|
||||
* 元素字段里能对上模板的比例过低(:data:`_LIST_FIELD_OVERLAP_MIN`,
|
||||
自造字段名占主导);
|
||||
* 元素字段对模板参考字段的**覆盖率**过低(:data:`_LIST_FIELD_RECALL_MIN`,
|
||||
只填了零星几个字段,展示字段大面积缺失)。
|
||||
|
||||
空列表不算错位(交由「无内容回退」处理)。
|
||||
"""
|
||||
if not isinstance(got, list) or not got:
|
||||
return False
|
||||
ref_fields = _element_fields(ref_val)
|
||||
if not ref_fields:
|
||||
return False # 模板元素本身没有对象字段,无从比对
|
||||
ref_dicts = [item for item in ref_val if isinstance(item, dict)]
|
||||
got_dicts = [item for item in got if isinstance(item, dict)]
|
||||
if ref_dicts and not got_dicts:
|
||||
return True # 模板元素是对象,转换给了字符串/数字 → 必然读不到字段
|
||||
if not got_dicts:
|
||||
return False
|
||||
got_fields: set[str] = set()
|
||||
for item in got_dicts:
|
||||
got_fields.update(item.keys())
|
||||
if not got_fields:
|
||||
return False
|
||||
overlap = got_fields & ref_fields
|
||||
if len(overlap) / len(got_fields) < _LIST_FIELD_OVERLAP_MIN:
|
||||
return True # 自造字段名占主导
|
||||
return len(overlap) / len(ref_fields) < _LIST_FIELD_RECALL_MIN # 覆盖率过低
|
||||
|
||||
|
||||
def _mismatch_reason(got: Any, ref_val: Any) -> str:
|
||||
"""错位原因的人话描述(回喂重试用),与 :func:`_list_misaligned` 同判定。"""
|
||||
ref_fields = _element_fields(ref_val)
|
||||
got_fields: set[str] = set()
|
||||
for item in got or []:
|
||||
if isinstance(item, dict):
|
||||
got_fields.update(item.keys())
|
||||
overlap = got_fields & ref_fields
|
||||
if got_fields and len(overlap) / len(got_fields) < _LIST_FIELD_OVERLAP_MIN:
|
||||
return "的元素字段名与模板不一致(疑似自造字段名,必须原样沿用目标结构的字段名)"
|
||||
return "的元素字段覆盖过低(样例元素的字段大部分缺失;缺数据的字段按类型留空补齐,不要省略字段)"
|
||||
|
||||
|
||||
def shape_mismatches(template_id: str, obj: Any, *, max_items: int = 20) -> list[str]:
|
||||
"""硬反馈:列出非空列表分支里「无法有效渲染」的项(供回喂重试)。
|
||||
|
||||
与 :func:`field_coverage_gaps`(软反馈,字段没填全)不同,本函数抓的是
|
||||
**填了也渲染不出来**的情况:列表有内容但元素字段自造(对不上模板)或覆盖
|
||||
过低(展示字段大面积缺失) → 渲染必然大面积 undefined,必须回喂重试。
|
||||
"""
|
||||
out: list[str] = []
|
||||
if not isinstance(obj, dict):
|
||||
return out
|
||||
ref = reference_data(template_id)
|
||||
for key, ref_val in ref.items():
|
||||
got = obj.get(key)
|
||||
if isinstance(ref_val, list) and _list_misaligned(got, ref_val):
|
||||
out.append(f"「{key}」{_mismatch_reason(got, ref_val)}")
|
||||
if len(out) >= max_items:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def _ref_element_types(ref_val: list) -> dict[str, Any]:
|
||||
"""参考列表各字段的类型样本(取第一个携带该字段的元素)。"""
|
||||
types: dict[str, Any] = {}
|
||||
for item in ref_val:
|
||||
if isinstance(item, dict):
|
||||
for key, value in item.items():
|
||||
types.setdefault(key, value)
|
||||
return types
|
||||
|
||||
|
||||
def _blank_like(sample: Any) -> Any:
|
||||
"""按参考类型给出「空值」:字符串→空串、列表→空数组、对象→空对象、其它→null。"""
|
||||
if isinstance(sample, str):
|
||||
return ""
|
||||
if isinstance(sample, list):
|
||||
return []
|
||||
if isinstance(sample, dict):
|
||||
return {}
|
||||
return None
|
||||
|
||||
|
||||
def _fill_missing_fields(got: list, ref_val: list) -> list:
|
||||
"""给保留的转换列表逐元素补齐模板元素字段(缺失的按参考类型给空值)。
|
||||
|
||||
模板 JS 常裸读 ``${item.字段}``(不经过空值兜底函数),字段缺失会直接把
|
||||
``undefined`` 打到页面上;补齐成空值后渲染为空白,不再出现字面 undefined。
|
||||
只补缺、不改已有值,多出来的自造键原样保留(JS 不读,无害)。
|
||||
"""
|
||||
types = _ref_element_types(ref_val)
|
||||
if not types:
|
||||
return got
|
||||
out: list[Any] = []
|
||||
for item in got:
|
||||
if isinstance(item, dict):
|
||||
filled = dict(item)
|
||||
for key, sample in types.items():
|
||||
if key not in filled:
|
||||
filled[key] = _blank_like(sample)
|
||||
out.append(filled)
|
||||
else:
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def _merge_fill(got: Any, ref: Any) -> Any:
|
||||
"""用 ``got`` 覆盖,但 ``got`` 里「没有有效内容」的部分回退 ``ref``。
|
||||
|
||||
字典逐键递归(空分支回退);列表/标量有内容就整体保留 ``got``(列表不逐元素合并,
|
||||
避免与原模板元素错配)。
|
||||
字典逐键递归(空分支回退);列表有内容就整体保留 ``got``(不逐元素合并,避免与
|
||||
原模板元素错配)——**例外**:列表元素无法有效渲染(:func:`_list_misaligned`,
|
||||
自造字段名占主导/覆盖率过低/元素类型不符)时整支回退 ``ref``,否则填进模板
|
||||
JS 读不到字段,页面满屏 undefined。保留的列表会逐元素补齐缺失字段的空值
|
||||
(:func:`_fill_missing_fields`),防止局部缺字段裸读出 undefined。
|
||||
"""
|
||||
if not _has_content(got):
|
||||
return ref
|
||||
@@ -522,6 +654,10 @@ def _merge_fill(got: Any, ref: Any) -> Any:
|
||||
for key, ref_val in ref.items():
|
||||
out[key] = _merge_fill(got.get(key), ref_val)
|
||||
return out
|
||||
if isinstance(ref, list) and isinstance(got, list):
|
||||
if _list_misaligned(got, ref):
|
||||
return ref
|
||||
return _fill_missing_fields(got, ref)
|
||||
return got
|
||||
|
||||
|
||||
@@ -541,21 +677,78 @@ def _dump_const(var: str, obj: Any) -> str:
|
||||
return f"const {var}={body};"
|
||||
|
||||
|
||||
def _escape_html(text: str) -> str:
|
||||
return (
|
||||
text.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace('"', """)
|
||||
)
|
||||
|
||||
|
||||
# 转换结果里约定的两个额外顶层键:页面大标题/副标题(填充时替换页头,不进 DATA)。
|
||||
PAGE_TITLE_KEY = "页面标题"
|
||||
PAGE_SUBTITLE_KEY = "页面副标题"
|
||||
|
||||
|
||||
def pop_page_titles(obj: dict[str, Any]) -> tuple[str | None, str | None]:
|
||||
"""取出并移除转换结果里的「页面标题/页面副标题」额外键。
|
||||
|
||||
模型按转换 prompt 的约定额外输出这两个顶层字符串键;它们不是模板 DATA 的
|
||||
字段(校验本就忽略额外键),填充前摘出来用于替换页头,避免漏进 ``const DATA``。
|
||||
"""
|
||||
def _clean(value: Any) -> str | None:
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
return None
|
||||
|
||||
title = _clean(obj.pop(PAGE_TITLE_KEY, None))
|
||||
subtitle = _clean(obj.pop(PAGE_SUBTITLE_KEY, None))
|
||||
return title, subtitle
|
||||
|
||||
|
||||
def fill_template(
|
||||
template_id: str,
|
||||
data_obj: Any,
|
||||
*,
|
||||
manifest_overrides: dict[str, Any] | None = None,
|
||||
update_date: date | None = None,
|
||||
title: str | None = None,
|
||||
subtitle: str | None = None,
|
||||
) -> str:
|
||||
"""把 ``data_obj`` 填进模板的 ``const DATA=…`` 行,产出完整 HTML 文档。
|
||||
|
||||
可选地更新 MANIFEST 的「系统.更新时间」(``update_date``,默认不动) 以及任意
|
||||
``manifest_overrides``(深合并到解析后的 MANIFEST,如改系统名称)。
|
||||
|
||||
``title``/``subtitle`` 来自转换结果里的「页面标题/页面副标题」:模板页头
|
||||
(<title>、第一个 <h1>、其后紧跟的副标题 <p>)是写死的静态 HTML,不随 DATA
|
||||
变化——给出新标题时替换这三处,并把 MANIFEST 的 系统.名称 一并同步;
|
||||
不给则保持模板原文。
|
||||
"""
|
||||
spec = _require(template_id)
|
||||
text = read_template_text(template_id)
|
||||
|
||||
if title:
|
||||
overrides = dict(manifest_overrides or {})
|
||||
system = overrides.get("系统")
|
||||
system = dict(system) if isinstance(system, dict) else {}
|
||||
system["名称"] = title
|
||||
overrides["系统"] = system
|
||||
manifest_overrides = overrides
|
||||
escaped = _escape_html(title)
|
||||
text = re.sub(r"<title>.*?</title>", lambda _m: f"<title>{escaped}</title>", text, count=1, flags=re.DOTALL)
|
||||
text = re.sub(r"<h1>.*?</h1>", lambda _m: f"<h1>{escaped}</h1>", text, count=1, flags=re.DOTALL)
|
||||
if subtitle:
|
||||
escaped_sub = _escape_html(subtitle)
|
||||
text = re.sub(
|
||||
r"(<h1>.*?</h1>\s*<p>).*?(</p>)",
|
||||
lambda m: f"{m.group(1)}{escaped_sub}{m.group(2)}",
|
||||
text,
|
||||
count=1,
|
||||
flags=re.DOTALL,
|
||||
)
|
||||
|
||||
data_re = _const_line_re(spec.data_var)
|
||||
if data_re.search(text) is None:
|
||||
raise TemplateError(f"模板 {template_id} 中未找到 const {spec.data_var}= 行")
|
||||
|
||||
Reference in new issue
Block a user