Files
life-echo/api/app/features/story/backfill.py
2026-03-20 17:25:42 +08:00

35 lines
1.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Story 图片回填 — 将 asset:// 引用追加到 markdown 末尾。
图片生成成功后,在正文最后插入 ![alt](asset://asset_id)。
alt 使用原始 prompt 短文prompt_brief而非模板拼接后的完整出图 prompt。
单主图策略Celery 任务在调用本函数前会先 strip 正文中已有 asset:// 插图,
避免与旧版本快照叠加多条引用。
"""
def _escape_markdown_image_alt(text: str) -> str:
"""在 ![alt](...) 的 alt 中安全转义 \\ 与 ]。"""
return text.replace("\\", "\\\\").replace("]", "\\]")
def backfill_image_into_markdown(
markdown: str,
asset_id: str,
image_alt: str,
) -> str:
"""
将图片引用追加到 markdown 末尾。
格式:![image_alt](asset://asset_id)
image_alt 一般为 intent.prompt_brief原始图片提示短文
"""
raw = (image_alt or "").strip() or "主插图"
alt = _escape_markdown_image_alt(raw)
img_ref = f"![{alt}](asset://{asset_id})"
if not markdown or not markdown.strip():
return img_ref
body = markdown.rstrip()
return f"{body}\n\n{img_ref}\n"