import json import re import shlex import subprocess 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.config import get_settings from app.database import SessionLocal, init_db from app.models import Article, Frame, Source, Video from app.quality import validate_article_content, validate_transcript_text 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, }, } 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 = """Ты редактор канала Николая Старикова в Дзене. Твоя задача: превращать расшифровки видеороликов в качественные статьи для Яндекс.Дзена. Работай только с предоставленным транскриптом и метаданными. Не добавляй факты, которых нет в исходном тексте. Не выдумывай цитаты, даты, имена, цифры и события. Стиль: - публицистический, ясный, уверенный; - без чрезмерной академичности; - без разговорных оговорок, повторов и мусора устной речи; - сохраняй позицию и смысл автора; - не делай текст агрессивнее исходника; - не используй кликбейт, если он искажает смысл; - заголовки должны быть сильными, но честными. - используй только русский язык; не вставляй китайские, английские или другие иностранные фразы, если они не являются частью исходной цитаты. Для каждого ролика определи, что лучше: 1. одна цельная статья; 2. несколько самостоятельных статей, если в ролике есть несколько разных тем. Если ролик длинный и содержит несколько тем, раздели его на 2-4 статьи. Если в пользовательском задании указано целевое количество статей, строго ориентируйся на него. Для выпусков программы «По сути дела» длительностью 30-40 минут обычно нужно сделать 4 статьи: по одной на каждый крупный смысловой блок выпуска. Каждая статья должна быть самостоятельной, с отдельным заголовком и законченной мыслью. Для каждой статьи сделай: - title: короткий сильный заголовок до 90 символов; - subtitle: поясняющий подзаголовок до 160 символов; - lead: вступление 1-2 абзаца; - body: основной текст с подзаголовками; - conclusion: финальный вывод; - image_prompt: какой кадр из видео лучше использовать; - image_timestamp_hint: примерный таймкод из транскрипта, где искать подходящий кадр; - tags: 5-8 тегов; - premium_teaser: короткий аккуратный призыв к платным материалам или курсам; - source_fragments: таймкоды/фрагменты транскрипта, на которых основана статья. Требования к статье: - объем обычной статьи: 3500-7000 знаков; - если тема маленькая, не раздувай искусственно; - если тема большая, дели на несколько статей; - каждый абзац должен быть удобен для чтения в Дзене; - не начинай статью словами "в данном видео"; - не упоминай технически "транскрипт", "ролик", "расшифровка", если это не нужно по смыслу; - исправляй ошибки распознавания Whisper по контексту, но не меняй смысл. Призыв к платным материалам: - размещай только в конце; - тон спокойный, без давления; - связывай призыв с темой статьи; - не обещай того, чего нет в исходных данных. Верни ответ строго в JSON без Markdown. Формат ответа: { "decision": "single_article" или "multiple_articles", "reason": "почему выбран такой формат", "articles": [ { "title": "...", "subtitle": "...", "lead": "...", "body": "...", "conclusion": "...", "image_prompt": "...", "image_timestamp_hint": "00:00:00", "tags": ["...", "..."], "premium_teaser": "...", "source_fragments": [ { "start": "00:00:00", "end": "00:00:00", "summary": "..." } ] } ] } """ 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 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 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) -> dict[str, int | str]: 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, "Транскрибация", "Запускаю Whisper") transcript = transcribe_video(local_video, video_id) 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() append_progress(video_id, 75, "ИИ-редактор", "Готовлю статью по транскрипту") articles = build_articles(video, transcript, frames) 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: 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) -> Path: target_dir = settings.transcripts_path / str(video_id) target_dir.mkdir(parents=True, exist_ok=True) transcript_path = target_dir / "transcript.txt" if not settings.whisper_command.strip(): raise RuntimeError("WHISPER_COMMAND не настроен. Транскрибация не выполнена, статья не создана.") command_base = shlex.split(settings.whisper_command) if "app.whisper_cli" in 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) 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 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 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]: 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(): 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)] 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"
{escape(chunk)}
") 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 generate_article_payload(video: Video, transcript: 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) user_prompt = f"""Название ролика: {video.title} Описание ролика: {video.description} Дата публикации: {video.published_at.isoformat() if video.published_at else ""} Длительность ролика: {format_video_duration(video.duration_seconds)} Редакционный план: {editorial_plan} Транскрипт: {transcript} Задача: Сделай из этого материала статью или серию статей для Дзена по системным правилам и редакционному плану.""" response_text = call_llm(user_prompt) return parse_llm_json(response_text) 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 исходного видео и блок Дзен Премиум." ) 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", } payload = { "model": settings.llm_model, "messages": [ {"role": "system", "content": ARTICLE_SYSTEM_PROMPT}, {"role": "user", "content": user_prompt}, ], "temperature": 0.35, } 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"] 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: match = re.search(r"\{.*\}", cleaned, flags=re.S) if not match: raise return json.loads(match.group(0)) def articles_from_payload(video: Video, payload: dict[str, Any], frames: list[Frame]) -> list[Article]: 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="", status="draft", ) ) return articles 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 "")), ] 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'{escape(normalized)}
") return "\n".join(html_blocks) def default_cta_text() -> str: return "Полный разбор темы и новые закрытые лекции доступны в платных материалах Николая Старикова."