dzen.nstarikov.ru/dzen-assistant/app/worker.py

1377 lines
64 KiB
Python
Raw Normal View History

import asyncio
2026-06-27 14:07:10 +03:00
import json
import re
import shlex
import subprocess
import time
2026-06-27 14:07:10 +03:00
from html import escape, unescape
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import httpx
from celery import Celery
from sqlalchemy import select
from app.chapters import seconds_to_timecode
2026-06-27 14:07:10 +03:00
from app.config import get_settings
from app.database import SessionLocal, init_db
from app.models import AppSetting, Article, Frame, Source, Video
from app.models import ImageGenerationBatch, ImageGenerationJob
from app.image_generation import ImageGenerationError, PolzaClient, error_from_status, extract_result_url, save_remote_image
2026-06-27 14:07:10 +03:00
from app.quality import validate_article_content, validate_transcript_text
2026-08-14 18:09:05 +03:00
from app.rss import VIDEO_PLACEHOLDER, split_audience_question_html
2026-06-27 14:07:10 +03:00
settings = get_settings()
celery_app = Celery(
"dzen_assistant",
broker=settings.celery_broker_url,
backend=settings.celery_result_backend,
)
celery_app.conf.beat_schedule = {
"scan-sources-every-hour": {
"task": "app.worker.scan_sources",
"schedule": 3600.0,
},
}
IMAGE_TOKEN_SETTING = "image_api_token"
def refresh_image_batch_status(session, batch: ImageGenerationBatch) -> None:
states = [job.status for job in batch.jobs]
if any(state in {"queued", "requesting", "generating", "downloading"} for state in states):
batch.status = "running" if any(state != "queued" for state in states) else "queued"
elif states and all(state == "ready" for state in states):
batch.status = "completed"
elif any(state == "ready" for state in states):
batch.status = "completed_with_errors"
else:
batch.status = "failed"
@celery_app.task(name="app.worker.generate_article_image")
def generate_article_image(job_id: str) -> None:
"""Generate one image. Never log prompt, token, or raw provider payload."""
init_db()
with SessionLocal() as session:
job = session.get(ImageGenerationJob, job_id)
if not job or job.status not in {"queued", "requesting"}:
return
token = session.scalar(select(AppSetting.value).where(AppSetting.key == IMAGE_TOKEN_SETTING)) or ""
if not token.strip():
job.status, job.stage, job.error_code, job.error_message = "failed", "Ошибка", "token_missing", "Не задан токен Polza."
refresh_image_batch_status(session, job.batch)
session.commit()
return
job.status, job.progress, job.stage = "requesting", 5, "Отправляем запрос"
refresh_image_batch_status(session, job.batch)
session.commit()
api_url, model, prompt, article_id, target = job.api_url, job.model, job.prompt, job.article_id, job.target
try:
client = PolzaClient(api_url, token)
image_url: str | None = None
generation_id = asyncio.run(client.create(model, prompt))
for _ in range(120):
with SessionLocal() as session:
job = session.get(ImageGenerationJob, job_id)
if not job:
return
job.status, job.progress, job.stage = "generating", max(job.progress, 20), "Генерируем изображение"
refresh_image_batch_status(session, job.batch)
session.commit()
result = asyncio.run(client.status(generation_id))
provider_status = str(result.get("status") or (result.get("data") or {}).get("status") or "").lower()
image_url = extract_result_url(result)
if image_url:
break
if provider_status in {"failed", "error", "cancelled", "canceled"}:
raise error_from_status(result)
time.sleep(3)
if image_url is None:
raise ImageGenerationError("provider_timeout", "Polza не успела создать изображение.")
with SessionLocal() as session:
job = session.get(ImageGenerationJob, job_id)
if not job:
return
job.status, job.progress, job.stage = "downloading", 85, "Сохраняем изображение"
refresh_image_batch_status(session, job.batch)
session.commit()
local_url = save_remote_image(image_url, settings.media_path, settings.public_base_url, article_id, target)
with SessionLocal() as session:
job = session.get(ImageGenerationJob, job_id)
if not job:
return
job.status, job.progress, job.stage, job.local_url = "ready", 100, "Готово", local_url
refresh_image_batch_status(session, job.batch)
session.commit()
except ImageGenerationError as exc:
with SessionLocal() as session:
job = session.get(ImageGenerationJob, job_id)
if job:
job.status, job.stage, job.error_code, job.error_message = "failed", "Ошибка", exc.code, exc.message
refresh_image_batch_status(session, job.batch)
session.commit()
except Exception:
with SessionLocal() as session:
job = session.get(ImageGenerationJob, job_id)
if job:
job.status, job.stage, job.error_code, job.error_message = "failed", "Ошибка", "provider_error", "Не удалось создать изображение."
refresh_image_batch_status(session, job.batch)
session.commit()
2026-06-27 14:07:10 +03:00
def slugify(text: str) -> str:
translit = {
"а": "a", "б": "b", "в": "v", "г": "g", "д": "d", "е": "e", "ё": "e",
"ж": "zh", "з": "z", "и": "i", "й": "y", "к": "k", "л": "l", "м": "m",
"н": "n", "о": "o", "п": "p", "р": "r", "с": "s", "т": "t", "у": "u",
"ф": "f", "х": "h", "ц": "c", "ч": "ch", "ш": "sh", "щ": "sch",
"ъ": "", "ы": "y", "ь": "", "э": "e", "ю": "yu", "я": "ya",
}
normalized = "".join(translit.get(ch, ch) for ch in text.lower())
normalized = re.sub(r"[^a-z0-9]+", "-", normalized).strip("-")
return normalized[:120] or "material"
ARTICLE_SYSTEM_PROMPT = """Ты редактор канала Николая Старикова в Дзене.
Твоя задача: превращать расшифровки видеороликов в качественные статьи для Яндекс.Дзена.
Работай только с предоставленным транскриптом и метаданными. Не добавляй факты, которых нет
в исходном тексте. Не выдумывай цитаты, даты, имена, цифры и события.
Стиль:
- публицистический, ясный, уверенный;
- без чрезмерной академичности;
- без разговорных оговорок, повторов и мусора устной речи;
- сохраняй позицию и смысл автора;
- не делай текст агрессивнее исходника;
- не используй кликбейт, если он искажает смысл;
- заголовки должны быть сильными, но честными.
- используй только русский язык и кириллицу в готовой статье; не переноси латинские
американские слова из транскрипта в результат.
- любые англоязычные слова, бренды, военные системы и термины передавай по-русски или
переводи: Patriot — «Патриот», Wildberries — «Вайлдберриз», inadvertently — «непреднамеренно».
Если существует устоявшееся русское написание, используй именно его.
- иностранные имена, должности, организации и географические названия пиши в общеупотребимом
русском написании, если оно существует: Трамп, Байден, Ормузский пролив, Баб-эль-Мандебский пролив.
Обязательная редакторская переработка:
- никогда не возвращай простую транскрибацию или слегка почищенную стенограмму;
- текст должен быть аналитической статьей в третьем лице, а не пересказом речи от первого лица;
- запрещены формулировки "я думаю", "мы видим", "нам нужно", "давайте разберем",
"в этом видео", "в ролике", "транскрипт", "расшифровка";
- запрещены местоимения и формы авторской речи от первого лица: "я", "мы", "мне", "меня",
"нам", "нас", "наш", "наша", "наше", "наши", "посмотрим", "разберем", "перейдем";
- если в транскрипте автор говорит от первого лица, преобразуй это в нейтральную аналитику:
вместо "мы видим" пиши "ситуация показывает", вместо "я считаю" пиши "такая позиция исходит из...";
- не обращайся к Николаю Старикову и не веди текст как интервью или диалог;
- не используй автора как говорящего персонажа, если без этого можно сохранить смысл;
- убирай повторы, оговорки, вводные слова устной речи и разговорные связки;
- каждый раздел должен быть написан как самостоятельный аналитический фрагмент.
Проверка имен, географии и терминов:
- перед финальным ответом проверь все географические названия, имена политиков,
организаций, государств, проливов, городов и фамилий;
- перед финальным ответом проверь должности и статусы упоминаемых персон на текущий месяц
и год редакционной даты. Если актуальность должности не следует из транскрипта и не может
быть надежно подтверждена, не формулируй ее как текущую: используй "на момент описываемых
событий", "бывший", "украинский военный деятель", "политик" или другую нейтральную формулировку;
- не называй человека действующим командующим, министром, президентом или руководителем,
если это может быть устаревшей должностью;
- исправляй типичные ошибки Whisper по контексту: "Армузский пролив" должен быть
"Ормузский пролив";
- если имя или географический термин распознаны сомнительно, выбери общеупотребимый
русский вариант написания, который соответствует контексту;
- не оставляй в тексте абракадабру, случайные фамилии и фонетические искажения.
2026-06-27 14:07:10 +03:00
Для каждого ролика определи, что лучше:
1. одна цельная статья;
2. несколько самостоятельных статей, если в ролике есть несколько разных тем.
Если ролик длинный и содержит несколько тем, раздели его на 2-4 статьи. Если в пользовательском
задании указано целевое количество статей, строго ориентируйся на него. Для выпусков программы
«По сути дела» длительностью 30-40 минут обычно нужно сделать 4 статьи: по одной на каждый
крупный смысловой блок выпуска. Каждая статья должна быть самостоятельной, с отдельным
заголовком и законченной мыслью.
Для каждой статьи сделай:
- title: короткий сильный заголовок до 90 символов;
- subtitle: поясняющий подзаголовок до 160 символов;
- lead: вступление 1-2 абзаца;
- body: основной текст с подзаголовками;
- conclusion: финальный вывод;
- audience_question: один конкретный вопрос по теме статьи, который побуждает читателя
сформулировать собственную позицию и написать комментарий;
2026-06-27 14:07:10 +03:00
- image_prompt: какой кадр из видео лучше использовать;
- image_timestamp_hint: примерный таймкод из транскрипта, где искать подходящий кадр;
- tags: 5-8 тегов;
- source_fragments: таймкоды/фрагменты транскрипта, на которых основана статья.
Требования к статье:
- объем обычной статьи: 3500-7000 знаков;
- если тема маленькая, не раздувай искусственно;
- если тема большая, дели на несколько статей;
- каждый абзац должен быть удобен для чтения в Дзене;
- не начинай статью словами "в данном видео";
- не упоминай технически "транскрипт", "ролик", "расшифровка", если это не нужно по смыслу;
- исправляй ошибки распознавания Whisper по контексту, но не меняй смысл.
- перед ответом проверь, что статья не написана от первого лица и не выглядит как стенограмма.
2026-06-27 14:07:10 +03:00
Призыв к платным материалам:
- размещай только в конце;
- тон спокойный, без давления;
- связывай призыв с темой статьи;
- не обещай того, чего нет в исходных данных.
Верни ответ строго в JSON без Markdown.
Формат ответа:
{
"decision": "single_article" или "multiple_articles",
"reason": "почему выбран такой формат",
"articles": [
{
"title": "...",
"subtitle": "...",
"lead": "...",
"body": "...",
"conclusion": "...",
"audience_question": "...",
2026-06-27 14:07:10 +03:00
"image_prompt": "...",
"image_timestamp_hint": "00:00:00",
"tags": ["...", "..."],
"source_fragments": [
{
"start": "00:00:00",
"end": "00:00:00",
"summary": "..."
}
]
}
]
}
"""
ENTITY_CORRECTIONS = {
"Армузский пролив": "Ормузский пролив",
"Армузского пролива": "Ормузского пролива",
"Армузском проливе": "Ормузском проливе",
"Армузским проливом": "Ормузским проливом",
}
QUALITY_REWRITE_ATTEMPTS = 3
QUALITY_ERROR_MARKERS = [
"LLM вернул невалидный JSON",
"Статья содержит первое лицо",
"Статья похожа на необработанную транскрибацию",
"Статья содержит подозрительную ошибку",
"Статья содержит латинские/английские слова",
"Статья слишком короткая",
]
2026-06-27 14:07:10 +03:00
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
2026-06-27 14:07:10 +03:00
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}"
if message:
line = f"{line}: {message}"
with SessionLocal() as session:
video = session.get(Video, video_id)
if not video:
return
if percent is not None:
video.progress_percent = max(0, min(100, percent))
video.progress_stage = stage
if status:
video.status = status
current_log = video.progress_log or ""
next_log = f"{current_log}\n{line}".strip()
video.progress_log = "\n".join(next_log.splitlines()[-220:])
session.commit()
def run_logged(command: list[str], video_id: int, stage: str, cwd: Path | None = None) -> str:
append_progress(video_id, None, stage, "Запуск команды: " + shlex.join(command))
process = subprocess.Popen(
command,
cwd=cwd,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
assert process.stdout is not None
output: list[str] = []
buffered: list[str] = []
for raw in process.stdout:
line = raw.strip()
if not line:
continue
output.append(line)
percent = command_progress_percent(stage, line)
if percent is not None:
append_progress(video_id, percent, stage)
buffered.append(line)
if len(buffered) >= 8:
append_progress(video_id, None, stage, "\n".join(buffered))
buffered = []
if buffered:
append_progress(video_id, None, stage, "\n".join(buffered))
return_code = process.wait()
if return_code:
output_tail = "\n".join(output[-30:]).strip()
message = f"Команда завершилась с кодом {return_code}: {shlex.join(command)}"
if output_tail:
message = f"{message}\n\nПоследний вывод команды:\n{output_tail}"
raise RuntimeError(message)
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
2026-06-27 14:07:10 +03:00
def command_progress_percent(stage: str, line: str) -> int | None:
if stage == "Скачивание":
match = re.search(r"\[download]\s+(\d+(?:\.\d+)?)%", line)
if match:
downloaded = min(100.0, max(0.0, float(match.group(1))))
return 10 + round(downloaded * 0.25)
return None
def ytdlp_base_args() -> list[str]:
args = ["yt-dlp"]
cookies = Path(settings.ytdlp_cookies_path)
if cookies.exists():
args.extend(["--cookies", str(cookies)])
return args
def parse_upload_date(value: str | None) -> datetime | None:
if not value:
return None
try:
return datetime.strptime(value, "%Y%m%d").replace(tzinfo=timezone.utc)
except ValueError:
return None
@celery_app.task(name="app.worker.scan_sources")
def scan_sources() -> dict[str, int]:
init_db()
created = 0
with SessionLocal() as session:
sources = session.scalars(select(Source).where(Source.enabled == True)).all() # noqa: E712
for source in sources:
try:
items = scan_vk_api_source(source) if source.source_type == "vk_api" else scan_ytdlp_source(source)
for item in items:
created += upsert_video(session, source, item)
source.last_checked_at = datetime.now(timezone.utc)
session.commit()
except Exception as exc:
source.last_checked_at = datetime.now(timezone.utc)
session.commit()
print(f"Failed to scan {source.url}: {exc}")
return {"created": created}
def scan_ytdlp_source(source: Source) -> list[dict]:
command = ytdlp_base_args() + [
"--flat-playlist",
"--dump-json",
"--playlist-end",
"200",
source.url,
]
result = run(command)
return [json.loads(line) for line in result.stdout.splitlines() if line.strip()]
def scan_vk_api_source(_source: Source) -> list[dict]:
if not settings.vk_api_token.strip():
raise RuntimeError("VK_API_TOKEN is required for vk_api sources")
with httpx.Client(timeout=30) as client:
response = client.get(
"https://api.vk.com/method/video.get",
params={
"owner_id": settings.vk_video_owner_id,
"count": 200,
"access_token": settings.vk_api_token,
"v": "5.199",
},
)
response.raise_for_status()
payload = response.json()
if "error" in payload:
raise RuntimeError(payload["error"].get("error_msg", "VK API error"))
return payload.get("response", {}).get("items", [])
def upsert_video(session, source: Source, item: dict) -> int:
owner_id = item.get("owner_id") or item.get("owner")
item_id = item.get("id") or item.get("video_id")
external_id = str(item.get("id") or item.get("url") or "")
if owner_id is not None and item_id is not None:
external_id = f"{owner_id}_{item_id}"
if not external_id:
return 0
page_url = item.get("webpage_url") or item.get("url") or item.get("player") or source.url
if owner_id is not None and item_id is not None:
page_url = f"https://vkvideo.ru/video{owner_id}_{item_id}"
if item.get("access_key"):
page_url = f"{page_url}_{item['access_key']}"
published_at = parse_upload_date(item.get("upload_date"))
if item.get("date") and not published_at:
published_at = datetime.fromtimestamp(int(item["date"]), tz=timezone.utc)
thumbnail_url = best_thumbnail_url(item)
existing = session.scalar(select(Video).where(Video.source_id == source.id, Video.external_id == external_id))
if existing:
if thumbnail_url and not existing.thumbnail_url:
existing.thumbnail_url = thumbnail_url
if page_url and existing.source_url != str(page_url):
existing.source_url = str(page_url)
if item.get("title") and not existing.title:
existing.title = str(item.get("title") or "")
if item.get("description") and not existing.description:
existing.description = str(item.get("description") or "")
return 0
video = Video(
source_id=source.id,
external_id=external_id,
source_url=str(page_url),
thumbnail_url=thumbnail_url,
title=str(item.get("title") or ""),
description=str(item.get("description") or ""),
duration_seconds=item.get("duration"),
published_at=published_at,
status="new",
)
session.add(video)
return 1
def best_thumbnail_url(item: dict) -> str:
for field in ["image", "first_frame"]:
images = item.get(field)
if not isinstance(images, list):
continue
candidates = [image for image in images if isinstance(image, dict) and image.get("url")]
if candidates:
best = max(candidates, key=lambda image: int(image.get("width") or 0) * int(image.get("height") or 0))
return str(best.get("url") or "")
for key in ["photo_2560", "photo_1280", "photo_800", "photo_640", "photo_320"]:
if item.get(key):
return str(item[key])
return ""
@celery_app.task(name="app.worker.process_video")
def process_video(video_id: int, selected_chapters: list[dict[str, Any]] | None = None) -> dict[str, int | str]:
2026-06-27 14:07:10 +03:00
init_db()
with SessionLocal() as session:
video = session.get(Video, video_id)
if not video:
return {"status": "missing", "videoId": video_id}
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"
video.error_message = None
session.commit()
try:
append_progress(video_id, 10, "Скачивание", "Скачиваю видео из VK")
local_video = download_video(video)
video.local_video_path = str(local_video)
session.commit()
append_progress(video_id, 35, "Транскрибация", "Проверяю сохраненную расшифровку")
transcript = transcribe_video(local_video, video_id, video.transcript_path)
2026-06-27 14:07:10 +03:00
video.transcript_path = str(transcript)
session.commit()
append_progress(video_id, 60, "Кадры", "Выбираю кадры-кандидаты")
frames = extract_frames(local_video, video_id)
for frame in frames:
session.add(frame)
session.commit()
chapter_count = len(selected_chapters or [])
chapter_note = f" по выбранным главам: {chapter_count}" if chapter_count else ""
append_progress(video_id, 75, "ИИ-редактор", f"Готовлю статьи по транскрипту{chapter_note}")
signature_html = session.scalar(
select(AppSetting.value).where(AppSetting.key == "article_signature_html")
) or ""
articles = build_articles(video, transcript, frames, selected_chapters, signature_html)
2026-06-27 14:07:10 +03:00
for article in articles:
session.add(article)
video.status = "drafted"
video.progress_percent = 100
video.progress_stage = "Готово"
session.commit()
append_progress(video_id, 100, "Готово", f"Создано статей: {len(articles)}", status="drafted")
return {"status": "drafted", "videoId": video.id, "articleCount": len(articles)}
except Exception as exc:
session.rollback()
video = session.get(Video, video_id)
if not video:
raise
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}")
return candidate
2026-06-27 14:07:10 +03:00
target_dir = settings.videos_path / str(video.id)
target_dir.mkdir(parents=True, exist_ok=True)
target = target_dir / "video.%(ext)s"
command = ytdlp_base_args() + [
"-f",
"bestvideo[height<=720]+bestaudio/best[height<=720]/best",
"-o",
str(target),
video.source_url,
]
run_logged(command, video.id, "Скачивание")
files = sorted(target_dir.glob("video.*"))
if not files:
raise RuntimeError("yt-dlp did not create a video file")
return files[0]
def transcribe_video(video_path: Path, video_id: int, cached_path: str | None = None) -> Path:
2026-06-27 14:07:10 +03:00
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
2026-06-27 14:07:10 +03:00
if not settings.whisper_command.strip():
raise RuntimeError("WHISPER_COMMAND не настроен. Транскрибация не выполнена, статья не создана.")
append_progress(video_id, 35, "Транскрибация", "Сохраненной расшифровки нет, запускаю Whisper")
2026-06-27 14:07:10 +03:00
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)
2026-06-27 14:07:10 +03:00
command = command_base + ["--output", str(transcript_path), str(video_path)]
cwd = Path("/app")
else:
command = command_base + [str(video_path)]
cwd = target_dir
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
2026-06-27 14:07:10 +03:00
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
txt_files = sorted(target_dir.glob("*.txt"), key=lambda item: item.stat().st_mtime, reverse=True)
if txt_files:
txt_files[0].replace(transcript_path)
validate_transcript_text(transcript_path.read_text(encoding="utf-8", errors="ignore"))
return transcript_path
transcript_path.write_text(output.strip(), encoding="utf-8")
validate_transcript_text(transcript_path.read_text(encoding="utf-8", errors="ignore"))
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
2026-06-27 14:07:10 +03:00
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)
command = [
"ffmpeg",
"-y",
"-i",
str(video_path),
"-vf",
"fps=1/30,scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2",
"-frames:v",
str(settings.frame_candidates),
"-c:v",
"libwebp",
"-quality",
"82",
str(target_dir / "frame-%03d.webp"),
]
run_logged(command, video_id, "Кадры")
frames: list[Frame] = []
for index, path in enumerate(sorted(target_dir.glob("frame-*.webp")), start=1):
public_url = f"{settings.public_base_url.rstrip('/')}/media/videos/{video_id}/{path.name}"
frames.append(
Frame(
video_id=video_id,
local_path=str(path),
public_url=public_url,
timestamp_seconds=index * 30,
score=max(1, settings.frame_candidates - index + 1),
reason="MVP: кадр-кандидат из равномерной выборки, требует редакторского подтверждения.",
selected=index <= 3,
)
)
return frames
def build_articles(
video: Video,
transcript_path: Path,
frames: list[Frame],
selected_chapters: list[dict[str, Any]] | None = None,
signature_html: str = "",
) -> list[Article]:
2026-06-27 14:07:10 +03:00
transcript = transcript_path.read_text(encoding="utf-8", errors="ignore")
validate_transcript_text(transcript)
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, signature_html=signature_html)
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,
signature_html=signature_html,
)
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,
signature_html: str = "",
) -> 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}",
)
2026-06-27 14:07:10 +03:00
try:
payload = generate_article_payload(video, transcript, chapter=chapter, quality_feedback=feedback)
if signature_html:
articles = articles_from_payload(video, payload, frames, signature_html=signature_html)
else:
articles = articles_from_payload(video, payload, 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}",
)
normalized_payload = neutralize_payload_first_person(payload)
if signature_html:
articles = articles_from_payload(video, normalized_payload, frames, signature_html=signature_html)
else:
articles = articles_from_payload(video, normalized_payload, frames)
if articles:
return articles
raise
if articles:
return articles
feedback = "В ответе нет массива articles с пригодными статьями."
return []
2026-06-27 14:07:10 +03:00
def is_quality_error(message: str) -> bool:
return any(marker in message for marker in QUALITY_ERROR_MARKERS)
2026-06-27 14:07:10 +03:00
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]:
2026-06-27 14:07:10 +03:00
transcript = transcript.strip()
if len(transcript) > settings.llm_max_transcript_chars:
transcript = transcript[: settings.llm_max_transcript_chars] + "\n\n[Транскрипт обрезан по лимиту контекста.]"
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 ""}
Перепиши материал заново. Не пытайся точечно заменить одно слово: полностью убери первое лицо,
разговорную подачу, обращения к зрителю, следы стенограммы и сомнительные имена/географию.
Запрещены местоимения и формы авторской речи: «я», «мы», «мне», «нам», «наш», «давайте»,
«посмотрим», «разберем», «я думаю», «я считаю». Текст должен звучать как готовая
редакторская аналитическая статья в третьем лице.
Если проверка указала сомнительную должность или имя, перепроверь актуальность на редакционную дату
и используй осторожную формулировку без устаревшей текущей должности.
"""
2026-06-27 14:07:10 +03:00
user_prompt = f"""Название ролика:
{video.title}
Описание ролика:
{video.description}
Дата публикации:
{video.published_at.isoformat() if video.published_at else ""}
Длительность ролика:
{format_video_duration(video.duration_seconds)}
Редакционная дата:
{current_editorial_date_ru()}
2026-06-27 14:07:10 +03:00
Редакционный план:
{editorial_plan}
{chapter_context}
{rewrite_context}
2026-06-27 14:07:10 +03:00
Транскрипт:
{transcript}
Задача:
Сделай из этого материала статью или серию статей для Дзена по системным правилам и редакционному плану."""
response_text = call_llm(user_prompt)
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 полного исходного видео будет добавлен автоматически."
)
2026-06-27 14:07:10 +03:00
def format_video_duration(seconds: int | None) -> str:
if not seconds:
return "неизвестна"
minutes = seconds // 60
rest = seconds % 60
return f"{minutes}:{rest:02d}"
def article_count_instruction(video: Video) -> str:
seconds = video.duration_seconds or 0
title = (video.title or "").lower()
is_program_episode = "по сути дела" in title
if seconds >= 30 * 60:
return (
"Сделай 4 самостоятельные статьи. Раздели выпуск на 4 крупных смысловых блока, "
"не дроби одну тему искусственно, но не объединяй разные темы в одну статью. "
"У каждой статьи должны быть свой заголовок, свой lead, свои подзаголовки и законченный вывод. "
"В конце каждой статьи будет автоматически добавлен один и тот же embed исходного видео."
2026-06-27 14:07:10 +03:00
)
if seconds >= 18 * 60 or is_program_episode:
return (
"Сделай 2-3 самостоятельные статьи, если в транскрипте есть несколько тем. "
"Если выпуск фактически состоит из одной темы, допустима одна большая статья."
)
return "Сделай одну цельную статью, если нет явно отдельной второй темы."
def call_llm(user_prompt: str) -> 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"
"---"
)
2026-06-27 14:07:10 +03:00
payload = {
"model": settings.llm_model,
"messages": [
{"role": "system", "content": system_prompt},
2026-06-27 14:07:10 +03:00
{"role": "user", "content": user_prompt},
],
"temperature": 0.15,
2026-06-27 14:07:10 +03:00
}
last_error = ""
attempts = max(1, settings.llm_retry_attempts)
2026-06-27 14:07:10 +03:00
with httpx.Client(timeout=settings.llm_timeout_seconds) as client:
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]
2026-08-11 13:23:56 +03:00
if status_code == 400 and "DataInspectionFailed" in detail:
if attempt < attempts:
time.sleep(2 * attempt)
continue
raise RuntimeError(
f"Timeweb LLM отклонил проверку входных данных после {attempts} попыток: {detail}"
) from exc
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}")
2026-06-27 14:07:10 +03:00
def parse_llm_json(text: str) -> dict[str, Any]:
cleaned = text.strip()
if cleaned.startswith("```"):
cleaned = re.sub(r"^```(?:json)?\s*", "", cleaned)
cleaned = re.sub(r"\s*```$", "", cleaned)
try:
return json.loads(cleaned)
except json.JSONDecodeError as original_error:
2026-06-27 14:07:10 +03:00
match = re.search(r"\{.*\}", cleaned, flags=re.S)
if not match:
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 '"}]'
2026-06-27 14:07:10 +03:00
def articles_from_payload(video: Video, payload: dict[str, Any], frames: list[Frame], signature_html: str = "") -> list[Article]:
2026-06-27 14:07:10 +03:00
raw_articles = payload.get("articles")
if not isinstance(raw_articles, list):
return []
articles: list[Article] = []
for index, item in enumerate(raw_articles, start=1):
if not isinstance(item, dict):
continue
title = clean_generated_text(str(item.get("title") or video.title or "Новый разбор Николая Старикова")).strip()
if not title:
continue
suffix = f"-{index}" if len(raw_articles) > 1 else ""
slug = f"{datetime.now(timezone.utc).strftime('%Y%m%d')}-{video.id}{suffix}-{slugify(title)}"
lead = generated_content_to_html(str(item.get("lead") or item.get("subtitle") or ""))
body_html = article_body_html(item, frames, title, video)
validate_article_content(title, lead, body_html)
articles.append(
Article(
video_id=video.id,
slug=slug,
title=title,
lead=lead,
body_html=body_html,
cta_html=signature_html.strip(),
feature_image_url=video.thumbnail_url or "",
2026-06-27 14:07:10 +03:00
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)
2026-06-27 14:07:10 +03:00
def article_body_html(item: dict[str, Any], frames: list[Frame], title: str, video: Video) -> str:
body_html = generated_content_to_html(str(item.get("body") or ""))
body_html = inject_section_frames(body_html, frames, title)
2026-08-14 18:09:05 +03:00
body_html, _ = split_audience_question_html(body_html)
conclusion_html, _ = split_audience_question_html(generated_content_to_html(str(item.get("conclusion") or "")))
2026-06-27 14:07:10 +03:00
parts = [
body_html,
2026-08-14 18:09:05 +03:00
conclusion_html,
f"<p>{VIDEO_PLACEHOLDER}</p>",
audience_question_html(item, title),
2026-06-27 14:07:10 +03:00
]
return "\n".join(part for part in parts if part).strip()
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}»?"
2026-08-15 08:39:30 +03:00
question = re.sub(r"^Ваше мнение\s*:\s*", "", question, flags=re.I)
question = re.sub(r"\bвы\b", "Вы", question)
if not question.endswith(("?", "?")):
question = f"{question.rstrip('.!')}?"
2026-08-15 08:39:30 +03:00
return f"<h2>Ваше мнение</h2><p>{escape(question)} Пишите своё мнение в комментариях.</p>"
2026-06-27 14:07:10 +03:00
def frame_figure_html(frame: Frame, title: str, caption: str | None = None) -> str:
if not frame.public_url:
return ""
caption_text = clean_generated_text(caption or title)
return (
f'<figure><img src="{escape(frame.public_url)}" alt="{escape(title)}">'
f"<figcaption>{escape(caption_text)}</figcaption></figure>"
)
def inject_section_frames(html: str, frames: list[Frame], title: str) -> str:
available_frames = [frame for frame in frames if frame.public_url]
if not html or not available_frames:
return html
frame_iter = iter(available_frames)
def add_frame_after_heading(match: re.Match[str]) -> str:
try:
frame = next(frame_iter)
except StopIteration:
return match.group(0)
heading = re.sub(r"<.*?>", "", match.group(0)).strip()
return f"{match.group(0)}\n{frame_figure_html(frame, title, heading)}"
return re.sub(r"(<h2>.*?</h2>)", add_frame_after_heading, html, flags=re.I | re.S)
def choose_frame_by_timestamp(frames: list[Frame], timestamp: str) -> Frame | None:
seconds = timestamp_to_seconds(timestamp)
if seconds is None:
return frames[0] if frames else None
return min(frames, key=lambda frame: abs(frame.timestamp_seconds - seconds), default=None)
def timestamp_to_seconds(value: str) -> int | None:
match = re.search(r"(?:(\d{1,2}):)?(\d{1,2}):(\d{2})", value)
if not match:
return None
hours = int(match.group(1) or 0)
minutes = int(match.group(2))
seconds = int(match.group(3))
return hours * 3600 + minutes * 60 + seconds
def clean_generated_text(text: str) -> str:
text = unescape(text).strip()
replacements = {
"新一轮": " новый виток ",
}
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)
2026-06-27 14:07:10 +03:00
text = re.sub(r"[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]+", "", text)
text = re.sub(r"[ \t]{2,}", " ", text)
text = text.replace("спровоцировав новый виток обсуждение", "спровоцировав новый виток обсуждения")
text = text.replace("спровоцировавновый виток обсуждение", "спровоцировав новый виток обсуждения")
return text.strip()
def clean_heading_text(text: str) -> str:
text = clean_generated_text(text)
return re.sub(r"^(?:#{1,6}\s*)+", "", text).strip()
def generated_content_to_html(text: str) -> str:
text = clean_generated_text(text)
if not text:
return ""
if re.search(r"</?(p|h2|h3|strong|em|b|i|ul|ol|li|br)\b", text, flags=re.I):
return sanitize_generated_html(text)
return text_to_html(text)
def sanitize_generated_html(html: str) -> str:
html = re.sub(r"<\s*(script|style)[^>]*>.*?<\s*/\s*\1\s*>", "", html, flags=re.I | re.S)
allowed = {"p", "h2", "h3", "strong", "em", "b", "i", "ul", "ol", "li", "br"}
def replace_tag(match: re.Match[str]) -> str:
closing, tag = match.group(1), match.group(2).lower()
if tag not in allowed:
return ""
if tag == "br":
return "<br>"
return f"<{closing}{tag}>"
html = re.sub(r"<\s*(/?)\s*([a-zA-Z0-9]+)(?:\s+[^>]*)?/?>", replace_tag, html)
return html.strip()
def text_to_html(text: str) -> str:
text = clean_generated_text(text)
if not text:
return ""
blocks = [block.strip() for block in re.split(r"\n{2,}", text) if block.strip()]
html_blocks: list[str] = []
for block in blocks:
normalized = re.sub(r"\s+", " ", block).strip()
heading = clean_heading_text(normalized)
if len(normalized) <= 120 and not normalized.endswith((".", "!", "?")):
html_blocks.append(f"<h2>{escape(heading)}</h2>")
else:
html_blocks.append(f"<p>{escape(normalized)}</p>")
return "\n".join(html_blocks)
def default_cta_text() -> str:
return "Полный разбор темы и новые закрытые лекции доступны в платных материалах Николая Старикова."