fix: 图片生成失败后重试 前端一直显示生成中
This commit is contained in:
@@ -18,6 +18,7 @@ from agents.prompts.memory_prompts import CHAPTER_CATEGORIES, CHAPTER_ORDER, STA
|
||||
from services.memoir_images.schema import (
|
||||
completed_image_assets,
|
||||
IMAGE_STATUS_COMPLETED,
|
||||
IMAGE_STATUS_FAILED,
|
||||
normalize_image_assets,
|
||||
)
|
||||
from services.memoir_images.serializers import memoir_image_to_dict
|
||||
@@ -74,6 +75,37 @@ def _normalize_image_assets(images: list[dict] | None) -> list[dict]:
|
||||
return normalized_assets
|
||||
|
||||
|
||||
def _is_image_permanently_unavailable(rec) -> bool:
|
||||
"""配图是否应清理:失败不可恢复,或 completed 但无 url/storage_key(损坏数据)"""
|
||||
if not rec:
|
||||
return False
|
||||
status = getattr(rec, "status", None) or ""
|
||||
retryable = getattr(rec, "retryable", None)
|
||||
url = getattr(rec, "url", None)
|
||||
storage_key = getattr(rec, "storage_key", None)
|
||||
if status == IMAGE_STATUS_FAILED and retryable is False:
|
||||
return True
|
||||
if status == IMAGE_STATUS_COMPLETED and not url and not storage_key:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
async def _cleanup_permanently_unavailable_images(ch: ChapterModel, db: AsyncSession) -> None:
|
||||
"""清理章节中永久不可用的配图:section.image_id 置空,删除 memoir_images 记录"""
|
||||
sections = getattr(ch, "sections", None) or []
|
||||
cleaned = False
|
||||
for s in sections:
|
||||
rec = getattr(s, "image_record", None)
|
||||
if rec and _is_image_permanently_unavailable(rec):
|
||||
logger.info("清理不可用配图: chapter=%s, section=%s", ch.id, s.id)
|
||||
s.image_id = None
|
||||
await db.delete(rec)
|
||||
cleaned = True
|
||||
if cleaned:
|
||||
await db.commit()
|
||||
await db.refresh(ch)
|
||||
|
||||
|
||||
def _section_image_to_dict(section) -> dict | None:
|
||||
"""从 section.image_id 关联的 memoir_images(image_record)取配图。"""
|
||||
if getattr(section, "image_record", None):
|
||||
@@ -179,6 +211,7 @@ async def get_chapters(
|
||||
for category in CHAPTER_ORDER:
|
||||
ch = chapter_by_category.pop(category, None)
|
||||
if ch:
|
||||
await _cleanup_permanently_unavailable_images(ch, db)
|
||||
all_chapters.append(_chapter_to_dict(ch))
|
||||
else:
|
||||
if is_new is True:
|
||||
@@ -199,6 +232,7 @@ async def get_chapters(
|
||||
})
|
||||
|
||||
for ch in chapter_by_category.values():
|
||||
await _cleanup_permanently_unavailable_images(ch, db)
|
||||
all_chapters.append(_chapter_to_dict(ch))
|
||||
|
||||
return all_chapters
|
||||
@@ -226,6 +260,7 @@ async def get_chapter(
|
||||
raise HTTPException(status_code=404, detail="Chapter not found")
|
||||
if chapter.user_id != current_user.id:
|
||||
raise HTTPException(status_code=403, detail="无权访问此章节")
|
||||
await _cleanup_permanently_unavailable_images(chapter, db)
|
||||
return _chapter_to_dict(chapter)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user