add uploaded video chapter planning
This commit is contained in:
parent
f772a6cf4e
commit
f2fa1e30e6
5 changed files with 285 additions and 27 deletions
|
|
@ -1146,6 +1146,22 @@ function StatusBadge({ status }: { status: string }) {
|
|||
</Badge>
|
||||
)
|
||||
}
|
||||
if (normalized === "planning") {
|
||||
return (
|
||||
<Badge className="gap-1.5 border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-50" variant="outline">
|
||||
<Loader2 className="size-3.5 animate-spin" />
|
||||
Хронометраж
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
if (normalized === "planned") {
|
||||
return (
|
||||
<Badge className="gap-1.5 border-sky-200 bg-sky-50 text-sky-700 hover:bg-sky-50" variant="outline">
|
||||
<CheckCircle2 className="size-3.5" />
|
||||
Темы готовы
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
return <Badge variant={statusVariant(status)}>{status}</Badge>
|
||||
}
|
||||
|
||||
|
|
@ -1504,6 +1520,12 @@ export default function App() {
|
|||
try {
|
||||
const result = await api<VideoChaptersResponse>(`/api/videos/${video.id}/chapters`)
|
||||
if (!result.canSplit || result.chapters.length < 2) {
|
||||
if (video.sourceUrl.startsWith("upload://")) {
|
||||
const task = await api<{ taskId: string }>(`/api/videos/${video.id}/chapter-plan`, { method: "POST" })
|
||||
setStatusMessage(`Строю хронометраж ролика. Транскрибация и темы появятся в журнале. Task: ${task.taskId}`)
|
||||
await refresh()
|
||||
return
|
||||
}
|
||||
await processVideo(video.id)
|
||||
return
|
||||
}
|
||||
|
|
@ -2336,7 +2358,7 @@ export default function App() {
|
|||
const draftArticleId = draftArticles[0]?.id ?? (publishedArticle ? undefined : fallbackArticleId)
|
||||
const progress = Math.max(0, Math.min(100, video.progressPercent || 0))
|
||||
const hasStarted = video.status !== "new" || progress > 0
|
||||
const isActive = ["queued", "processing"].includes(video.status)
|
||||
const isActive = ["queued", "processing", "planning"].includes(video.status)
|
||||
const isSubmitting = videoActionId === video.id
|
||||
const hasDraftAction = draftArticles.length > 0 || Boolean(draftArticleId)
|
||||
return (
|
||||
|
|
@ -2415,12 +2437,12 @@ export default function App() {
|
|||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={isSubmitting}
|
||||
disabled={isSubmitting || video.status === "planning"}
|
||||
className="border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-100 hover:text-amber-900"
|
||||
onClick={() => processVideo(video.id, true)}
|
||||
>
|
||||
<RefreshCw data-icon="inline-start" className={isSubmitting ? "animate-spin" : ""} />
|
||||
Перезапустить
|
||||
<RefreshCw data-icon="inline-start" className={isSubmitting || video.status === "planning" ? "animate-spin" : ""} />
|
||||
{video.status === "planning" ? "Хронометраж" : "Перезапустить"}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ from app.models import AppSetting, Article, Frame, ImageGenerationBatch, ImageGe
|
|||
from app.image_generation import DEFAULT_API_URL, DEFAULT_MODEL, build_prompt, normalize_api_url
|
||||
from app.quality import validate_article_content
|
||||
from app.rss import VIDEO_PLACEHOLDER, article_url, build_feed_xml, render_article_html, split_audience_question_html
|
||||
from app.worker import best_thumbnail_url, generate_article_image, parse_upload_date, process_video, scan_sources, ytdlp_base_args
|
||||
from app.worker import best_thumbnail_url, create_chapter_plan, generate_article_image, parse_upload_date, process_video, scan_sources, ytdlp_base_args
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
|
@ -825,7 +825,8 @@ def process_video_route(video_id: int, payload: VideoProcessIn | None = Body(def
|
|||
action = "старые черновики отправлены на переделку"
|
||||
if selected_chapters:
|
||||
action += f", выбрано глав: {len(selected_chapters)}"
|
||||
video.progress_log = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}] В очереди: {action}"
|
||||
queue_log = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}] В очереди: {action}"
|
||||
video.progress_log = "\n".join(part for part in [video.progress_log, queue_log] if part)
|
||||
video.error_message = None
|
||||
session.commit()
|
||||
task = process_video.delay(video_id, selected_chapters or None)
|
||||
|
|
@ -847,8 +848,40 @@ def video_chapters(video_id: int, session: Session = Depends(get_session)) -> di
|
|||
}
|
||||
|
||||
|
||||
@router.post("/api/videos/{video_id}/chapter-plan")
|
||||
def create_video_chapter_plan(video_id: int, session: Session = Depends(get_session)) -> dict[str, str]:
|
||||
video = session.get(Video, video_id)
|
||||
if not video:
|
||||
raise HTTPException(status_code=404, detail="Video not found")
|
||||
if not video.duration_seconds or video.duration_seconds < 20 * 60:
|
||||
raise HTTPException(status_code=422, detail="Хронометраж нужен только для роликов длиннее 20 минут.")
|
||||
if video.status in {"queued", "processing", "planning"}:
|
||||
raise HTTPException(status_code=409, detail="Ролик уже находится в обработке.")
|
||||
video.status = "planning"
|
||||
video.progress_percent = 1
|
||||
video.progress_stage = "В очереди на хронометраж"
|
||||
video.error_message = None
|
||||
plan_log = upload_log_line("Хронометраж", "Задача поставлена в очередь: транскрибация и анализ тем")
|
||||
video.progress_log = "\n".join(part for part in [video.progress_log, plan_log] if part)
|
||||
session.commit()
|
||||
task = create_chapter_plan.delay(video_id)
|
||||
return {"taskId": task.id}
|
||||
|
||||
|
||||
def delete_video_storage_dir(video: Video, settings: Settings) -> None:
|
||||
root = settings.videos_path.resolve()
|
||||
video_dir = (root / str(video.id)).resolve()
|
||||
if video_dir != root and video_dir.is_relative_to(root):
|
||||
shutil.rmtree(video_dir, ignore_errors=True)
|
||||
video.local_video_path = None
|
||||
|
||||
|
||||
@router.delete("/api/videos/{video_id}")
|
||||
def ignore_video(video_id: int, session: Session = Depends(get_session)) -> dict[str, int | str]:
|
||||
def ignore_video(
|
||||
video_id: int,
|
||||
session: Session = Depends(get_session),
|
||||
settings: Settings = Depends(get_settings),
|
||||
) -> dict[str, int | str]:
|
||||
video = session.get(Video, video_id)
|
||||
if not video:
|
||||
raise HTTPException(status_code=404, detail="Video not found")
|
||||
|
|
@ -860,6 +893,7 @@ def ignore_video(video_id: int, session: Session = Depends(get_session)) -> dict
|
|||
for article in video.articles:
|
||||
if article.status != "published":
|
||||
article.status = "rejected"
|
||||
delete_video_storage_dir(video, settings)
|
||||
session.commit()
|
||||
return {"id": video.id, "status": video.status}
|
||||
|
||||
|
|
|
|||
|
|
@ -264,6 +264,7 @@ ENTITY_CORRECTIONS = {
|
|||
}
|
||||
|
||||
QUALITY_REWRITE_ATTEMPTS = 3
|
||||
CHAPTER_PLAN_MIN_DURATION_SECONDS = 20 * 60
|
||||
QUALITY_ERROR_MARKERS = [
|
||||
"LLM вернул невалидный JSON",
|
||||
"Статья содержит первое лицо",
|
||||
|
|
@ -273,6 +274,25 @@ QUALITY_ERROR_MARKERS = [
|
|||
"Статья слишком короткая",
|
||||
]
|
||||
|
||||
CHAPTER_PLAN_SYSTEM_PROMPT = """Ты редактор хронометража для русскоязычных видео.
|
||||
|
||||
По расшифровке длинного видео выдели самостоятельные тематические эпизоды. Каждый
|
||||
эпизод должен отражать смену темы, а не паузу, приветствие или техническую реплику.
|
||||
Верни только валидный JSON без Markdown и пояснений:
|
||||
{
|
||||
"chapters": [
|
||||
{"title": "Краткое название темы", "startSeconds": 0}
|
||||
]
|
||||
}
|
||||
|
||||
Правила:
|
||||
- первая глава всегда начинается с 0;
|
||||
- startSeconds - целое число секунд, главы идут строго по возрастанию;
|
||||
- не добавляй вымышленных фактов, дат и имён;
|
||||
- заголовок главы краткий, на русском языке, без точки в конце;
|
||||
- для длинного выпуска выделяй только содержательные темы, обычно от 3 до 10 глав.
|
||||
"""
|
||||
|
||||
|
||||
def run(command: list[str], cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run(command, cwd=cwd, text=True, capture_output=True, check=True)
|
||||
|
|
@ -515,11 +535,12 @@ def process_video(video_id: int, selected_chapters: list[dict[str, Any]] | None
|
|||
video.status = "processing"
|
||||
video.progress_percent = 5
|
||||
video.progress_stage = "Подготовка"
|
||||
video.progress_log = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}] Подготовка: задача взята worker"
|
||||
worker_log = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}] Подготовка: задача взята worker"
|
||||
video.progress_log = "\n".join(part for part in [video.progress_log, worker_log] if part)
|
||||
video.error_message = None
|
||||
session.commit()
|
||||
try:
|
||||
append_progress(video_id, 10, "Скачивание", "Скачиваю видео из VK")
|
||||
append_progress(video_id, 10, "Подготовка видео", "Проверяю локальный файл или источник")
|
||||
local_video = download_video(video)
|
||||
video.local_video_path = str(local_video)
|
||||
session.commit()
|
||||
|
|
@ -560,15 +581,79 @@ def process_video(video_id: int, selected_chapters: list[dict[str, Any]] | None
|
|||
raise
|
||||
|
||||
|
||||
@celery_app.task(name="app.worker.create_chapter_plan")
|
||||
def create_chapter_plan(video_id: int) -> dict[str, int | str]:
|
||||
"""Create a reusable, parseable chapter plan from a saved long-video transcript."""
|
||||
init_db()
|
||||
with SessionLocal() as session:
|
||||
video = session.get(Video, video_id)
|
||||
if not video:
|
||||
return {"status": "missing", "videoId": video_id}
|
||||
|
||||
duration = video.duration_seconds
|
||||
if duration is None and video.local_video_path:
|
||||
duration = media_duration_seconds(Path(video.local_video_path))
|
||||
video.duration_seconds = duration
|
||||
session.commit()
|
||||
if not duration or duration < CHAPTER_PLAN_MIN_DURATION_SECONDS:
|
||||
append_progress(
|
||||
video_id,
|
||||
None,
|
||||
"Хронометраж",
|
||||
"План глав не нужен: длительность ролика меньше 20 минут",
|
||||
)
|
||||
return {"status": "skipped", "videoId": video_id}
|
||||
|
||||
try:
|
||||
video.status = "planning"
|
||||
video.progress_percent = max(video.progress_percent or 0, 5)
|
||||
video.progress_stage = "Подготовка хронометража"
|
||||
session.commit()
|
||||
append_progress(video_id, 10, "Подготовка видео", "Проверяю локальный файл или источник")
|
||||
local_video = download_video(video)
|
||||
video.local_video_path = str(local_video)
|
||||
session.commit()
|
||||
append_progress(video_id, 35, "Транскрибация", "Проверяю сохраненную расшифровку")
|
||||
transcript_path = transcribe_video(local_video, video_id, video.transcript_path)
|
||||
video.transcript_path = str(transcript_path)
|
||||
session.commit()
|
||||
append_progress(video_id, 62, "Хронометраж", "Анализирую темы в сохраненной транскрибации")
|
||||
transcript = transcript_path.read_text(encoding="utf-8", errors="ignore")
|
||||
chapters = generate_chapter_plan(video, transcript)
|
||||
video.description = render_chapter_plan(chapters)
|
||||
video.progress_percent = max(video.progress_percent or 0, 72)
|
||||
video.progress_stage = "Хронометраж готов"
|
||||
video.status = "planned"
|
||||
session.commit()
|
||||
append_progress(
|
||||
video_id,
|
||||
72,
|
||||
"Хронометраж",
|
||||
f"Готов план: {len(chapters)} тематических глав",
|
||||
)
|
||||
return {"status": "ready", "videoId": video_id, "chapterCount": len(chapters)}
|
||||
except Exception as exc:
|
||||
session.rollback()
|
||||
video = session.get(Video, video_id)
|
||||
if video:
|
||||
video.status = "error"
|
||||
video.error_message = str(exc)
|
||||
video.progress_stage = "Ошибка"
|
||||
session.commit()
|
||||
append_progress(video_id, None, "Ошибка", str(exc), status="error")
|
||||
raise
|
||||
|
||||
|
||||
def download_video(video: Video) -> Path:
|
||||
if video.local_video_path:
|
||||
candidate = Path(video.local_video_path)
|
||||
if candidate.exists() and candidate.is_file() and candidate.stat().st_size > 0:
|
||||
append_progress(video.id, 35, "Скачивание", f"Использую уже скачанный файл: {candidate}")
|
||||
append_progress(video.id, 35, "Подготовка видео", f"Использую сохраненный локальный файл: {candidate.name}")
|
||||
return candidate
|
||||
target_dir = settings.videos_path / str(video.id)
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = target_dir / "video.%(ext)s"
|
||||
append_progress(video.id, 10, "Скачивание", "Локального файла нет, скачиваю видео из источника")
|
||||
command = ytdlp_base_args() + [
|
||||
"-f",
|
||||
"bestvideo[height<=720]+bestaudio/best[height<=720]/best",
|
||||
|
|
@ -850,6 +935,69 @@ def normalize_selected_chapters(chapters: list[dict[str, Any]] | None, duration_
|
|||
return sorted(normalized, key=lambda chapter: chapter["startSeconds"])
|
||||
|
||||
|
||||
def generate_chapter_plan(video: Video, transcript: str) -> list[dict[str, int | str]]:
|
||||
if not settings.llm_api_url.strip() or not settings.llm_api_key.strip():
|
||||
raise RuntimeError("LLM-редактор не настроен. Хронометраж не создан.")
|
||||
duration = video.duration_seconds
|
||||
if not duration or duration < CHAPTER_PLAN_MIN_DURATION_SECONDS:
|
||||
return []
|
||||
transcript = transcript.strip()
|
||||
if len(transcript) > settings.llm_max_transcript_chars:
|
||||
transcript = transcript[: settings.llm_max_transcript_chars] + "\n\n[Транскрипт обрезан по лимиту контекста.]"
|
||||
user_prompt = f"""Название ролика:
|
||||
{video.title}
|
||||
|
||||
Длительность ролика: {format_video_duration(duration)}.
|
||||
|
||||
Транскрипт:
|
||||
{transcript}
|
||||
|
||||
Составь тематический хронометраж ролика. Верни только JSON указанного формата."""
|
||||
payload = parse_llm_json(
|
||||
call_llm(
|
||||
user_prompt,
|
||||
system_prompt=CHAPTER_PLAN_SYSTEM_PROMPT,
|
||||
include_editor_instructions=False,
|
||||
)
|
||||
)
|
||||
return normalize_chapter_plan(payload, duration)
|
||||
|
||||
|
||||
def normalize_chapter_plan(payload: dict[str, Any], duration_seconds: int) -> list[dict[str, int | str]]:
|
||||
raw_chapters = payload.get("chapters")
|
||||
if not isinstance(raw_chapters, list):
|
||||
raise RuntimeError("LLM не вернул массив chapters для хронометража.")
|
||||
|
||||
by_start: dict[int, dict[str, int | str]] = {}
|
||||
for item in raw_chapters:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
try:
|
||||
start = int(item.get("startSeconds"))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if start < 0 or start >= duration_seconds or start in by_start:
|
||||
continue
|
||||
title = clean_generated_text(str(item.get("title") or ""))
|
||||
title = re.sub(r"\s+", " ", title).strip(" -—–\t\n")[:180]
|
||||
if not title:
|
||||
continue
|
||||
by_start[start] = {"title": title, "startSeconds": start}
|
||||
|
||||
chapters = [by_start[start] for start in sorted(by_start)]
|
||||
if len(chapters) < 2:
|
||||
raise RuntimeError("LLM вернул слишком мало тематических глав для длинного ролика.")
|
||||
chapters[0]["startSeconds"] = 0
|
||||
return chapters
|
||||
|
||||
|
||||
def render_chapter_plan(chapters: list[dict[str, int | str]]) -> str:
|
||||
return "\n".join(
|
||||
f"{seconds_to_timecode(int(chapter['startSeconds']))} {chapter['title']}"
|
||||
for chapter in chapters
|
||||
)
|
||||
|
||||
|
||||
def transcript_slice_by_time(transcript: str, start_seconds: int, end_seconds: int | None, duration_seconds: int | None) -> str:
|
||||
if not duration_seconds or duration_seconds <= 0:
|
||||
return transcript
|
||||
|
|
@ -996,30 +1144,35 @@ def article_count_instruction(video: Video) -> str:
|
|||
return "Сделай одну цельную статью, если нет явно отдельной второй темы."
|
||||
|
||||
|
||||
def call_llm(user_prompt: str) -> str:
|
||||
def call_llm(
|
||||
user_prompt: str,
|
||||
system_prompt: str | None = None,
|
||||
include_editor_instructions: bool = True,
|
||||
) -> str:
|
||||
url = settings.llm_api_url.rstrip("/") + "/chat/completions"
|
||||
headers = {
|
||||
"Authorization": f"Bearer {settings.llm_api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
system_prompt = ARTICLE_SYSTEM_PROMPT
|
||||
with SessionLocal() as session:
|
||||
extra_instructions = session.scalar(
|
||||
select(AppSetting.value).where(AppSetting.key == "llm_instructions")
|
||||
) or ""
|
||||
if extra_instructions.strip():
|
||||
system_prompt += (
|
||||
"\n\nДОПОЛНИТЕЛЬНЫЕ ИНСТРУКЦИИ РЕДАКТОРА:\n"
|
||||
"Ниже приведены настройки редактора. Учитывай их вместе с основными правилами, "
|
||||
"если они не противоречат формату JSON и системным ограничениям.\n"
|
||||
"---\n"
|
||||
f"{extra_instructions.strip()}\n"
|
||||
"---"
|
||||
)
|
||||
resolved_system_prompt = system_prompt or ARTICLE_SYSTEM_PROMPT
|
||||
if include_editor_instructions:
|
||||
with SessionLocal() as session:
|
||||
extra_instructions = session.scalar(
|
||||
select(AppSetting.value).where(AppSetting.key == "llm_instructions")
|
||||
) or ""
|
||||
if extra_instructions.strip():
|
||||
resolved_system_prompt += (
|
||||
"\n\nДОПОЛНИТЕЛЬНЫЕ ИНСТРУКЦИИ РЕДАКТОРА:\n"
|
||||
"Ниже приведены настройки редактора. Учитывай их вместе с основными правилами, "
|
||||
"если они не противоречат формату JSON и системным ограничениям.\n"
|
||||
"---\n"
|
||||
f"{extra_instructions.strip()}\n"
|
||||
"---"
|
||||
)
|
||||
payload = {
|
||||
"model": settings.llm_model,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "system", "content": resolved_system_prompt},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
"temperature": 0.15,
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ from sqlalchemy.orm import Session
|
|||
from app.config import Settings
|
||||
from app.database import Base
|
||||
from app.models import Video
|
||||
from app.routes import upload_video, video_storage_payload
|
||||
from app.routes import delete_video_storage_dir, upload_video, video_storage_payload
|
||||
|
||||
|
||||
class VideoUploadRouteTest(unittest.TestCase):
|
||||
|
|
@ -66,6 +66,27 @@ class VideoUploadRouteTest(unittest.TestCase):
|
|||
self.assertGreater(payload["totalBytes"], 0)
|
||||
self.assertGreaterEqual(payload["usedPercent"], 0)
|
||||
|
||||
def test_delete_storage_dir_removes_only_target_video_directory(self):
|
||||
with Session(self.engine) as session:
|
||||
video = Video(external_id="upload:delete", source_url="upload://delete", title="Delete")
|
||||
session.add(video)
|
||||
session.commit()
|
||||
session.refresh(video)
|
||||
|
||||
target = self.settings.videos_path / str(video.id)
|
||||
neighbour = self.settings.videos_path / str(video.id + 1)
|
||||
target.mkdir(parents=True)
|
||||
neighbour.mkdir(parents=True)
|
||||
(target / "video.mp4").write_bytes(b"video")
|
||||
(neighbour / "video.mp4").write_bytes(b"other")
|
||||
video.local_video_path = str(target / "video.mp4")
|
||||
|
||||
delete_video_storage_dir(video, self.settings)
|
||||
|
||||
self.assertFalse(target.exists())
|
||||
self.assertTrue((neighbour / "video.mp4").exists())
|
||||
self.assertIsNone(video.local_video_path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
28
dzen-assistant/tests/test_worker_chapter_plan.py
Normal file
28
dzen-assistant/tests/test_worker_chapter_plan.py
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import unittest
|
||||
|
||||
from app.worker import normalize_chapter_plan, render_chapter_plan
|
||||
|
||||
|
||||
class ChapterPlanTest(unittest.TestCase):
|
||||
def test_normalize_chapter_plan_makes_first_topic_start_at_zero(self):
|
||||
chapters = normalize_chapter_plan(
|
||||
{
|
||||
"chapters": [
|
||||
{"title": "Вступление", "startSeconds": 12},
|
||||
{"title": "Основная тема", "startSeconds": 340},
|
||||
]
|
||||
},
|
||||
900,
|
||||
)
|
||||
|
||||
self.assertEqual(chapters[0]["startSeconds"], 0)
|
||||
self.assertEqual(chapters[1]["startSeconds"], 340)
|
||||
self.assertIn("00:00 Вступление", render_chapter_plan(chapters))
|
||||
|
||||
def test_normalize_chapter_plan_rejects_single_topic(self):
|
||||
with self.assertRaisesRegex(RuntimeError, "слишком мало"):
|
||||
normalize_chapter_plan({"chapters": [{"title": "Тема", "startSeconds": 0}]}, 900)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Reference in a new issue