feat: enhance project audio directory management by clearing segments and chapters during analysis and identification

This commit is contained in:
2026-03-12 23:57:13 +08:00
parent 29799a8c7d
commit c2e1ee0289

View File

@@ -1,6 +1,7 @@
import asyncio
import logging
import re
import shutil
from pathlib import Path
from typing import Optional
@@ -202,14 +203,18 @@ async def analyze_project(project_id: int, user: User, db: Session, turbo: bool
samples = _sample_full_text(text)
n = len(samples)
# Ensure previews directory is clean for new analysis
previews_dir = Path(settings.OUTPUT_DIR) / "audiobook" / str(project_id) / "previews"
if previews_dir.exists():
import shutil
project_audio_dir = Path(settings.OUTPUT_DIR) / "audiobook" / str(project_id)
for subdir in ("previews", "segments", "chapters"):
d = project_audio_dir / subdir
if d.exists():
try:
shutil.rmtree(previews_dir)
shutil.rmtree(d)
except Exception as e:
logger.warning(f"Failed to clear previews directory: {e}")
logger.warning(f"Failed to clear {subdir} directory: {e}")
full_path = project_audio_dir / "full.wav"
if full_path.exists():
full_path.unlink(missing_ok=True)
previews_dir = project_audio_dir / "previews"
previews_dir.mkdir(parents=True, exist_ok=True)
mode_label = "极速并发" if turbo else "顺序"
@@ -349,6 +354,15 @@ def identify_chapters(project_id: int, db, project) -> None:
crud.delete_audiobook_chapters(db, project_id)
crud.delete_audiobook_segments(db, project_id)
project_audio_dir = Path(settings.OUTPUT_DIR) / "audiobook" / str(project_id)
for subdir in ("segments", "chapters"):
d = project_audio_dir / subdir
if d.exists():
shutil.rmtree(d, ignore_errors=True)
full_path = project_audio_dir / "full.wav"
if full_path.exists():
full_path.unlink(missing_ok=True)
real_idx = 0
for text in texts:
if text.strip():
@@ -397,6 +411,18 @@ async def parse_one_chapter(project_id: int, chapter_id: int, user: User, db) ->
crud.delete_audiobook_segments_for_chapter(db, project_id, chapter.chapter_index)
segments_dir = Path(settings.OUTPUT_DIR) / "audiobook" / str(project_id) / "segments"
if segments_dir.exists():
chapter_prefix = f"ch{chapter.chapter_index:03d}_"
for f in segments_dir.glob(f"{chapter_prefix}*.wav"):
f.unlink(missing_ok=True)
chapter_audio = Path(settings.OUTPUT_DIR) / "audiobook" / str(project_id) / "chapters" / f"chapter_{chapter.chapter_index}.wav"
if chapter_audio.exists():
chapter_audio.unlink(missing_ok=True)
full_path = Path(settings.OUTPUT_DIR) / "audiobook" / str(project_id) / "full.wav"
if full_path.exists():
full_path.unlink(missing_ok=True)
chunks = _chunk_chapter(chapter.source_text, max_chars=1500)
ps.append_line(key, f"{len(chunks)}\n")