feat: refresh dzen assistant admin and processing pipeline
This commit is contained in:
parent
71dc381ac1
commit
9632308ddc
18 changed files with 2121 additions and 423 deletions
18
dzen-assistant/.dockerignore
Normal file
18
dzen-assistant/.dockerignore
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
.env
|
||||
.git
|
||||
.pytest_cache
|
||||
.ruff_cache
|
||||
__pycache__
|
||||
*.pyc
|
||||
|
||||
admin/dist
|
||||
admin/node_modules
|
||||
|
||||
data
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
|
||||
Dockerfile
|
||||
docker-compose*.yml
|
||||
README.md
|
||||
DEPLOY.md
|
||||
|
|
@ -1,11 +1,22 @@
|
|||
FROM node:22-alpine AS admin-build
|
||||
WORKDIR /admin
|
||||
COPY admin/package*.json ./
|
||||
RUN npm install
|
||||
RUN npm ci --no-audit --no-fund
|
||||
COPY admin ./
|
||||
RUN npm run build
|
||||
|
||||
FROM python:3.12-slim
|
||||
FROM python:3.12-slim AS python-wheels
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
COPY requirements.txt requirements-yt-dlp.txt ./
|
||||
RUN python -m pip install --no-cache-dir --upgrade pip wheel \
|
||||
&& python -m pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt -r requirements-yt-dlp.txt
|
||||
|
||||
FROM python:3.12-slim AS runtime
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
|
@ -13,12 +24,13 @@ ENV PYTHONUNBUFFERED=1
|
|||
WORKDIR /app
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ffmpeg ca-certificates curl libgomp1 \
|
||||
&& apt-get install -y --no-install-recommends ffmpeg ca-certificates libgomp1 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt \
|
||||
&& pip install --no-cache-dir yt-dlp
|
||||
COPY requirements.txt requirements-yt-dlp.txt ./
|
||||
COPY --from=python-wheels /wheels /wheels
|
||||
RUN python -m pip install --no-cache-dir --no-index --find-links=/wheels -r requirements.txt -r requirements-yt-dlp.txt \
|
||||
&& rm -rf /wheels
|
||||
|
||||
COPY app ./app
|
||||
COPY --from=admin-build /admin/dist ./admin_dist
|
||||
|
|
|
|||
|
|
@ -60,8 +60,8 @@ LLM_API_KEY=...
|
|||
LLM_MODEL=agent
|
||||
```
|
||||
|
||||
Агент должен отвечать JSON со списком статей. Если агент временно недоступен, конвейер создаст простой
|
||||
fallback-черновик из транскрипта.
|
||||
Агент должен отвечать JSON со списком статей. Если агент временно недоступен, конвейер покажет
|
||||
ошибку обработки и не создаст черновик из сырой транскрибации.
|
||||
|
||||
## MVP-поток
|
||||
|
||||
|
|
|
|||
|
|
@ -3,11 +3,18 @@
|
|||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="icon" type="image/png" href="/favicon.png" />
|
||||
<title>Дзен-ассистент</title>
|
||||
</head>
|
||||
<body>
|
||||
<!--
|
||||
THESIS: an editorial production desk that keeps video-to-article work visible at a glance and refuses dashboard clutter.
|
||||
OWN-WORLD: cool white paper, graphite type, thin rules, restrained semantic color, and compact publication rows.
|
||||
STORY: the operator sees what arrived, what is processing, and what is ready to publish without opening a second screen.
|
||||
FIRST VIEWPORT: a compact command header, metric rail, then two equal work columns for videos and accepted articles.
|
||||
FORM: editorial studio, operate mode. FINISH: unreviewed and undocumented is unfinished; this build ends with the finish review.
|
||||
-->
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
|
|
|||
BIN
dzen-assistant/admin/public/favicon.png
Normal file
BIN
dzen-assistant/admin/public/favicon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
File diff suppressed because it is too large
Load diff
|
|
@ -35,6 +35,127 @@
|
|||
}
|
||||
|
||||
@layer components {
|
||||
.editorial-studio {
|
||||
background: hsl(210 20% 95%);
|
||||
}
|
||||
|
||||
.editorial-studio .app-header {
|
||||
border-color: hsl(214 18% 82%);
|
||||
border-radius: 0.35rem;
|
||||
box-shadow: 0 1px 0 hsl(224 13% 12% / 0.04);
|
||||
}
|
||||
|
||||
.editorial-studio .app-header h1 {
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.editorial-studio .vk-sync-button {
|
||||
border-color: #0077ff;
|
||||
background: #0077ff;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.editorial-studio .vk-sync-button:hover {
|
||||
border-color: #0067e6;
|
||||
background: #0067e6;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.editorial-studio .manual-import {
|
||||
border-color: hsl(214 18% 85%);
|
||||
box-shadow: 0 1px 0 hsl(224 13% 12% / 0.03);
|
||||
}
|
||||
|
||||
.editorial-studio .metrics-strip .metric-tile {
|
||||
min-height: 82px;
|
||||
border-color: hsl(214 18% 82%);
|
||||
border-radius: 0;
|
||||
background: hsl(0 0% 100% / 0.9);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.editorial-studio .metrics-strip .metric-tile:first-child {
|
||||
border-radius: 0.35rem 0 0 0.35rem;
|
||||
}
|
||||
|
||||
.editorial-studio .metrics-strip .metric-tile:last-child {
|
||||
border-radius: 0 0.35rem 0.35rem 0;
|
||||
}
|
||||
|
||||
.editorial-studio .metrics-strip .metric-tile [data-slot="card-description"] {
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.editorial-studio .metrics-strip .metric-tile [data-slot="card-title"] {
|
||||
color: hsl(224 13% 12%);
|
||||
font-size: 1.5rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.editorial-studio .work-column {
|
||||
overflow: hidden;
|
||||
border-color: hsl(214 18% 82%);
|
||||
border-radius: 0.35rem;
|
||||
background: hsl(0 0% 100% / 0.94);
|
||||
box-shadow: 0 6px 18px hsl(224 13% 12% / 0.05);
|
||||
}
|
||||
|
||||
.editorial-studio .work-column:first-child {
|
||||
border-top: 3px solid hsl(35 92% 52%);
|
||||
}
|
||||
|
||||
.editorial-studio .work-column:last-child {
|
||||
border-top: 3px solid hsl(214 82% 52%);
|
||||
}
|
||||
|
||||
.editorial-studio .work-column > [data-slot="card-header"] {
|
||||
border-bottom: 1px solid hsl(214 18% 89%);
|
||||
background: hsl(210 20% 97% / 0.95);
|
||||
padding: 1rem 1.1rem;
|
||||
}
|
||||
|
||||
.editorial-studio .work-column > [data-slot="card-header"] [data-slot="card-title"] {
|
||||
letter-spacing: -0.015em;
|
||||
}
|
||||
|
||||
.editorial-studio .work-list {
|
||||
background: hsl(210 20% 97% / 0.72);
|
||||
padding: 0.9rem;
|
||||
}
|
||||
|
||||
.editorial-studio .production-item,
|
||||
.editorial-studio .article-item {
|
||||
border-color: hsl(214 18% 87%);
|
||||
border-radius: 0.5rem;
|
||||
box-shadow: 0 1px 1px hsl(224 13% 12% / 0.025);
|
||||
transition: border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
|
||||
}
|
||||
|
||||
.editorial-studio .production-item:hover,
|
||||
.editorial-studio .article-item:hover {
|
||||
border-color: hsl(214 18% 76%);
|
||||
box-shadow: 0 5px 14px hsl(224 13% 12% / 0.07);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.editorial-studio .production-item h3,
|
||||
.editorial-studio .article-item h3 {
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.editorial-studio .production-item .rounded-full.bg-muted {
|
||||
background: hsl(214 18% 90%);
|
||||
}
|
||||
|
||||
@media (max-width: 1279px) {
|
||||
.editorial-studio .work-list {
|
||||
max-height: none;
|
||||
}
|
||||
}
|
||||
|
||||
.modal-overlay {
|
||||
animation: modal-overlay-in 140ms ease-out both;
|
||||
}
|
||||
|
|
@ -125,7 +246,7 @@
|
|||
}
|
||||
|
||||
.article-preview blockquote {
|
||||
@apply mx-auto mt-6 max-w-3xl border-l-4 border-zinc-300 pl-5 text-lg italic leading-8 text-zinc-700;
|
||||
@apply mx-auto mt-6 max-w-3xl border-l-2 border-zinc-300 pl-5 text-lg italic leading-8 text-zinc-700;
|
||||
}
|
||||
|
||||
.article-preview ul,
|
||||
|
|
@ -190,6 +311,14 @@
|
|||
@apply text-lg leading-8;
|
||||
}
|
||||
|
||||
.article-editorjs a {
|
||||
@apply text-blue-600 underline decoration-blue-300 underline-offset-2 transition-colors;
|
||||
}
|
||||
|
||||
.article-editorjs a:hover {
|
||||
@apply text-blue-800 decoration-blue-500;
|
||||
}
|
||||
|
||||
.article-editorjs .ce-header {
|
||||
@apply font-bold leading-tight tracking-normal text-zinc-950;
|
||||
}
|
||||
|
|
@ -203,7 +332,7 @@
|
|||
}
|
||||
|
||||
.article-editorjs .cdx-quote {
|
||||
@apply border-l-4 border-zinc-300 pl-5;
|
||||
@apply border-l-2 border-zinc-300 pl-5;
|
||||
}
|
||||
|
||||
.article-editorjs .cdx-quote__text {
|
||||
|
|
@ -218,6 +347,37 @@
|
|||
@apply aspect-video w-full object-cover;
|
||||
}
|
||||
|
||||
.article-editorjs .ce-block.is-image-paste-target .image-tool__image::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 2;
|
||||
pointer-events: none;
|
||||
background: rgb(24 24 27 / 0.5);
|
||||
backdrop-filter: blur(1px);
|
||||
}
|
||||
|
||||
.article-editorjs .ce-block.is-image-paste-target .image-tool__image::before {
|
||||
content: "Вставьте изображение из буфера обмена или принесите файл";
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
z-index: 3;
|
||||
max-width: min(90%, 28rem);
|
||||
transform: translate(-50%, -50%);
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgb(255 255 255 / 0.42);
|
||||
background: rgb(24 24 27 / 0.76);
|
||||
padding: 0.55rem 0.9rem;
|
||||
color: white;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.25;
|
||||
letter-spacing: 0;
|
||||
text-align: center;
|
||||
box-shadow: 0 12px 30px rgb(0 0 0 / 0.22);
|
||||
}
|
||||
|
||||
.article-editorjs .ce-block.is-random-frame-loading .image-tool__image::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
|
|
|
|||
102
dzen-assistant/app/chapters.py
Normal file
102
dzen-assistant/app/chapters.py
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VideoChapter:
|
||||
id: str
|
||||
title: str
|
||||
start_seconds: int
|
||||
end_seconds: int | None
|
||||
|
||||
@property
|
||||
def duration_seconds(self) -> int | None:
|
||||
if self.end_seconds is None:
|
||||
return None
|
||||
return max(0, self.end_seconds - self.start_seconds)
|
||||
|
||||
|
||||
TIMECODE_RE = re.compile(
|
||||
r"(?:^|\n)\s*(?:[-*]\s*)?(?:\[(?P<link_time>\d{1,2}:\d{2}(?::\d{2})?)\]\([^)]+\)|(?P<plain_time>\d{1,2}:\d{2}(?::\d{2})?))\s*(?P<title>[^\n]+)",
|
||||
flags=re.I,
|
||||
)
|
||||
|
||||
|
||||
def timecode_to_seconds(value: str) -> int:
|
||||
parts = [int(part) for part in value.split(":")]
|
||||
if len(parts) == 2:
|
||||
minutes, seconds = parts
|
||||
return minutes * 60 + seconds
|
||||
hours, minutes, seconds = parts
|
||||
return hours * 3600 + minutes * 60 + seconds
|
||||
|
||||
|
||||
def seconds_to_timecode(seconds: int | None) -> str:
|
||||
if seconds is None:
|
||||
return ""
|
||||
seconds = max(0, seconds)
|
||||
hours = seconds // 3600
|
||||
minutes = (seconds % 3600) // 60
|
||||
rest = seconds % 60
|
||||
if hours:
|
||||
return f"{hours:02d}:{minutes:02d}:{rest:02d}"
|
||||
return f"{minutes:02d}:{rest:02d}"
|
||||
|
||||
|
||||
def clean_chapter_title(title: str) -> str:
|
||||
title = re.sub(r"\]\([^)]+\)", "", title)
|
||||
title = re.sub(r"\s+", " ", title).strip(" -—–\t")
|
||||
return title[:180].strip() or "Эпизод"
|
||||
|
||||
|
||||
def parse_video_chapters(description: str | None, duration_seconds: int | None = None) -> list[VideoChapter]:
|
||||
raw: list[tuple[int, str]] = []
|
||||
for match in TIMECODE_RE.finditer(description or ""):
|
||||
time_value = match.group("link_time") or match.group("plain_time")
|
||||
if not time_value:
|
||||
continue
|
||||
start = timecode_to_seconds(time_value)
|
||||
title = clean_chapter_title(match.group("title") or "")
|
||||
raw.append((start, title))
|
||||
|
||||
deduped: list[tuple[int, str]] = []
|
||||
seen: set[int] = set()
|
||||
for start, title in sorted(raw, key=lambda item: item[0]):
|
||||
if start in seen:
|
||||
continue
|
||||
if duration_seconds and start >= duration_seconds:
|
||||
continue
|
||||
seen.add(start)
|
||||
deduped.append((start, title))
|
||||
|
||||
chapters: list[VideoChapter] = []
|
||||
for index, (start, title) in enumerate(deduped):
|
||||
next_start = deduped[index + 1][0] if index + 1 < len(deduped) else duration_seconds
|
||||
if next_start is not None and next_start <= start:
|
||||
continue
|
||||
chapters.append(
|
||||
VideoChapter(
|
||||
id=f"{index + 1}-{start}",
|
||||
title=title,
|
||||
start_seconds=start,
|
||||
end_seconds=next_start,
|
||||
)
|
||||
)
|
||||
return chapters
|
||||
|
||||
|
||||
def chapter_to_payload(chapter: VideoChapter, default_selected_min_seconds: int = 180) -> dict[str, Any]:
|
||||
duration = chapter.duration_seconds
|
||||
return {
|
||||
"id": chapter.id,
|
||||
"title": chapter.title,
|
||||
"startSeconds": chapter.start_seconds,
|
||||
"endSeconds": chapter.end_seconds,
|
||||
"durationSeconds": duration,
|
||||
"startTimecode": seconds_to_timecode(chapter.start_seconds),
|
||||
"endTimecode": seconds_to_timecode(chapter.end_seconds),
|
||||
"selected": bool(duration is not None and duration >= default_selected_min_seconds),
|
||||
}
|
||||
|
|
@ -27,11 +27,14 @@ class Settings(BaseSettings):
|
|||
llm_api_key: str = ""
|
||||
llm_model: str = "agent"
|
||||
llm_timeout_seconds: int = 120
|
||||
llm_max_transcript_chars: int = 45000
|
||||
llm_max_transcript_chars: int = 24000
|
||||
llm_retry_attempts: int = 3
|
||||
|
||||
max_concurrent_videos: int = 1
|
||||
frame_candidates: int = 12
|
||||
rss_limit: int = 100
|
||||
whisper_chunk_seconds: int = 600
|
||||
whisper_chunk_min_duration_seconds: int = 1800
|
||||
|
||||
@property
|
||||
def sqlite_url(self) -> str:
|
||||
|
|
|
|||
|
|
@ -47,6 +47,9 @@ def migrate_db() -> None:
|
|||
"progress_percent": "INTEGER NOT NULL DEFAULT 0",
|
||||
"progress_stage": "TEXT NOT NULL DEFAULT ''",
|
||||
"progress_log": "TEXT NOT NULL DEFAULT ''",
|
||||
},
|
||||
"articles": {
|
||||
"feature_image_url": "TEXT NOT NULL DEFAULT ''",
|
||||
}
|
||||
}
|
||||
with engine.begin() as connection:
|
||||
|
|
|
|||
|
|
@ -39,7 +39,15 @@ if admin_dist.exists():
|
|||
app.mount("/assets", StaticFiles(directory=admin_dist / "assets"), name="admin-assets")
|
||||
|
||||
|
||||
@app.get("/favicon.png", include_in_schema=False)
|
||||
def favicon() -> FileResponse:
|
||||
return FileResponse(admin_dist / "favicon.png", media_type="image/png")
|
||||
|
||||
|
||||
@app.get("/admin")
|
||||
@app.get("/admin/{path:path}")
|
||||
def admin_index() -> FileResponse:
|
||||
return FileResponse(admin_dist / "index.html")
|
||||
return FileResponse(
|
||||
admin_dist / "index.html",
|
||||
headers={"Cache-Control": "no-store, no-cache, must-revalidate"},
|
||||
)
|
||||
|
|
|
|||
|
|
@ -20,6 +20,15 @@ class Source(Base):
|
|||
videos: Mapped[list["Video"]] = relationship(back_populates="source")
|
||||
|
||||
|
||||
class AppSetting(Base):
|
||||
__tablename__ = "app_settings"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
key: Mapped[str] = mapped_column(String(80), unique=True, index=True)
|
||||
value: Mapped[str] = mapped_column(Text, default="")
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||
|
||||
|
||||
class Video(Base):
|
||||
__tablename__ = "videos"
|
||||
__table_args__ = (UniqueConstraint("source_id", "external_id", name="uq_videos_source_external"),)
|
||||
|
|
@ -73,6 +82,7 @@ class Article(Base):
|
|||
lead: Mapped[str] = mapped_column(Text, default="")
|
||||
body_html: Mapped[str] = mapped_column(Text, default="")
|
||||
cta_html: Mapped[str] = mapped_column(Text, default="")
|
||||
feature_image_url: Mapped[str] = mapped_column(Text, default="")
|
||||
status: Mapped[str] = mapped_column(String(32), default="draft", index=True)
|
||||
rss_guid: Mapped[str | None] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
|
|
|||
|
|
@ -5,6 +5,35 @@ TRANSCRIPT_PLACEHOLDERS = [
|
|||
"Транскрибация еще не подключена. Это технический черновик для проверки RSS-конвейера.",
|
||||
]
|
||||
|
||||
TRANSCRIPT_MARKERS = [
|
||||
"в данном видео",
|
||||
"в этом видео",
|
||||
"в ролике",
|
||||
"в этом ролике",
|
||||
"транскрипт",
|
||||
"расшифровка",
|
||||
"сегодня я расскажу",
|
||||
"я думаю",
|
||||
"я считаю",
|
||||
"мне кажется",
|
||||
"давайте разбер",
|
||||
"подписывайтесь",
|
||||
]
|
||||
|
||||
FIRST_PERSON_RE = re.compile(
|
||||
r"(^|[^\wа-яё])("
|
||||
r"я|мы|мне|меня|мной|нам|нас|нами|наш|наша|наше|наши|"
|
||||
r"думаю|считаю|скажу|расскажу|покажу|объясню|перейдем|посмотрим|разберем"
|
||||
r")($|[^\wа-яё])",
|
||||
flags=re.I,
|
||||
)
|
||||
|
||||
SUSPICIOUS_ENTITY_ERRORS = [
|
||||
"армузский пролив",
|
||||
"армузского пролива",
|
||||
"армузском проливе",
|
||||
"бабльман",
|
||||
]
|
||||
|
||||
def contains_transcript_placeholder(text: str | None) -> bool:
|
||||
value = text or ""
|
||||
|
|
@ -17,6 +46,13 @@ def meaningful_text_length(text: str | None) -> int:
|
|||
return len(value)
|
||||
|
||||
|
||||
def plain_text(text: str | None) -> str:
|
||||
value = re.sub(r"https?://\S+", " ", text or "")
|
||||
value = re.sub(r"<[^>]+>", " ", value)
|
||||
value = re.sub(r"\s+", " ", value).strip()
|
||||
return value
|
||||
|
||||
|
||||
def validate_transcript_text(text: str) -> None:
|
||||
if contains_transcript_placeholder(text):
|
||||
raise RuntimeError("Транскрибация не выполнена: найден технический placeholder вместо текста.")
|
||||
|
|
@ -30,3 +66,16 @@ def validate_article_content(title: str, lead: str, body_html: str) -> None:
|
|||
raise RuntimeError("Статья содержит технический текст вместо транскрибации.")
|
||||
if meaningful_text_length((lead or "") + "\n" + (body_html or "")) < 800:
|
||||
raise RuntimeError("Статья слишком короткая для публикации в RSS.")
|
||||
normalized = plain_text(content).lower()
|
||||
for marker in TRANSCRIPT_MARKERS:
|
||||
if marker in normalized:
|
||||
raise RuntimeError(f"Статья похожа на необработанную транскрибацию: найдено «{marker}».")
|
||||
first_person_match = FIRST_PERSON_RE.search(normalized)
|
||||
if first_person_match:
|
||||
marker = first_person_match.group(2)
|
||||
raise RuntimeError(
|
||||
f"Статья содержит первое лицо или разговорную подачу вместо аналитического текста: найдено «{marker}»."
|
||||
)
|
||||
for error in SUSPICIOUS_ENTITY_ERRORS:
|
||||
if error in normalized:
|
||||
raise RuntimeError(f"Статья содержит подозрительную ошибку в имени или географии: «{error}».")
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ import asyncio
|
|||
from datetime import datetime, timezone
|
||||
from html import escape, unescape
|
||||
from html.parser import HTMLParser
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import random
|
||||
|
|
@ -10,18 +12,19 @@ import subprocess
|
|||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, File, HTTPException, Query, UploadFile, WebSocket, WebSocketDisconnect
|
||||
from fastapi.responses import HTMLResponse, Response
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse, Response
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import Settings, get_settings
|
||||
from app.captions import strip_leading_duplicate_title
|
||||
from app.chapters import chapter_to_payload, parse_video_chapters
|
||||
from app.database import SessionLocal, get_session
|
||||
from app.models import Article, Frame, Source, Video
|
||||
from app.models import AppSetting, Article, Frame, Source, Video
|
||||
from app.quality import validate_article_content
|
||||
from app.rss import article_url, build_feed_xml, render_article_html
|
||||
from app.worker import process_video, scan_sources
|
||||
from app.worker import best_thumbnail_url, parse_upload_date, process_video, scan_sources, ytdlp_base_args
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
|
@ -32,6 +35,7 @@ ZEN_VERIFICATION_META = (
|
|||
'<meta name="zen-verification" '
|
||||
'content="y2a3098Zp7skRQXDYdkEOwOXFDdQsSzU7bkouMOhtBECx6zgC5CCqVZRxslhhjSg" />'
|
||||
)
|
||||
PUBLIC_REDIRECT_URL = "https://nstarikov.ru"
|
||||
|
||||
|
||||
class SourceIn(BaseModel):
|
||||
|
|
@ -41,6 +45,15 @@ class SourceIn(BaseModel):
|
|||
enabled: bool = True
|
||||
|
||||
|
||||
class ManualVideoIn(BaseModel):
|
||||
url: str
|
||||
|
||||
|
||||
class AppSettingsIn(BaseModel):
|
||||
signatureHtml: str = ""
|
||||
llmInstructions: str = ""
|
||||
|
||||
|
||||
class ChatIn(BaseModel):
|
||||
message: str
|
||||
|
||||
|
|
@ -48,17 +61,72 @@ class ChatIn(BaseModel):
|
|||
class ArticleUpdateIn(BaseModel):
|
||||
title: str
|
||||
editableHtml: str
|
||||
featureImageUrl: str | None = None
|
||||
|
||||
|
||||
class ArticlePublishIn(BaseModel):
|
||||
publishedAt: datetime | None = None
|
||||
|
||||
|
||||
class VideoChapterIn(BaseModel):
|
||||
id: str | None = None
|
||||
title: str
|
||||
startSeconds: int
|
||||
endSeconds: int | None = None
|
||||
|
||||
|
||||
class VideoProcessIn(BaseModel):
|
||||
chapters: list[VideoChapterIn] | None = None
|
||||
recreateDrafts: bool = False
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
SETTING_SIGNATURE = "article_signature_html"
|
||||
SETTING_LLM_INSTRUCTIONS = "llm_instructions"
|
||||
|
||||
|
||||
def app_settings_payload(session: Session) -> dict[str, str]:
|
||||
values = {
|
||||
setting.key: setting.value
|
||||
for setting in session.scalars(
|
||||
select(AppSetting).where(AppSetting.key.in_([SETTING_SIGNATURE, SETTING_LLM_INSTRUCTIONS]))
|
||||
).all()
|
||||
}
|
||||
return {
|
||||
"signatureHtml": values.get(SETTING_SIGNATURE, ""),
|
||||
"llmInstructions": values.get(SETTING_LLM_INSTRUCTIONS, ""),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/settings")
|
||||
def get_app_settings(session: Session = Depends(get_session)) -> dict[str, str]:
|
||||
return app_settings_payload(session)
|
||||
|
||||
|
||||
@router.put("/api/settings")
|
||||
def update_app_settings(payload: AppSettingsIn, session: Session = Depends(get_session)) -> dict[str, str]:
|
||||
values = {
|
||||
SETTING_SIGNATURE: payload.signatureHtml.strip(),
|
||||
SETTING_LLM_INSTRUCTIONS: payload.llmInstructions.strip(),
|
||||
}
|
||||
existing = {
|
||||
setting.key: setting
|
||||
for setting in session.scalars(select(AppSetting).where(AppSetting.key.in_(values))).all()
|
||||
}
|
||||
for key, value in values.items():
|
||||
setting = existing.get(key)
|
||||
if setting:
|
||||
setting.value = value
|
||||
else:
|
||||
session.add(AppSetting(key=key, value=value))
|
||||
session.commit()
|
||||
return app_settings_payload(session)
|
||||
|
||||
|
||||
@router.get("/feed")
|
||||
def feed(session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> Response:
|
||||
return Response(build_feed_xml(session, settings), media_type="application/rss+xml; charset=utf-8")
|
||||
|
|
@ -180,13 +248,24 @@ def sanitize_article_editor_html(html: str) -> str:
|
|||
sanitizer = ArticleHtmlSanitizer()
|
||||
sanitizer.feed(html)
|
||||
sanitized = "".join(sanitizer.parts)
|
||||
sanitized = strip_article_cover_html(sanitized)
|
||||
sanitized = re.sub(r"<p>\s*</p>", "", sanitized)
|
||||
sanitized = re.sub(r"\n{3,}", "\n\n", sanitized).strip()
|
||||
return sanitized
|
||||
|
||||
|
||||
def strip_article_cover_html(html: str) -> str:
|
||||
return re.sub(
|
||||
r"<figure\b[^>]*class=[\"'][^\"']*\barticle-cover\b[^\"']*[\"'][^>]*>.*?</figure>",
|
||||
"",
|
||||
html or "",
|
||||
flags=re.I | re.S,
|
||||
).strip()
|
||||
|
||||
|
||||
def editable_article_html(article: Article) -> str:
|
||||
html = "\n".join(part for part in [article.lead, article.body_html] if part).strip()
|
||||
html = "\n".join(part for part in [article.lead, article.body_html, article.cta_html] if part).strip()
|
||||
html = strip_article_cover_html(html)
|
||||
return strip_leading_duplicate_title(html, article.title)
|
||||
|
||||
|
||||
|
|
@ -198,6 +277,8 @@ def split_lead_and_body(html: str) -> tuple[str, str]:
|
|||
|
||||
|
||||
def article_cover_url(session: Session, article: Article) -> str | None:
|
||||
if article.feature_image_url:
|
||||
return article.feature_image_url
|
||||
if article.video and article.video.thumbnail_url:
|
||||
return article.video.thumbnail_url
|
||||
if not article.video_id:
|
||||
|
|
@ -273,226 +354,24 @@ def zen_verification_head() -> Response:
|
|||
return Response(media_type="text/html; charset=utf-8")
|
||||
|
||||
|
||||
@router.get("/", response_class=HTMLResponse)
|
||||
def home(
|
||||
page: int = Query(1, ge=1),
|
||||
session: Session = Depends(get_session),
|
||||
settings: Settings = Depends(get_settings),
|
||||
) -> str:
|
||||
per_page = 12
|
||||
total = session.scalar(select(func.count(Article.id)).where(Article.status == "published")) or 0
|
||||
pages = max(1, (total + per_page - 1) // per_page)
|
||||
current_page = min(page, pages)
|
||||
articles = session.scalars(
|
||||
select(Article)
|
||||
.where(Article.status == "published")
|
||||
.order_by(Article.published_at.desc(), Article.id.desc())
|
||||
.offset((current_page - 1) * per_page)
|
||||
.limit(per_page)
|
||||
).all()
|
||||
|
||||
cards = []
|
||||
for article in articles:
|
||||
url = article_url(settings, article)
|
||||
cover = article_cover_url(session, article)
|
||||
image_html = (
|
||||
f'<img src="{escape(cover)}" alt="{escape(article.title)}" class="h-full w-full object-cover">'
|
||||
if cover
|
||||
else '<div class="flex h-full w-full items-center justify-center bg-zinc-100 text-sm text-zinc-400">Без изображения</div>'
|
||||
)
|
||||
excerpt = plain_excerpt(render_article_html(article, include_video_embed=False))
|
||||
cards.append(
|
||||
f"""
|
||||
<article class="overflow-hidden rounded-lg border border-zinc-200 bg-white shadow-sm transition hover:border-zinc-300 hover:shadow-md">
|
||||
<a href="{escape(url)}" class="block aspect-video bg-zinc-100">{image_html}</a>
|
||||
<div class="flex min-h-[220px] flex-col gap-4 p-5">
|
||||
<div class="flex flex-col gap-2">
|
||||
<a href="{escape(url)}" class="text-xl font-bold leading-snug tracking-normal text-zinc-950 hover:text-zinc-700">{escape(article.title)}</a>
|
||||
<p class="text-sm leading-6 text-zinc-600">{escape(excerpt)}</p>
|
||||
</div>
|
||||
<a href="{escape(url)}" class="mt-auto inline-flex w-fit items-center rounded-md bg-zinc-950 px-4 py-2 text-sm font-medium text-white hover:bg-zinc-800">Читать полностью</a>
|
||||
</div>
|
||||
</article>""".strip()
|
||||
)
|
||||
|
||||
previous_link = (
|
||||
f'<a href="/?page={current_page - 1}" class="rounded-md border border-zinc-200 bg-white px-4 py-2 text-sm font-medium text-zinc-900 hover:bg-zinc-50">Назад</a>'
|
||||
if current_page > 1
|
||||
else '<span class="rounded-md border border-zinc-100 bg-zinc-100 px-4 py-2 text-sm font-medium text-zinc-400">Назад</span>'
|
||||
)
|
||||
next_link = (
|
||||
f'<a href="/?page={current_page + 1}" class="rounded-md border border-zinc-200 bg-white px-4 py-2 text-sm font-medium text-zinc-900 hover:bg-zinc-50">Вперед</a>'
|
||||
if current_page < pages
|
||||
else '<span class="rounded-md border border-zinc-100 bg-zinc-100 px-4 py-2 text-sm font-medium text-zinc-400">Вперед</span>'
|
||||
)
|
||||
empty_state = ""
|
||||
if not articles:
|
||||
empty_state = '<div class="rounded-lg border border-zinc-200 bg-white p-8 text-center text-zinc-600">Опубликованных материалов пока нет.</div>'
|
||||
|
||||
return f"""<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
{ZEN_VERIFICATION_META}
|
||||
<link rel="alternate" type="application/rss+xml" title="Николай Стариков" href="{escape(settings.public_base_url.rstrip())}/feed">
|
||||
<title>Николай Стариков</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
</head>
|
||||
<body class="bg-zinc-50 text-zinc-950">
|
||||
<main class="mx-auto flex w-full max-w-[1180px] flex-col gap-8 px-4 py-8 sm:px-6 lg:px-8">
|
||||
<header class="flex flex-col gap-3 border-b border-zinc-200 pb-6">
|
||||
<p class="text-sm font-medium uppercase tracking-normal text-zinc-500">Лента материалов</p>
|
||||
<div class="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
|
||||
<div class="flex max-w-3xl flex-col gap-3">
|
||||
<h1 class="text-4xl font-bold leading-tight tracking-normal text-zinc-950 sm:text-5xl">Николай Стариков</h1>
|
||||
<p class="text-lg leading-8 text-zinc-600">Публикации, подготовленные по выступлениям и видеоматериалам.</p>
|
||||
</div>
|
||||
<a href="/feed" class="inline-flex w-fit items-center rounded-md border border-zinc-200 bg-white px-4 py-2 text-sm font-medium text-zinc-900 hover:bg-zinc-50">RSS</a>
|
||||
</div>
|
||||
</header>
|
||||
{empty_state}
|
||||
<section class="grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-3">
|
||||
{chr(10).join(cards)}
|
||||
</section>
|
||||
<nav class="flex items-center justify-between border-t border-zinc-200 pt-6">
|
||||
{previous_link}
|
||||
<span class="text-sm text-zinc-500">Страница {current_page} из {pages}</span>
|
||||
{next_link}
|
||||
</nav>
|
||||
</main>
|
||||
</body>
|
||||
</html>"""
|
||||
@router.get("/")
|
||||
def home() -> RedirectResponse:
|
||||
return RedirectResponse(url=PUBLIC_REDIRECT_URL, status_code=302)
|
||||
|
||||
|
||||
@router.head("/")
|
||||
def home_head() -> Response:
|
||||
return Response(media_type="text/html; charset=utf-8")
|
||||
def home_head() -> RedirectResponse:
|
||||
return RedirectResponse(url=PUBLIC_REDIRECT_URL, status_code=302)
|
||||
|
||||
|
||||
@router.get("/posts/{slug}", response_class=HTMLResponse)
|
||||
def post(slug: str, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> str:
|
||||
article = session.scalar(select(Article).where(Article.slug == slug))
|
||||
if not article or article.status != "published":
|
||||
raise HTTPException(status_code=404, detail="Article not found")
|
||||
title = escape(article.title)
|
||||
return f"""<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="canonical" href="{article_url(settings, article)}">
|
||||
<title>{title}</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<style>
|
||||
article :where(p) {{
|
||||
margin-top: 1rem;
|
||||
font-size: 1.125rem;
|
||||
line-height: 1.8;
|
||||
color: rgb(39 39 42);
|
||||
}}
|
||||
article :where(h2) {{
|
||||
margin-top: 2.25rem;
|
||||
font-size: 1.875rem;
|
||||
line-height: 1.2;
|
||||
font-weight: 700;
|
||||
color: rgb(24 24 27);
|
||||
}}
|
||||
article :where(figure) {{
|
||||
margin: 2rem 0;
|
||||
}}
|
||||
article :where(img) {{
|
||||
width: 100%;
|
||||
aspect-ratio: 16 / 9;
|
||||
object-fit: cover;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid rgb(228 228 231);
|
||||
background: rgb(244 244 245);
|
||||
}}
|
||||
article :where(figcaption) {{
|
||||
margin-top: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
color: rgb(113 113 122);
|
||||
}}
|
||||
article :where(.premium-cta) {{
|
||||
margin-top: 2.5rem;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid rgb(120 87 43);
|
||||
background: rgb(9 9 11);
|
||||
padding: 1.5rem;
|
||||
color: rgb(250 250 250);
|
||||
}}
|
||||
article :where(.premium-cover) {{
|
||||
margin: 0 0 1.5rem 0;
|
||||
}}
|
||||
article :where(.premium-cta h2) {{
|
||||
margin-top: 0;
|
||||
color: rgb(250 250 250);
|
||||
}}
|
||||
article :where(.premium-cta p) {{
|
||||
color: rgb(228 228 231);
|
||||
}}
|
||||
article :where(.premium-cta a) {{
|
||||
font-weight: 700;
|
||||
color: rgb(251 191 36);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 3px;
|
||||
}}
|
||||
article :where(.cultural-initiatives) {{
|
||||
margin-top: 2.5rem;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid rgb(186 230 253);
|
||||
background: rgb(240 249 255);
|
||||
padding: 1.25rem;
|
||||
}}
|
||||
article :where(.cultural-initiatives p) {{
|
||||
margin: 0.5rem 0;
|
||||
color: rgb(12 74 110);
|
||||
}}
|
||||
article :where(.cultural-initiatives a) {{
|
||||
font-weight: 700;
|
||||
color: rgb(2 132 199);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 3px;
|
||||
}}
|
||||
article :where(.video-embed) {{
|
||||
margin-top: 2.5rem;
|
||||
border-top: 1px solid rgb(228 228 231);
|
||||
padding-top: 2rem;
|
||||
}}
|
||||
article :where(.video-embed__frame) {{
|
||||
margin-top: 1rem;
|
||||
aspect-ratio: 16 / 9;
|
||||
overflow: hidden;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid rgb(228 228 231);
|
||||
background: rgb(24 24 27);
|
||||
}}
|
||||
article :where(iframe) {{
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: block;
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-zinc-50 text-zinc-950">
|
||||
<main class="mx-auto w-full max-w-[1024px] px-4 py-8 sm:px-6 lg:px-8">
|
||||
<article class="rounded-lg border border-zinc-200 bg-white px-5 py-7 shadow-sm sm:px-8 lg:px-10">
|
||||
<h1 class="text-3xl font-bold leading-tight tracking-normal text-zinc-950 sm:text-4xl">{title}</h1>
|
||||
{render_article_html(article)}
|
||||
</article>
|
||||
</main>
|
||||
</body>
|
||||
</html>"""
|
||||
@router.get("/posts/{slug}")
|
||||
def post(slug: str) -> RedirectResponse:
|
||||
return RedirectResponse(url=PUBLIC_REDIRECT_URL, status_code=302)
|
||||
|
||||
|
||||
@router.head("/posts/{slug}")
|
||||
def post_head(slug: str, session: Session = Depends(get_session)) -> Response:
|
||||
article = session.scalar(select(Article).where(Article.slug == slug))
|
||||
if not article or article.status != "published":
|
||||
raise HTTPException(status_code=404, detail="Article not found")
|
||||
return Response(media_type="text/html; charset=utf-8")
|
||||
def post_head(slug: str) -> RedirectResponse:
|
||||
return RedirectResponse(url=PUBLIC_REDIRECT_URL, status_code=302)
|
||||
|
||||
|
||||
@router.get("/api/dashboard")
|
||||
|
|
@ -550,6 +429,69 @@ def scan_all_sources() -> dict[str, str]:
|
|||
return {"taskId": task.id}
|
||||
|
||||
|
||||
@router.post("/api/videos/import")
|
||||
def import_video(payload: ManualVideoIn, session: Session = Depends(get_session)) -> dict[str, int | str | None]:
|
||||
source_url = payload.url.strip()
|
||||
if not source_url:
|
||||
raise HTTPException(status_code=400, detail="Вставьте ссылку на видео.")
|
||||
|
||||
command = ytdlp_base_args() + [
|
||||
"--no-playlist",
|
||||
"--dump-single-json",
|
||||
"--skip-download",
|
||||
"--no-warnings",
|
||||
source_url,
|
||||
]
|
||||
try:
|
||||
result = subprocess.run(command, text=True, capture_output=True, timeout=90, check=False)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise HTTPException(status_code=422, detail="yt-dlp не успел проверить ссылку за 90 секунд.") from exc
|
||||
if result.returncode != 0:
|
||||
details = (result.stderr or result.stdout or "Не удалось разобрать ссылку через yt-dlp").strip()
|
||||
raise HTTPException(status_code=422, detail=f"yt-dlp не смог проверить ссылку: {details[-1200:]}")
|
||||
|
||||
try:
|
||||
metadata = json.loads(result.stdout)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise HTTPException(status_code=422, detail="yt-dlp вернул некорректные метаданные для этой ссылки.") from exc
|
||||
if not isinstance(metadata, dict) or metadata.get("_type") == "playlist":
|
||||
raise HTTPException(status_code=422, detail="Нужна ссылка на отдельный ролик, а не на плейлист.")
|
||||
|
||||
external_id = str(metadata.get("id") or metadata.get("webpage_url") or source_url)
|
||||
external_id = f"manual:{hashlib.sha256(external_id.encode('utf-8')).hexdigest()}"
|
||||
existing = session.scalar(select(Video).where(Video.source_id.is_(None), Video.external_id == external_id))
|
||||
if existing:
|
||||
raise HTTPException(status_code=409, detail=f"Этот ролик уже добавлен: #{existing.id}")
|
||||
|
||||
published_at = parse_upload_date(metadata.get("upload_date"))
|
||||
duration = metadata.get("duration")
|
||||
try:
|
||||
duration = round(float(duration)) if duration is not None else None
|
||||
except (TypeError, ValueError):
|
||||
duration = None
|
||||
video = Video(
|
||||
source_id=None,
|
||||
external_id=external_id,
|
||||
source_url=source_url,
|
||||
thumbnail_url=best_thumbnail_url(metadata),
|
||||
title=str(metadata.get("title") or metadata.get("fulltitle") or "Произвольный ролик"),
|
||||
description=str(metadata.get("description") or ""),
|
||||
duration_seconds=duration,
|
||||
published_at=published_at,
|
||||
status="new",
|
||||
)
|
||||
session.add(video)
|
||||
session.commit()
|
||||
session.refresh(video)
|
||||
return {
|
||||
"id": video.id,
|
||||
"title": video.title,
|
||||
"sourceUrl": video.source_url,
|
||||
"durationSeconds": video.duration_seconds,
|
||||
"status": video.status,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/videos")
|
||||
def list_videos(session: Session = Depends(get_session)) -> list[dict]:
|
||||
videos = session.scalars(
|
||||
|
|
@ -586,23 +528,50 @@ def list_videos(session: Session = Depends(get_session)) -> list[dict]:
|
|||
|
||||
|
||||
@router.post("/api/videos/{video_id}/process")
|
||||
def process_video_route(video_id: int) -> dict[str, str]:
|
||||
def process_video_route(video_id: int, payload: VideoProcessIn | None = Body(default=None)) -> dict[str, str]:
|
||||
with SessionLocal() as session:
|
||||
video = session.get(Video, video_id)
|
||||
if not video:
|
||||
raise HTTPException(status_code=404, detail="Video not found")
|
||||
selected_chapters = [chapter.model_dump() for chapter in (payload.chapters if payload else []) or []]
|
||||
recreate_drafts = bool(payload and payload.recreateDrafts)
|
||||
if recreate_drafts:
|
||||
for article in video.articles:
|
||||
if article.status != "published":
|
||||
article.status = "rejected"
|
||||
article.published_at = None
|
||||
article.rss_guid = None
|
||||
was_active = video.status in {"queued", "processing"}
|
||||
video.status = "queued"
|
||||
video.progress_percent = 1
|
||||
video.progress_stage = "В очереди"
|
||||
action = "задача перезапущена" if was_active else "задача поставлена в обработку"
|
||||
if recreate_drafts:
|
||||
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}"
|
||||
video.error_message = None
|
||||
session.commit()
|
||||
task = process_video.delay(video_id)
|
||||
task = process_video.delay(video_id, selected_chapters or None)
|
||||
return {"taskId": task.id}
|
||||
|
||||
|
||||
@router.get("/api/videos/{video_id}/chapters")
|
||||
def video_chapters(video_id: int, session: Session = Depends(get_session)) -> dict:
|
||||
video = session.get(Video, video_id)
|
||||
if not video:
|
||||
raise HTTPException(status_code=404, detail="Video not found")
|
||||
chapters = parse_video_chapters(video.description, video.duration_seconds)
|
||||
return {
|
||||
"videoId": video.id,
|
||||
"title": video.title,
|
||||
"durationSeconds": video.duration_seconds,
|
||||
"chapters": [chapter_to_payload(chapter) for chapter in chapters],
|
||||
"canSplit": len(chapters) >= 2,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/api/videos/{video_id}")
|
||||
def ignore_video(video_id: int, session: Session = Depends(get_session)) -> dict[str, int | str]:
|
||||
video = session.get(Video, video_id)
|
||||
|
|
@ -696,6 +665,7 @@ def list_articles(
|
|||
"slug": article.slug,
|
||||
"status": article.status,
|
||||
"url": article_url(settings, article),
|
||||
"featureImageUrl": article_cover_url(session, article),
|
||||
"createdAt": article.created_at,
|
||||
"publishedAt": article.published_at,
|
||||
}
|
||||
|
|
@ -716,6 +686,7 @@ def get_article(article_id: int, session: Session = Depends(get_session), settin
|
|||
"status": article.status,
|
||||
"videoId": article.video_id,
|
||||
"url": article_url(settings, article),
|
||||
"featureImageUrl": article_cover_url(session, article),
|
||||
"createdAt": article.created_at,
|
||||
"publishedAt": article.published_at,
|
||||
"contentHtml": render_article_html(article),
|
||||
|
|
@ -733,6 +704,12 @@ def update_article(article_id: int, payload: ArticleUpdateIn, session: Session =
|
|||
body = strip_leading_duplicate_title(body, title)
|
||||
if not title:
|
||||
raise HTTPException(status_code=422, detail="Title is required")
|
||||
configured_signature = session.scalar(
|
||||
select(AppSetting.value).where(AppSetting.key == SETTING_SIGNATURE)
|
||||
) or ""
|
||||
signature_html = article.cta_html or configured_signature
|
||||
if signature_html.strip() and body.rstrip().endswith(signature_html.strip()):
|
||||
body = body[: -len(signature_html.strip())].rstrip()
|
||||
lead, body_html = split_lead_and_body(body)
|
||||
try:
|
||||
validate_article_content(title, lead, body_html)
|
||||
|
|
@ -741,6 +718,9 @@ def update_article(article_id: int, payload: ArticleUpdateIn, session: Session =
|
|||
article.title = title
|
||||
article.lead = lead
|
||||
article.body_html = body_html
|
||||
article.cta_html = signature_html.strip()
|
||||
if payload.featureImageUrl is not None:
|
||||
article.feature_image_url = payload.featureImageUrl.strip()
|
||||
session.commit()
|
||||
session.refresh(article)
|
||||
return {
|
||||
|
|
@ -750,6 +730,7 @@ def update_article(article_id: int, payload: ArticleUpdateIn, session: Session =
|
|||
"status": article.status,
|
||||
"videoId": article.video_id,
|
||||
"url": article_url(settings, article),
|
||||
"featureImageUrl": article_cover_url(session, article),
|
||||
"createdAt": article.created_at,
|
||||
"publishedAt": article.published_at,
|
||||
"contentHtml": render_article_html(article),
|
||||
|
|
|
|||
|
|
@ -114,15 +114,33 @@ def cultural_initiatives_rss_html() -> str:
|
|||
<p>#Фондкультурныхинициатив<br>#Грантдлякреативныхкоманд</p>""".strip()
|
||||
|
||||
|
||||
def strip_article_cover_html(html: str) -> str:
|
||||
return re.sub(
|
||||
r"<figure\b[^>]*class=[\"'][^\"']*\barticle-cover\b[^\"']*[\"'][^>]*>.*?</figure>",
|
||||
"",
|
||||
html or "",
|
||||
flags=re.I | re.S,
|
||||
).strip()
|
||||
|
||||
|
||||
def article_feature_image_url(article: Article) -> str:
|
||||
if article.feature_image_url:
|
||||
return article.feature_image_url
|
||||
if article.video and article.video.thumbnail_url:
|
||||
return article.video.thumbnail_url
|
||||
return ""
|
||||
|
||||
|
||||
def cover_html(article: Article, rss_safe: bool = False) -> str:
|
||||
if not article.video or not article.video.thumbnail_url:
|
||||
cover_url = article_feature_image_url(article)
|
||||
if not cover_url:
|
||||
return ""
|
||||
existing_html = "\n".join(part for part in [article.lead, article.body_html] if part)
|
||||
if "article-cover" in existing_html or article.video.thumbnail_url in existing_html:
|
||||
if cover_url in existing_html:
|
||||
return ""
|
||||
figure_class = "" if rss_safe else ' class="article-cover"'
|
||||
return (
|
||||
f'<figure{figure_class}><img src="{escape(article.video.thumbnail_url)}" alt="{escape(article.title)}">'
|
||||
f'<figure{figure_class}><img src="{escape(cover_url)}" alt="{escape(article.title)}">'
|
||||
f"<figcaption>{escape(article.title)}</figcaption></figure>"
|
||||
)
|
||||
|
||||
|
|
@ -134,6 +152,18 @@ def sanitize_rss_html(html: str) -> str:
|
|||
return html
|
||||
|
||||
|
||||
def split_audience_question_html(html: str) -> tuple[str, str]:
|
||||
match = re.search(
|
||||
r'(<p\b[^>]*class=["\'][^"\']*\baudience-question\b[^"\']*["\'][^>]*>.*?</p>)',
|
||||
html or "",
|
||||
flags=re.I | re.S,
|
||||
)
|
||||
if not match:
|
||||
return html or "", ""
|
||||
body_html = f"{html[:match.start()]}{html[match.end():]}".strip()
|
||||
return body_html, match.group(1).strip()
|
||||
|
||||
|
||||
def media_player_xml(article: Article) -> str:
|
||||
if not article.video or not article.video.source_url:
|
||||
return ""
|
||||
|
|
@ -144,15 +174,16 @@ def media_player_xml(article: Article) -> str:
|
|||
|
||||
|
||||
def render_article_html(article: Article, include_video_embed: bool = True, rss_safe: bool = False) -> str:
|
||||
premium_html = premium_cta_rss_html() if rss_safe else premium_cta_html()
|
||||
cultural_html = cultural_initiatives_rss_html() if rss_safe else cultural_initiatives_html()
|
||||
body_html = sanitize_rss_html(article.body_html) if rss_safe else article.body_html
|
||||
body_html = strip_article_cover_html(article.body_html)
|
||||
body_html, audience_question_html = split_audience_question_html(body_html)
|
||||
body_html = sanitize_rss_html(body_html) if rss_safe else body_html
|
||||
parts = [article.lead, cover_html(article, rss_safe=rss_safe), body_html]
|
||||
if is_po_suti_dela_article(article):
|
||||
parts.append(cultural_html)
|
||||
parts.append(premium_html)
|
||||
if include_video_embed:
|
||||
parts.append(video_embed_html(article, rss_safe=rss_safe))
|
||||
if audience_question_html:
|
||||
parts.append(audience_question_html)
|
||||
if article.cta_html:
|
||||
parts.append(article.cta_html)
|
||||
html = "\n".join(part for part in parts if part).strip()
|
||||
html = strip_leading_duplicate_title(html, article.title)
|
||||
return sanitize_rss_html(html) if rss_safe else html
|
||||
|
|
@ -180,7 +211,7 @@ def build_feed_xml(session: Session, settings: Settings) -> str:
|
|||
.limit(1)
|
||||
).all()
|
||||
enclosure = ""
|
||||
cover_url = article.video.thumbnail_url if article.video and article.video.thumbnail_url else ""
|
||||
cover_url = article_feature_image_url(article)
|
||||
if cover_url:
|
||||
enclosure = f'<enclosure url="{escape(cover_url)}" type="{image_mime_type(cover_url)}" />'
|
||||
elif frames and frames[0].public_url:
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ def parse_args() -> argparse.Namespace:
|
|||
parser.add_argument("--language", default="ru")
|
||||
parser.add_argument("--device", default="cpu")
|
||||
parser.add_argument("--compute-type", default="int8")
|
||||
parser.add_argument("--beam-size", type=int, default=5)
|
||||
parser.add_argument("--beam-size", type=int, default=1)
|
||||
parser.add_argument("--output", default="transcript.txt")
|
||||
return parser.parse_args()
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import json
|
|||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import time
|
||||
from html import escape, unescape
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
|
@ -11,9 +12,10 @@ import httpx
|
|||
from celery import Celery
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.chapters import seconds_to_timecode
|
||||
from app.config import get_settings
|
||||
from app.database import SessionLocal, init_db
|
||||
from app.models import Article, Frame, Source, Video
|
||||
from app.models import AppSetting, Article, Frame, Source, Video
|
||||
from app.quality import validate_article_content, validate_transcript_text
|
||||
|
||||
settings = get_settings()
|
||||
|
|
@ -59,8 +61,42 @@ ARTICLE_SYSTEM_PROMPT = """Ты редактор канала Николая С
|
|||
- не делай текст агрессивнее исходника;
|
||||
- не используй кликбейт, если он искажает смысл;
|
||||
- заголовки должны быть сильными, но честными.
|
||||
- используй только русский язык; не вставляй китайские, английские или другие иностранные фразы,
|
||||
если они не являются частью исходной цитаты.
|
||||
- используй только русский язык и кириллицу в готовой статье; не переноси латинские
|
||||
американские слова из транскрипта в результат.
|
||||
- любые англоязычные слова, бренды, военные системы и термины передавай по-русски или
|
||||
переводи: Patriot — «Патриот», Wildberries — «Вайлдберриз», inadvertently — «непреднамеренно».
|
||||
Если существует устоявшееся русское написание, используй именно его.
|
||||
- иностранные имена, должности, организации и географические названия пиши в общеупотребимом
|
||||
русском написании, если оно существует: Трамп, Байден, Ормузский пролив, Баб-эль-Мандебский пролив.
|
||||
|
||||
Обязательная редакторская переработка:
|
||||
- никогда не возвращай простую транскрибацию или слегка почищенную стенограмму;
|
||||
- текст должен быть аналитической статьей в третьем лице, а не пересказом речи от первого лица;
|
||||
- запрещены формулировки "я думаю", "мы видим", "нам нужно", "давайте разберем",
|
||||
"в этом видео", "в ролике", "транскрипт", "расшифровка";
|
||||
- запрещены местоимения и формы авторской речи от первого лица: "я", "мы", "мне", "меня",
|
||||
"нам", "нас", "наш", "наша", "наше", "наши", "посмотрим", "разберем", "перейдем";
|
||||
- если в транскрипте автор говорит от первого лица, преобразуй это в нейтральную аналитику:
|
||||
вместо "мы видим" пиши "ситуация показывает", вместо "я считаю" пиши "такая позиция исходит из...";
|
||||
- не обращайся к Николаю Старикову и не веди текст как интервью или диалог;
|
||||
- не используй автора как говорящего персонажа, если без этого можно сохранить смысл;
|
||||
- убирай повторы, оговорки, вводные слова устной речи и разговорные связки;
|
||||
- каждый раздел должен быть написан как самостоятельный аналитический фрагмент.
|
||||
|
||||
Проверка имен, географии и терминов:
|
||||
- перед финальным ответом проверь все географические названия, имена политиков,
|
||||
организаций, государств, проливов, городов и фамилий;
|
||||
- перед финальным ответом проверь должности и статусы упоминаемых персон на текущий месяц
|
||||
и год редакционной даты. Если актуальность должности не следует из транскрипта и не может
|
||||
быть надежно подтверждена, не формулируй ее как текущую: используй "на момент описываемых
|
||||
событий", "бывший", "украинский военный деятель", "политик" или другую нейтральную формулировку;
|
||||
- не называй человека действующим командующим, министром, президентом или руководителем,
|
||||
если это может быть устаревшей должностью;
|
||||
- исправляй типичные ошибки Whisper по контексту: "Армузский пролив" должен быть
|
||||
"Ормузский пролив";
|
||||
- если имя или географический термин распознаны сомнительно, выбери общеупотребимый
|
||||
русский вариант написания, который соответствует контексту;
|
||||
- не оставляй в тексте абракадабру, случайные фамилии и фонетические искажения.
|
||||
|
||||
Для каждого ролика определи, что лучше:
|
||||
1. одна цельная статья;
|
||||
|
|
@ -78,10 +114,11 @@ ARTICLE_SYSTEM_PROMPT = """Ты редактор канала Николая С
|
|||
- lead: вступление 1-2 абзаца;
|
||||
- body: основной текст с подзаголовками;
|
||||
- conclusion: финальный вывод;
|
||||
- audience_question: один конкретный вопрос по теме статьи, который побуждает читателя
|
||||
сформулировать собственную позицию и написать комментарий;
|
||||
- image_prompt: какой кадр из видео лучше использовать;
|
||||
- image_timestamp_hint: примерный таймкод из транскрипта, где искать подходящий кадр;
|
||||
- tags: 5-8 тегов;
|
||||
- premium_teaser: короткий аккуратный призыв к платным материалам или курсам;
|
||||
- source_fragments: таймкоды/фрагменты транскрипта, на которых основана статья.
|
||||
|
||||
Требования к статье:
|
||||
|
|
@ -92,6 +129,7 @@ ARTICLE_SYSTEM_PROMPT = """Ты редактор канала Николая С
|
|||
- не начинай статью словами "в данном видео";
|
||||
- не упоминай технически "транскрипт", "ролик", "расшифровка", если это не нужно по смыслу;
|
||||
- исправляй ошибки распознавания Whisper по контексту, но не меняй смысл.
|
||||
- перед ответом проверь, что статья не написана от первого лица и не выглядит как стенограмма.
|
||||
|
||||
Призыв к платным материалам:
|
||||
- размещай только в конце;
|
||||
|
|
@ -112,10 +150,10 @@ ARTICLE_SYSTEM_PROMPT = """Ты редактор канала Николая С
|
|||
"lead": "...",
|
||||
"body": "...",
|
||||
"conclusion": "...",
|
||||
"audience_question": "...",
|
||||
"image_prompt": "...",
|
||||
"image_timestamp_hint": "00:00:00",
|
||||
"tags": ["...", "..."],
|
||||
"premium_teaser": "...",
|
||||
"source_fragments": [
|
||||
{
|
||||
"start": "00:00:00",
|
||||
|
|
@ -129,10 +167,44 @@ ARTICLE_SYSTEM_PROMPT = """Ты редактор канала Николая С
|
|||
"""
|
||||
|
||||
|
||||
ENTITY_CORRECTIONS = {
|
||||
"Армузский пролив": "Ормузский пролив",
|
||||
"Армузского пролива": "Ормузского пролива",
|
||||
"Армузском проливе": "Ормузском проливе",
|
||||
"Армузским проливом": "Ормузским проливом",
|
||||
}
|
||||
|
||||
QUALITY_REWRITE_ATTEMPTS = 3
|
||||
QUALITY_ERROR_MARKERS = [
|
||||
"LLM вернул невалидный JSON",
|
||||
"Статья содержит первое лицо",
|
||||
"Статья похожа на необработанную транскрибацию",
|
||||
"Статья содержит подозрительную ошибку",
|
||||
"Статья содержит латинские/английские слова",
|
||||
"Статья слишком короткая",
|
||||
]
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def existing_text_file(path: str | Path | None) -> Path | None:
|
||||
if not path:
|
||||
return None
|
||||
candidate = Path(path)
|
||||
if not candidate.exists() or not candidate.is_file():
|
||||
return None
|
||||
text = candidate.read_text(encoding="utf-8", errors="ignore").strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
validate_transcript_text(text)
|
||||
except RuntimeError:
|
||||
return None
|
||||
return candidate
|
||||
|
||||
|
||||
def append_progress(video_id: int, percent: int | None, stage: str, message: str | None = None, status: str | None = None) -> None:
|
||||
now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
|
||||
line = f"[{now}] {stage}"
|
||||
|
|
@ -189,6 +261,25 @@ def run_logged(command: list[str], video_id: int, stage: str, cwd: Path | None =
|
|||
return "\n".join(output)
|
||||
|
||||
|
||||
def media_duration_seconds(path: Path) -> int | None:
|
||||
command = [
|
||||
"ffprobe",
|
||||
"-v",
|
||||
"error",
|
||||
"-show_entries",
|
||||
"format=duration",
|
||||
"-of",
|
||||
"default=noprint_wrappers=1:nokey=1",
|
||||
str(path),
|
||||
]
|
||||
try:
|
||||
result = run(command)
|
||||
value = result.stdout.strip()
|
||||
return max(0, round(float(value))) if value else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def command_progress_percent(stage: str, line: str) -> int | None:
|
||||
if stage == "Скачивание":
|
||||
match = re.search(r"\[download]\s+(\d+(?:\.\d+)?)%", line)
|
||||
|
|
@ -326,7 +417,7 @@ def best_thumbnail_url(item: dict) -> str:
|
|||
|
||||
|
||||
@celery_app.task(name="app.worker.process_video")
|
||||
def process_video(video_id: int) -> dict[str, int | str]:
|
||||
def process_video(video_id: int, selected_chapters: list[dict[str, Any]] | None = None) -> dict[str, int | str]:
|
||||
init_db()
|
||||
with SessionLocal() as session:
|
||||
video = session.get(Video, video_id)
|
||||
|
|
@ -343,8 +434,8 @@ def process_video(video_id: int) -> dict[str, int | str]:
|
|||
local_video = download_video(video)
|
||||
video.local_video_path = str(local_video)
|
||||
session.commit()
|
||||
append_progress(video_id, 35, "Транскрибация", "Запускаю Whisper")
|
||||
transcript = transcribe_video(local_video, video_id)
|
||||
append_progress(video_id, 35, "Транскрибация", "Проверяю сохраненную расшифровку")
|
||||
transcript = transcribe_video(local_video, video_id, video.transcript_path)
|
||||
video.transcript_path = str(transcript)
|
||||
session.commit()
|
||||
append_progress(video_id, 60, "Кадры", "Выбираю кадры-кандидаты")
|
||||
|
|
@ -352,8 +443,10 @@ def process_video(video_id: int) -> dict[str, int | str]:
|
|||
for frame in frames:
|
||||
session.add(frame)
|
||||
session.commit()
|
||||
append_progress(video_id, 75, "ИИ-редактор", "Готовлю статью по транскрипту")
|
||||
articles = build_articles(video, transcript, frames)
|
||||
chapter_count = len(selected_chapters or [])
|
||||
chapter_note = f" по выбранным главам: {chapter_count}" if chapter_count else ""
|
||||
append_progress(video_id, 75, "ИИ-редактор", f"Готовлю статьи по транскрипту{chapter_note}")
|
||||
articles = build_articles(video, transcript, frames, selected_chapters)
|
||||
for article in articles:
|
||||
session.add(article)
|
||||
video.status = "drafted"
|
||||
|
|
@ -376,6 +469,11 @@ def process_video(video_id: int) -> dict[str, int | str]:
|
|||
|
||||
|
||||
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}")
|
||||
return candidate
|
||||
target_dir = settings.videos_path / str(video.id)
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = target_dir / "video.%(ext)s"
|
||||
|
|
@ -393,20 +491,41 @@ def download_video(video: Video) -> Path:
|
|||
return files[0]
|
||||
|
||||
|
||||
def transcribe_video(video_path: Path, video_id: int) -> Path:
|
||||
def transcribe_video(video_path: Path, video_id: int, cached_path: str | None = None) -> Path:
|
||||
target_dir = settings.transcripts_path / str(video_id)
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
transcript_path = target_dir / "transcript.txt"
|
||||
|
||||
cached_transcript = existing_text_file(cached_path) or existing_text_file(transcript_path)
|
||||
if cached_transcript:
|
||||
append_progress(video_id, 60, "Транскрибация", f"Использую сохраненную расшифровку: {cached_transcript}")
|
||||
return cached_transcript
|
||||
|
||||
if not settings.whisper_command.strip():
|
||||
raise RuntimeError("WHISPER_COMMAND не настроен. Транскрибация не выполнена, статья не создана.")
|
||||
append_progress(video_id, 35, "Транскрибация", "Сохраненной расшифровки нет, запускаю Whisper")
|
||||
command_base = shlex.split(settings.whisper_command)
|
||||
if "app.whisper_cli" in command_base:
|
||||
duration = media_duration_seconds(video_path)
|
||||
if duration and duration >= settings.whisper_chunk_min_duration_seconds:
|
||||
return transcribe_video_in_chunks(video_path, video_id, transcript_path, command_base)
|
||||
command = command_base + ["--output", str(transcript_path), str(video_path)]
|
||||
cwd = Path("/app")
|
||||
else:
|
||||
command = command_base + [str(video_path)]
|
||||
cwd = target_dir
|
||||
output = run_logged(command, video_id, "Транскрибация", cwd=cwd)
|
||||
try:
|
||||
output = run_logged(command, video_id, "Транскрибация", cwd=cwd)
|
||||
except RuntimeError as exc:
|
||||
if "кодом -9" in str(exc) and "app.whisper_cli" in command_base:
|
||||
append_progress(
|
||||
video_id,
|
||||
36,
|
||||
"Транскрибация",
|
||||
"Whisper был остановлен системой, переключаюсь на покусковую расшифровку",
|
||||
)
|
||||
return transcribe_video_in_chunks(video_path, video_id, transcript_path, command_base)
|
||||
raise
|
||||
if transcript_path.exists() and transcript_path.read_text(encoding="utf-8").strip():
|
||||
validate_transcript_text(transcript_path.read_text(encoding="utf-8", errors="ignore"))
|
||||
return transcript_path
|
||||
|
|
@ -420,6 +539,58 @@ def transcribe_video(video_path: Path, video_id: int) -> Path:
|
|||
return transcript_path
|
||||
|
||||
|
||||
def transcribe_video_in_chunks(video_path: Path, video_id: int, transcript_path: Path, command_base: list[str]) -> Path:
|
||||
chunk_seconds = max(120, settings.whisper_chunk_seconds)
|
||||
chunks_dir = transcript_path.parent / "chunks"
|
||||
chunks_dir.mkdir(parents=True, exist_ok=True)
|
||||
for stale in chunks_dir.glob("*"):
|
||||
if stale.is_file():
|
||||
stale.unlink()
|
||||
append_progress(video_id, 36, "Транскрибация", f"Нарезаю аудио на фрагменты по {chunk_seconds // 60} мин.")
|
||||
split_command = [
|
||||
"ffmpeg",
|
||||
"-y",
|
||||
"-i",
|
||||
str(video_path),
|
||||
"-vn",
|
||||
"-ac",
|
||||
"1",
|
||||
"-ar",
|
||||
"16000",
|
||||
"-f",
|
||||
"segment",
|
||||
"-segment_time",
|
||||
str(chunk_seconds),
|
||||
"-reset_timestamps",
|
||||
"1",
|
||||
str(chunks_dir / "chunk-%03d.wav"),
|
||||
]
|
||||
run_logged(split_command, video_id, "Транскрибация")
|
||||
chunk_files = sorted(chunks_dir.glob("chunk-*.wav"))
|
||||
if not chunk_files:
|
||||
raise RuntimeError("Не удалось нарезать аудио для покусковой транскрибации.")
|
||||
|
||||
parts: list[str] = []
|
||||
total = len(chunk_files)
|
||||
for index, chunk_path in enumerate(chunk_files, start=1):
|
||||
chunk_output = chunks_dir / f"{chunk_path.stem}.txt"
|
||||
percent = 36 + round((index - 1) / total * 22)
|
||||
append_progress(video_id, percent, "Транскрибация", f"Распознаю фрагмент {index}/{total}")
|
||||
run_logged(command_base + ["--output", str(chunk_output), str(chunk_path)], video_id, "Транскрибация", cwd=Path("/app"))
|
||||
text = chunk_output.read_text(encoding="utf-8", errors="ignore").strip() if chunk_output.exists() else ""
|
||||
if text:
|
||||
parts.append(text)
|
||||
try:
|
||||
chunk_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
transcript_path.write_text("\n\n".join(parts).strip() + "\n", encoding="utf-8")
|
||||
validate_transcript_text(transcript_path.read_text(encoding="utf-8", errors="ignore"))
|
||||
append_progress(video_id, 60, "Транскрибация", f"Покусковая расшифровка готова: {total} фрагментов")
|
||||
return transcript_path
|
||||
|
||||
|
||||
def extract_frames(video_path: Path, video_id: int) -> list[Frame]:
|
||||
target_dir = settings.media_path / "videos" / str(video_id)
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
|
@ -456,68 +627,188 @@ def extract_frames(video_path: Path, video_id: int) -> list[Frame]:
|
|||
return frames
|
||||
|
||||
|
||||
def paragraphs(text: str, limit: int = 8) -> list[str]:
|
||||
cleaned = re.sub(r"\s+", " ", text).strip()
|
||||
sentences = re.split(r"(?<=[.!?])\s+", cleaned)
|
||||
chunks: list[str] = []
|
||||
current: list[str] = []
|
||||
for sentence in sentences:
|
||||
current.append(sentence)
|
||||
if len(" ".join(current)) > 450:
|
||||
chunks.append(" ".join(current))
|
||||
current = []
|
||||
if len(chunks) >= limit:
|
||||
break
|
||||
if current and len(chunks) < limit:
|
||||
chunks.append(" ".join(current))
|
||||
return [chunk for chunk in chunks if chunk]
|
||||
|
||||
|
||||
def build_articles(video: Video, transcript_path: Path, frames: list[Frame]) -> list[Article]:
|
||||
def build_articles(
|
||||
video: Video,
|
||||
transcript_path: Path,
|
||||
frames: list[Frame],
|
||||
selected_chapters: list[dict[str, Any]] | None = None,
|
||||
) -> list[Article]:
|
||||
transcript = transcript_path.read_text(encoding="utf-8", errors="ignore")
|
||||
validate_transcript_text(transcript)
|
||||
if settings.llm_api_url.strip() and settings.llm_api_key.strip():
|
||||
if not settings.llm_api_url.strip() or not settings.llm_api_key.strip():
|
||||
raise RuntimeError("LLM-редактор не настроен. Черновик из сырой транскрибации не создается.")
|
||||
chapters = normalize_selected_chapters(selected_chapters, video.duration_seconds)
|
||||
if not chapters:
|
||||
articles = generate_articles_with_quality_retries(video, transcript, frames)
|
||||
if not articles:
|
||||
raise RuntimeError("LLM-редактор не вернул пригодную статью. Черновик не создан.")
|
||||
return articles
|
||||
|
||||
articles: list[Article] = []
|
||||
for index, chapter in enumerate(chapters, start=1):
|
||||
append_progress(
|
||||
video.id,
|
||||
min(95, 75 + int(index / max(1, len(chapters)) * 18)),
|
||||
"ИИ-редактор",
|
||||
f"Готовлю статью {index}/{len(chapters)}: {chapter['title']}",
|
||||
)
|
||||
chapter_transcript = transcript_slice_by_time(
|
||||
transcript,
|
||||
chapter["startSeconds"],
|
||||
chapter.get("endSeconds"),
|
||||
video.duration_seconds,
|
||||
)
|
||||
chapter_frames = frames_for_chapter(frames, chapter["startSeconds"], chapter.get("endSeconds"))
|
||||
chapter_articles = generate_articles_with_quality_retries(
|
||||
video,
|
||||
chapter_transcript,
|
||||
chapter_frames or frames,
|
||||
chapter=chapter,
|
||||
)
|
||||
if not chapter_articles:
|
||||
raise RuntimeError(f"LLM-редактор не вернул пригодную статью для главы «{chapter['title']}».")
|
||||
for article in chapter_articles[:1]:
|
||||
article.slug = f"{datetime.now(timezone.utc).strftime('%Y%m%d')}-{video.id}-ch{index}-{slugify(article.title)}"
|
||||
articles.append(article)
|
||||
if not articles:
|
||||
raise RuntimeError("LLM-редактор не вернул пригодные статьи по выбранным главам. Черновики не созданы.")
|
||||
return articles
|
||||
|
||||
|
||||
def generate_articles_with_quality_retries(
|
||||
video: Video,
|
||||
transcript: str,
|
||||
frames: list[Frame],
|
||||
chapter: dict[str, Any] | None = None,
|
||||
) -> list[Article]:
|
||||
feedback = ""
|
||||
for attempt in range(1, QUALITY_REWRITE_ATTEMPTS + 1):
|
||||
if attempt > 1:
|
||||
append_progress(
|
||||
video.id,
|
||||
None,
|
||||
"ИИ-редактор",
|
||||
f"Повторная редактура {attempt}/{QUALITY_REWRITE_ATTEMPTS}: {feedback}",
|
||||
)
|
||||
payload = generate_article_payload(video, transcript, chapter=chapter, quality_feedback=feedback)
|
||||
try:
|
||||
payload = generate_article_payload(video, transcript)
|
||||
articles = articles_from_payload(video, payload, frames)
|
||||
if articles:
|
||||
return articles
|
||||
except Exception as exc:
|
||||
print(f"LLM article generation failed for video {video.id}: {exc}")
|
||||
return [fallback_article(video, transcript, frames)]
|
||||
except (RuntimeError, json.JSONDecodeError) as exc:
|
||||
message = str(exc)
|
||||
if isinstance(exc, json.JSONDecodeError):
|
||||
message = f"LLM вернул невалидный JSON: {exc.msg} в строке {exc.lineno}, колонке {exc.colno}."
|
||||
if is_quality_error(message) and attempt < QUALITY_REWRITE_ATTEMPTS:
|
||||
feedback = message
|
||||
continue
|
||||
if "Статья содержит первое лицо" in message or "Статья похожа на необработанную транскрибацию" in message:
|
||||
append_progress(
|
||||
video.id,
|
||||
None,
|
||||
"ИИ-редактор",
|
||||
f"Локальная редактура после ответа LLM: {message}",
|
||||
)
|
||||
articles = articles_from_payload(video, neutralize_payload_first_person(payload), frames)
|
||||
if articles:
|
||||
return articles
|
||||
raise
|
||||
if articles:
|
||||
return articles
|
||||
feedback = "В ответе нет массива articles с пригодными статьями."
|
||||
return []
|
||||
|
||||
|
||||
def fallback_article(video: Video, transcript: str, frames: list[Frame]) -> Article:
|
||||
title = video.title.strip() or "Новый разбор Николая Старикова"
|
||||
slug = f"{datetime.now(timezone.utc).strftime('%Y%m%d')}-{video.id}-{slugify(title)}"
|
||||
lead = ""
|
||||
cover_html = cover_figure_html(video, title)
|
||||
body_parts: list[str] = []
|
||||
frame_index = 0
|
||||
for index, chunk in enumerate(paragraphs(transcript), start=1):
|
||||
if index > 1 and frame_index < len(frames):
|
||||
body_parts.append(frame_figure_html(frames[frame_index], title))
|
||||
frame_index += 1
|
||||
body_parts.append(f"<p>{escape(chunk)}</p>")
|
||||
body = "\n".join(part for part in [cover_html, *body_parts] if part)
|
||||
article = Article(
|
||||
video_id=video.id,
|
||||
slug=slug,
|
||||
title=title,
|
||||
lead=lead,
|
||||
body_html=body.strip(),
|
||||
cta_html="",
|
||||
status="draft",
|
||||
)
|
||||
validate_article_content(article.title, article.lead, article.body_html)
|
||||
return article
|
||||
def is_quality_error(message: str) -> bool:
|
||||
return any(marker in message for marker in QUALITY_ERROR_MARKERS)
|
||||
|
||||
|
||||
def generate_article_payload(video: Video, transcript: str) -> dict[str, Any]:
|
||||
def normalize_selected_chapters(chapters: list[dict[str, Any]] | None, duration_seconds: int | None) -> list[dict[str, Any]]:
|
||||
normalized: list[dict[str, Any]] = []
|
||||
for item in chapters or []:
|
||||
try:
|
||||
start = max(0, int(item.get("startSeconds") or 0))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
try:
|
||||
end = int(item["endSeconds"]) if item.get("endSeconds") is not None else duration_seconds
|
||||
except (TypeError, ValueError):
|
||||
end = duration_seconds
|
||||
if end is not None:
|
||||
end = max(start + 1, end)
|
||||
if duration_seconds:
|
||||
end = min(duration_seconds, end)
|
||||
title = clean_generated_text(str(item.get("title") or "")).strip() or f"Эпизод с {seconds_to_timecode(start)}"
|
||||
normalized.append(
|
||||
{
|
||||
"id": str(item.get("id") or f"{len(normalized) + 1}-{start}"),
|
||||
"title": title,
|
||||
"startSeconds": start,
|
||||
"endSeconds": end,
|
||||
}
|
||||
)
|
||||
return sorted(normalized, key=lambda chapter: chapter["startSeconds"])
|
||||
|
||||
|
||||
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
|
||||
cleaned = transcript.strip()
|
||||
if not cleaned:
|
||||
return cleaned
|
||||
end = min(duration_seconds, end_seconds or duration_seconds)
|
||||
start_ratio = max(0, min(1, start_seconds / duration_seconds))
|
||||
end_ratio = max(start_ratio, min(1, end / duration_seconds))
|
||||
start_index = int(len(cleaned) * start_ratio)
|
||||
end_index = int(len(cleaned) * end_ratio)
|
||||
start_index = cleaned.rfind("\n", 0, start_index) + 1 if "\n" in cleaned[:start_index] else start_index
|
||||
next_newline = cleaned.find("\n", end_index)
|
||||
if next_newline != -1:
|
||||
end_index = next_newline
|
||||
fragment = cleaned[start_index:end_index].strip()
|
||||
return fragment if len(fragment) >= 500 else cleaned
|
||||
|
||||
|
||||
def frames_for_chapter(frames: list[Frame], start_seconds: int, end_seconds: int | None) -> list[Frame]:
|
||||
return [
|
||||
frame
|
||||
for frame in frames
|
||||
if frame.timestamp_seconds >= start_seconds and (end_seconds is None or frame.timestamp_seconds < end_seconds)
|
||||
]
|
||||
|
||||
|
||||
def generate_article_payload(
|
||||
video: Video,
|
||||
transcript: str,
|
||||
chapter: dict[str, Any] | None = None,
|
||||
quality_feedback: str = "",
|
||||
) -> dict[str, Any]:
|
||||
transcript = transcript.strip()
|
||||
if len(transcript) > settings.llm_max_transcript_chars:
|
||||
transcript = transcript[: settings.llm_max_transcript_chars] + "\n\n[Транскрипт обрезан по лимиту контекста.]"
|
||||
editorial_plan = article_count_instruction(video)
|
||||
editorial_plan = chapter_article_instruction(chapter) if chapter else article_count_instruction(video)
|
||||
chapter_context = ""
|
||||
if chapter:
|
||||
end = chapter.get("endSeconds")
|
||||
chapter_context = f"""
|
||||
Выбранный эпизод:
|
||||
{seconds_to_timecode(chapter["startSeconds"])}{f"—{seconds_to_timecode(end)}" if end is not None else ""} — {chapter["title"]}
|
||||
"""
|
||||
rewrite_context = ""
|
||||
if quality_feedback:
|
||||
json_feedback = "невалидный JSON" in quality_feedback.lower()
|
||||
rewrite_context = f"""
|
||||
Предыдущая попытка была отклонена автоматической проверкой качества:
|
||||
{quality_feedback}
|
||||
|
||||
{"Предыдущий ответ невозможно разобрать программно. Верни только один валидный JSON-объект без Markdown, пояснений, комментариев, лишних запятых и незакрытых кавычек. Все переносы строк внутри строк экранируй как \\n." if json_feedback else ""}
|
||||
|
||||
Перепиши материал заново. Не пытайся точечно заменить одно слово: полностью убери первое лицо,
|
||||
разговорную подачу, обращения к зрителю, следы стенограммы и сомнительные имена/географию.
|
||||
Запрещены местоимения и формы авторской речи: «я», «мы», «мне», «нам», «наш», «давайте»,
|
||||
«посмотрим», «разберем», «я думаю», «я считаю». Текст должен звучать как готовая
|
||||
редакторская аналитическая статья в третьем лице.
|
||||
Если проверка указала сомнительную должность или имя, перепроверь актуальность на редакционную дату
|
||||
и используй осторожную формулировку без устаревшей текущей должности.
|
||||
"""
|
||||
user_prompt = f"""Название ролика:
|
||||
{video.title}
|
||||
|
||||
|
|
@ -530,8 +821,13 @@ def generate_article_payload(video: Video, transcript: str) -> dict[str, Any]:
|
|||
Длительность ролика:
|
||||
{format_video_duration(video.duration_seconds)}
|
||||
|
||||
Редакционная дата:
|
||||
{current_editorial_date_ru()}
|
||||
|
||||
Редакционный план:
|
||||
{editorial_plan}
|
||||
{chapter_context}
|
||||
{rewrite_context}
|
||||
|
||||
Транскрипт:
|
||||
{transcript}
|
||||
|
|
@ -542,6 +838,35 @@ def generate_article_payload(video: Video, transcript: str) -> dict[str, Any]:
|
|||
return parse_llm_json(response_text)
|
||||
|
||||
|
||||
def current_editorial_date_ru() -> str:
|
||||
months = [
|
||||
"январь",
|
||||
"февраль",
|
||||
"март",
|
||||
"апрель",
|
||||
"май",
|
||||
"июнь",
|
||||
"июль",
|
||||
"август",
|
||||
"сентябрь",
|
||||
"октябрь",
|
||||
"ноябрь",
|
||||
"декабрь",
|
||||
]
|
||||
now = datetime.now(timezone.utc)
|
||||
return f"{months[now.month - 1]} {now.year} года"
|
||||
|
||||
|
||||
def chapter_article_instruction(chapter: dict[str, Any]) -> str:
|
||||
title = chapter["title"]
|
||||
return (
|
||||
"Сделай ровно одну самостоятельную статью только по выбранному эпизоду. "
|
||||
f"Тема эпизода: «{title}». Не пересказывай весь выпуск и не добавляй соседние темы, "
|
||||
"если они не нужны для контекста. Заголовок статьи должен отражать именно эту тему. "
|
||||
"Финальный embed полного исходного видео будет добавлен автоматически."
|
||||
)
|
||||
|
||||
|
||||
def format_video_duration(seconds: int | None) -> str:
|
||||
if not seconds:
|
||||
return "неизвестна"
|
||||
|
|
@ -559,7 +884,7 @@ def article_count_instruction(video: Video) -> str:
|
|||
"Сделай 4 самостоятельные статьи. Раздели выпуск на 4 крупных смысловых блока, "
|
||||
"не дроби одну тему искусственно, но не объединяй разные темы в одну статью. "
|
||||
"У каждой статьи должны быть свой заголовок, свой lead, свои подзаголовки и законченный вывод. "
|
||||
"В конце каждой статьи будет автоматически добавлен один и тот же embed исходного видео и блок Дзен Премиум."
|
||||
"В конце каждой статьи будет автоматически добавлен один и тот же embed исходного видео."
|
||||
)
|
||||
if seconds >= 18 * 60 or is_program_episode:
|
||||
return (
|
||||
|
|
@ -575,19 +900,59 @@ def call_llm(user_prompt: str) -> str:
|
|||
"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"
|
||||
"---"
|
||||
)
|
||||
payload = {
|
||||
"model": settings.llm_model,
|
||||
"messages": [
|
||||
{"role": "system", "content": ARTICLE_SYSTEM_PROMPT},
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
"temperature": 0.35,
|
||||
"temperature": 0.15,
|
||||
}
|
||||
last_error = ""
|
||||
attempts = max(1, settings.llm_retry_attempts)
|
||||
with httpx.Client(timeout=settings.llm_timeout_seconds) as client:
|
||||
response = client.post(url, headers=headers, json=payload)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return data["choices"][0]["message"]["content"]
|
||||
for attempt in range(1, attempts + 1):
|
||||
try:
|
||||
response = client.post(url, headers=headers, json=payload)
|
||||
if response.status_code >= 500:
|
||||
last_error = response.text[:1000]
|
||||
if attempt < attempts:
|
||||
time.sleep(2 * attempt)
|
||||
continue
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return data["choices"][0]["message"]["content"]
|
||||
except (httpx.TimeoutException, httpx.TransportError) as exc:
|
||||
last_error = str(exc)
|
||||
if attempt < attempts:
|
||||
time.sleep(2 * attempt)
|
||||
continue
|
||||
raise RuntimeError(f"LLM-редактор временно недоступен после {attempts} попыток: {last_error}") from exc
|
||||
except httpx.HTTPStatusError as exc:
|
||||
status_code = exc.response.status_code
|
||||
detail = exc.response.text[:1000]
|
||||
if status_code >= 500:
|
||||
raise RuntimeError(
|
||||
f"Timeweb LLM вернул {status_code} после {attempts} попыток. "
|
||||
"Это внутренняя ошибка сервиса агента; попробуйте повторить обработку позже. "
|
||||
f"Ответ сервиса: {detail}"
|
||||
) from exc
|
||||
raise RuntimeError(f"LLM-редактор отклонил запрос с кодом {status_code}: {detail}") from exc
|
||||
raise RuntimeError(f"LLM-редактор не вернул ответ после {attempts} попыток: {last_error}")
|
||||
|
||||
|
||||
def parse_llm_json(text: str) -> dict[str, Any]:
|
||||
|
|
@ -597,11 +962,79 @@ def parse_llm_json(text: str) -> dict[str, Any]:
|
|||
cleaned = re.sub(r"\s*```$", "", cleaned)
|
||||
try:
|
||||
return json.loads(cleaned)
|
||||
except json.JSONDecodeError:
|
||||
except json.JSONDecodeError as original_error:
|
||||
match = re.search(r"\{.*\}", cleaned, flags=re.S)
|
||||
if not match:
|
||||
raise
|
||||
return json.loads(match.group(0))
|
||||
raise original_error
|
||||
candidate = match.group(0)
|
||||
try:
|
||||
return json.loads(candidate)
|
||||
except json.JSONDecodeError:
|
||||
repaired = repair_llm_json(candidate)
|
||||
try:
|
||||
return json.loads(repaired)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise RuntimeError(
|
||||
f"LLM вернул невалидный JSON: {exc.msg} в строке {exc.lineno}, колонке {exc.colno}."
|
||||
) from exc
|
||||
|
||||
|
||||
def repair_llm_json(value: str) -> str:
|
||||
"""Repair common LLM JSON mistakes without changing JSON structure or text semantics."""
|
||||
output: list[str] = []
|
||||
in_string = False
|
||||
escaped = False
|
||||
for index, char in enumerate(value):
|
||||
if escaped:
|
||||
if in_string and char not in '"\\/bfnrtu':
|
||||
output.append("\\")
|
||||
output.append(char)
|
||||
escaped = False
|
||||
continue
|
||||
if char == "\\":
|
||||
output.append(char)
|
||||
escaped = True
|
||||
continue
|
||||
if char == '"':
|
||||
if not in_string:
|
||||
in_string = True
|
||||
output.append(char)
|
||||
continue
|
||||
next_index = index + 1
|
||||
while next_index < len(value) and value[next_index].isspace():
|
||||
next_index += 1
|
||||
next_char = value[next_index] if next_index < len(value) else ""
|
||||
if is_json_string_boundary(value, next_index):
|
||||
in_string = False
|
||||
output.append(char)
|
||||
else:
|
||||
output.append('\\"')
|
||||
continue
|
||||
if in_string and char == "\n":
|
||||
output.append("\\n")
|
||||
continue
|
||||
if in_string and char == "\r":
|
||||
output.append("\\r")
|
||||
continue
|
||||
if in_string and ord(char) < 0x20:
|
||||
output.append(f"\\u{ord(char):04x}")
|
||||
continue
|
||||
output.append(char)
|
||||
return "".join(output)
|
||||
|
||||
|
||||
def is_json_string_boundary(value: str, index: int) -> bool:
|
||||
next_char = value[index] if index < len(value) else ""
|
||||
if next_char in "}]:":
|
||||
return True
|
||||
if next_char != ",":
|
||||
return False
|
||||
next_index = index + 1
|
||||
while next_index < len(value) and value[next_index].isspace():
|
||||
next_index += 1
|
||||
if next_index >= len(value):
|
||||
return True
|
||||
return value[next_index] in '"}]'
|
||||
|
||||
|
||||
def articles_from_payload(video: Video, payload: dict[str, Any], frames: list[Frame]) -> list[Article]:
|
||||
|
|
@ -628,31 +1061,95 @@ def articles_from_payload(video: Video, payload: dict[str, Any], frames: list[Fr
|
|||
lead=lead,
|
||||
body_html=body_html,
|
||||
cta_html="",
|
||||
feature_image_url=video.thumbnail_url or "",
|
||||
status="draft",
|
||||
)
|
||||
)
|
||||
return articles
|
||||
|
||||
|
||||
def neutralize_payload_first_person(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
cloned = json.loads(json.dumps(payload, ensure_ascii=False))
|
||||
raw_articles = cloned.get("articles")
|
||||
if not isinstance(raw_articles, list):
|
||||
return cloned
|
||||
for item in raw_articles:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
for key in ["title", "subtitle", "lead", "body", "conclusion", "premium_teaser"]:
|
||||
if isinstance(item.get(key), str):
|
||||
item[key] = neutralize_first_person_text(item[key])
|
||||
return cloned
|
||||
|
||||
|
||||
def neutralize_first_person_text(text: str) -> str:
|
||||
replacements = [
|
||||
(r"\bмы\s+видим\b", "ситуация показывает"),
|
||||
(r"\bмы\s+наблюдаем\b", "наблюдается"),
|
||||
(r"\bмы\s+понимаем\b", "становится понятно"),
|
||||
(r"\bмы\s+получаем\b", "возникает"),
|
||||
(r"\bмы\s+имеем\b", "возникает"),
|
||||
(r"\bмы\s+говорим\b", "речь идет"),
|
||||
(r"\bмы\s+говорили\b", "ранее отмечалось"),
|
||||
(r"\bмы\s+уже\s+говорили\b", "ранее отмечалось"),
|
||||
(r"\bдавайте\s+разбер[её]м\b", "важно рассмотреть"),
|
||||
(r"\bдавайте\s+посмотрим\b", "важно посмотреть"),
|
||||
(r"\bпосмотрим\b", "следует посмотреть"),
|
||||
(r"\bразбер[её]м\b", "следует разобрать"),
|
||||
(r"\bперейд[её]м\b", "следует перейти"),
|
||||
(r"\bя\s+думаю\b", "можно предположить"),
|
||||
(r"\bя\s+считаю\b", "такая позиция исходит из того"),
|
||||
(r"\bмне\s+кажется\b", "можно предположить"),
|
||||
(r"\bсегодня\s+я\s+расскажу\b", "далее рассматривается"),
|
||||
(r"\bдумаю\b", "можно предположить"),
|
||||
(r"\bсчитаю\b", "такая позиция исходит из того"),
|
||||
(r"\bскажу\b", "следует отметить"),
|
||||
(r"\bрасскажу\b", "далее рассматривается"),
|
||||
(r"\bпокажу\b", "далее показано"),
|
||||
(r"\bобъясню\b", "далее объясняется"),
|
||||
(r"\bнаш(а|е|и)?\s+страна\b", "Россия"),
|
||||
(r"\bнашей\s+страны\b", "России"),
|
||||
(r"\bнашей\s+стране\b", "России"),
|
||||
(r"\bнашу\s+страну\b", "Россию"),
|
||||
(r"\bнашим\s+государством\b", "Россией"),
|
||||
(r"\bнаше\s+государство\b", "Россия"),
|
||||
]
|
||||
cleaned = text
|
||||
for pattern, replacement in replacements:
|
||||
cleaned = re.sub(pattern, replacement, cleaned, flags=re.I)
|
||||
cleaned = re.sub(r"\bмы\b", "эксперты", cleaned, flags=re.I)
|
||||
cleaned = re.sub(r"\bнам\b", "обществу", cleaned, flags=re.I)
|
||||
cleaned = re.sub(r"\bнас\b", "общество", cleaned, flags=re.I)
|
||||
cleaned = re.sub(r"\bнами\b", "обществом", cleaned, flags=re.I)
|
||||
cleaned = re.sub(r"\bмне\b", "автору позиции", cleaned, flags=re.I)
|
||||
cleaned = re.sub(r"\bменя\b", "автора позиции", cleaned, flags=re.I)
|
||||
cleaned = re.sub(r"\bмной\b", "автором позиции", cleaned, flags=re.I)
|
||||
cleaned = re.sub(r"\bя\b", "автор позиции", cleaned, flags=re.I)
|
||||
cleaned = re.sub(r"\bнаш\b", "российский", cleaned, flags=re.I)
|
||||
cleaned = re.sub(r"\bнаша\b", "российская", cleaned, flags=re.I)
|
||||
cleaned = re.sub(r"\bнаше\b", "российское", cleaned, flags=re.I)
|
||||
cleaned = re.sub(r"\bнаши\b", "российские", cleaned, flags=re.I)
|
||||
return clean_generated_text(cleaned)
|
||||
|
||||
|
||||
def article_body_html(item: dict[str, Any], frames: list[Frame], title: str, video: Video) -> str:
|
||||
cover_html = cover_figure_html(video, title)
|
||||
body_html = generated_content_to_html(str(item.get("body") or ""))
|
||||
body_html = inject_section_frames(body_html, frames, title)
|
||||
parts = [
|
||||
cover_html,
|
||||
body_html,
|
||||
generated_content_to_html(str(item.get("conclusion") or "")),
|
||||
audience_question_html(item, title),
|
||||
]
|
||||
return "\n".join(part for part in parts if part).strip()
|
||||
|
||||
|
||||
def cover_figure_html(video: Video, title: str) -> str:
|
||||
if not video.thumbnail_url:
|
||||
return ""
|
||||
return (
|
||||
f'<figure class="article-cover"><img src="{escape(video.thumbnail_url)}" alt="{escape(title)}">'
|
||||
f"<figcaption>{escape(title)}</figcaption></figure>"
|
||||
)
|
||||
def audience_question_html(item: dict[str, Any], title: str) -> str:
|
||||
question = clean_generated_text(str(item.get("audience_question") or "")).strip()
|
||||
if not question:
|
||||
question = f"Как вы оцениваете основные выводы статьи «{title}»?"
|
||||
if not question.endswith(("?", "?")):
|
||||
question = f"{question.rstrip('.!')}?"
|
||||
return f'<p class="audience-question"><strong>Ваше мнение:</strong> {escape(question)} Пишите своё мнение в комментариях.</p>'
|
||||
|
||||
|
||||
def frame_figure_html(frame: Frame, title: str, caption: str | None = None) -> str:
|
||||
|
|
@ -706,6 +1203,8 @@ def clean_generated_text(text: str) -> str:
|
|||
}
|
||||
for source, replacement in replacements.items():
|
||||
text = text.replace(source, replacement)
|
||||
for source, replacement in ENTITY_CORRECTIONS.items():
|
||||
text = re.sub(re.escape(source), replacement, text, flags=re.I)
|
||||
text = re.sub(r"[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]+", "", text)
|
||||
text = re.sub(r"[ \t]{2,}", " ", text)
|
||||
text = text.replace("спровоцировав новый виток обсуждение", "спровоцировав новый виток обсуждения")
|
||||
|
|
|
|||
1
dzen-assistant/requirements-yt-dlp.txt
Normal file
1
dzen-assistant/requirements-yt-dlp.txt
Normal file
|
|
@ -0,0 +1 @@
|
|||
yt-dlp==2026.7.4
|
||||
Loading…
Reference in a new issue