chore: initialize project repository
This commit is contained in:
commit
23f75adb40
73 changed files with 10419 additions and 0 deletions
9
.dockerignore
Normal file
9
.dockerignore
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
.DS_Store
|
||||
.env
|
||||
.git
|
||||
.venv
|
||||
__pycache__/
|
||||
*.pyc
|
||||
data/
|
||||
output/
|
||||
storage/
|
||||
23
.env.example
Normal file
23
.env.example
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
APP_ENV=production
|
||||
APP_BASE_URL=https://vk2ok.bot.nstarikov.ru
|
||||
|
||||
SQLITE_PATH=/app/data/vk2ok.sqlite3
|
||||
STORAGE_DIR=/app/storage
|
||||
|
||||
REDIS_URL=redis://redis:6379/0
|
||||
CELERY_BROKER_URL=redis://redis:6379/0
|
||||
CELERY_RESULT_BACKEND=redis://redis:6379/1
|
||||
|
||||
VK_GROUP_ID=9828339
|
||||
VK_CONFIRMATION_CODE=58578d71
|
||||
VK_SECRET=590c3c72
|
||||
VK_API_VERSION=5.199
|
||||
|
||||
OK_APP_ID=
|
||||
OK_PUBLIC_KEY=
|
||||
OK_SECRET_KEY=
|
||||
OK_ACCESS_TOKEN=
|
||||
OK_SESSION_SECRET_KEY=
|
||||
OK_GROUP_ID=
|
||||
|
||||
YTDLP_COOKIES_PATH=/app/data/vk_cookies.txt
|
||||
10
.gitignore
vendored
Normal file
10
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
.DS_Store
|
||||
.env
|
||||
.venv/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
node_modules/
|
||||
dist/
|
||||
.worktrees/
|
||||
data/
|
||||
storage/
|
||||
3
Caddyfile.snippet
Normal file
3
Caddyfile.snippet
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
vk2ok.bot.nstarikov.ru {
|
||||
reverse_proxy vk2ok-api:8000
|
||||
}
|
||||
18
Dockerfile
Normal file
18
Dockerfile
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
FROM python:3.12-slim
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ffmpeg ca-certificates curl fonts-dejavu-core \
|
||||
&& 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 app ./app
|
||||
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
43
README.md
Normal file
43
README.md
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
# vk2ok
|
||||
|
||||
Сервис принимает webhook VK на `https://vk2ok.bot.nstarikov.ru/webhook`, сохраняет событие в SQLite и ставит обработку в Redis/Celery.
|
||||
|
||||
## Развертывание
|
||||
|
||||
```bash
|
||||
mkdir -p /var/www/bots/vk2ok
|
||||
cd /var/www/bots/vk2ok
|
||||
cp .env.example .env
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
В Caddy добавить:
|
||||
|
||||
```caddyfile
|
||||
vk2ok.bot.nstarikov.ru {
|
||||
reverse_proxy vk2ok-api:8000
|
||||
}
|
||||
```
|
||||
|
||||
После запуска в VK нажать "Подтвердить". На confirmation-запрос сервис вернет строку из `VK_CONFIRMATION_CODE`.
|
||||
|
||||
## Проверка webhook
|
||||
|
||||
```bash
|
||||
curl -i https://vk2ok.bot.nstarikov.ru/health
|
||||
curl -i -X POST https://vk2ok.bot.nstarikov.ru/webhook \
|
||||
-H 'content-type: application/json' \
|
||||
-d '{"type":"confirmation","group_id":9828339}'
|
||||
```
|
||||
|
||||
Ожидаемый ответ второго запроса:
|
||||
|
||||
```text
|
||||
58578d71
|
||||
```
|
||||
|
||||
## Файлы
|
||||
|
||||
- SQLite: `/var/www/bots/vk2ok/data/vk2ok.sqlite3`
|
||||
- Видео и обложки: `/var/www/bots/vk2ok/storage`
|
||||
- cookies VK для yt-dlp: `/var/www/bots/vk2ok/data/vk_cookies.txt`
|
||||
1
app/__init__.py
Normal file
1
app/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
|||
|
||||
45
app/config.py
Normal file
45
app/config.py
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
|
||||
|
||||
app_env: str = "production"
|
||||
app_base_url: str = "https://vk2ok.bot.nstarikov.ru"
|
||||
|
||||
sqlite_path: str = "/app/data/vk2ok.sqlite3"
|
||||
storage_dir: str = "/app/storage"
|
||||
|
||||
redis_url: str = "redis://redis:6379/0"
|
||||
celery_broker_url: str = "redis://redis:6379/0"
|
||||
celery_result_backend: str = "redis://redis:6379/1"
|
||||
|
||||
vk_group_id: str = "9828339"
|
||||
vk_confirmation_code: str = "58578d71"
|
||||
vk_secret: str = "590c3c72"
|
||||
vk_api_version: str = "5.199"
|
||||
|
||||
ok_app_id: str = ""
|
||||
ok_public_key: str = ""
|
||||
ok_secret_key: str = ""
|
||||
ok_access_token: str = ""
|
||||
ok_session_secret_key: str = ""
|
||||
ok_group_id: str = ""
|
||||
|
||||
ytdlp_cookies_path: str = "/app/data/vk_cookies.txt"
|
||||
|
||||
@property
|
||||
def sqlite_url(self) -> str:
|
||||
return f"sqlite:///{self.sqlite_path}"
|
||||
|
||||
@property
|
||||
def storage_path(self) -> Path:
|
||||
return Path(self.storage_dir)
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
63
app/database.py
Normal file
63
app/database.py
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
from collections.abc import Generator
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
Path(settings.sqlite_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
engine = create_engine(
|
||||
settings.sqlite_url,
|
||||
connect_args={"check_same_thread": False},
|
||||
future=True,
|
||||
)
|
||||
|
||||
|
||||
@event.listens_for(engine, "connect")
|
||||
def configure_sqlite(dbapi_connection, _connection_record) -> None:
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA journal_mode=WAL")
|
||||
cursor.execute("PRAGMA busy_timeout=5000")
|
||||
cursor.execute("PRAGMA foreign_keys=ON")
|
||||
cursor.close()
|
||||
|
||||
|
||||
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False)
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
from app import models # noqa: F401
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
with engine.begin() as connection:
|
||||
post_media_columns = {
|
||||
row[1] for row in connection.exec_driver_sql("PRAGMA table_info(post_media)").fetchall()
|
||||
}
|
||||
if "duration_seconds" not in post_media_columns:
|
||||
connection.exec_driver_sql("ALTER TABLE post_media ADD COLUMN duration_seconds INTEGER")
|
||||
if "playlist_title" not in post_media_columns:
|
||||
connection.exec_driver_sql("ALTER TABLE post_media ADD COLUMN playlist_title TEXT")
|
||||
post_columns = {row[1] for row in connection.exec_driver_sql("PRAGMA table_info(posts)").fetchall()}
|
||||
if "content_key" not in post_columns:
|
||||
connection.exec_driver_sql("ALTER TABLE posts ADD COLUMN content_key VARCHAR(128)")
|
||||
connection.exec_driver_sql("CREATE INDEX IF NOT EXISTS ix_posts_content_key ON posts (content_key)")
|
||||
if "publish_lock" not in post_columns:
|
||||
connection.exec_driver_sql("ALTER TABLE posts ADD COLUMN publish_lock VARCHAR(128)")
|
||||
connection.exec_driver_sql("CREATE INDEX IF NOT EXISTS ix_posts_publish_lock ON posts (publish_lock)")
|
||||
video_columns = {row[1] for row in connection.exec_driver_sql("PRAGMA table_info(videos)").fetchall()}
|
||||
if "upload_lock" not in video_columns:
|
||||
connection.exec_driver_sql("ALTER TABLE videos ADD COLUMN upload_lock VARCHAR(128)")
|
||||
connection.exec_driver_sql("CREATE INDEX IF NOT EXISTS ix_videos_upload_lock ON videos (upload_lock)")
|
||||
|
||||
|
||||
def get_session() -> Generator[Session, None, None]:
|
||||
with SessionLocal() as session:
|
||||
yield session
|
||||
16
app/main.py
Normal file
16
app/main.py
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
|
||||
from app.database import init_db
|
||||
from app.routes import router
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
init_db()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="vk2ok", version="0.1.0", lifespan=lifespan)
|
||||
app.include_router(router)
|
||||
91
app/models.py
Normal file
91
app/models.py
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Integer, String, Text, UniqueConstraint, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class VkEvent(Base):
|
||||
__tablename__ = "vk_events"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
event_id: Mapped[str | None] = mapped_column(String(128), index=True)
|
||||
event_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
group_id: Mapped[str] = mapped_column(String(64), index=True)
|
||||
raw_payload_json: Mapped[str] = mapped_column(Text)
|
||||
status: Mapped[str] = mapped_column(String(32), default="queued", index=True)
|
||||
error_message: Mapped[str | None] = mapped_column(Text)
|
||||
received_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
processed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class Post(Base):
|
||||
__tablename__ = "posts"
|
||||
__table_args__ = (UniqueConstraint("vk_group_id", "vk_post_id", name="uq_posts_vk_group_post"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
vk_group_id: Mapped[str] = mapped_column(String(64), index=True)
|
||||
vk_post_id: Mapped[str] = mapped_column(String(64), index=True)
|
||||
vk_post_url: Mapped[str | None] = mapped_column(Text)
|
||||
text: Mapped[str] = mapped_column(Text, default="")
|
||||
content_key: Mapped[str | None] = mapped_column(String(128), index=True)
|
||||
status: Mapped[str] = mapped_column(String(32), default="pending", index=True)
|
||||
ok_topic_id: Mapped[str | None] = mapped_column(String(128), index=True)
|
||||
publish_lock: Mapped[str | None] = mapped_column(String(128), index=True)
|
||||
error_message: Mapped[str | None] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
media: Mapped[list["PostMedia"]] = relationship(back_populates="post", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class PostMedia(Base):
|
||||
__tablename__ = "post_media"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
post_id: Mapped[int] = mapped_column(ForeignKey("posts.id", ondelete="CASCADE"), index=True)
|
||||
media_type: Mapped[str] = mapped_column(String(32), index=True)
|
||||
vk_attachment_id: Mapped[str | None] = mapped_column(String(128), index=True)
|
||||
source_url: Mapped[str | None] = mapped_column(Text)
|
||||
local_path: Mapped[str | None] = mapped_column(Text)
|
||||
local_cover_path: Mapped[str | None] = mapped_column(Text)
|
||||
ok_media_id: Mapped[str | None] = mapped_column(String(128), index=True)
|
||||
duration_seconds: Mapped[int | None] = mapped_column(Integer)
|
||||
playlist_title: Mapped[str | None] = mapped_column(Text)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
status: Mapped[str] = mapped_column(String(32), default="pending", index=True)
|
||||
error_message: Mapped[str | None] = mapped_column(Text)
|
||||
|
||||
post: Mapped[Post] = relationship(back_populates="media")
|
||||
|
||||
|
||||
class Video(Base):
|
||||
__tablename__ = "videos"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
vk_video_id: Mapped[str | None] = mapped_column(String(128), index=True)
|
||||
vk_video_url: Mapped[str] = mapped_column(Text)
|
||||
title: Mapped[str | None] = mapped_column(Text)
|
||||
description: Mapped[str | None] = mapped_column(Text)
|
||||
local_video_path: Mapped[str | None] = mapped_column(Text)
|
||||
local_cover_path: Mapped[str | None] = mapped_column(Text)
|
||||
ok_video_id: Mapped[str | None] = mapped_column(String(128), index=True)
|
||||
upload_lock: Mapped[str | None] = mapped_column(String(128), index=True)
|
||||
status: Mapped[str] = mapped_column(String(32), default="pending", index=True)
|
||||
error_message: Mapped[str | None] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||
|
||||
|
||||
class PublishJob(Base):
|
||||
__tablename__ = "publish_jobs"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
post_id: Mapped[int] = mapped_column(ForeignKey("posts.id", ondelete="CASCADE"), index=True)
|
||||
celery_task_id: Mapped[str | None] = mapped_column(String(128), index=True)
|
||||
status: Mapped[str] = mapped_column(String(32), default="queued", index=True)
|
||||
attempts: Mapped[int] = mapped_column(Integer, default=0)
|
||||
last_error: Mapped[str | None] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||
256
app/ok_api.py
Normal file
256
app/ok_api.py
Normal file
|
|
@ -0,0 +1,256 @@
|
|||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from app.config import Settings
|
||||
|
||||
|
||||
OK_API_URL = "https://api.ok.ru/fb.do"
|
||||
|
||||
|
||||
class OkApiError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
TAG_STOPWORDS = {
|
||||
"А", "Без", "Будет", "Был", "Была", "Были", "В", "Во", "Вот", "Все", "Для", "Если",
|
||||
"Его", "Ее", "И", "Или", "Как", "Когда", "Кто", "На", "Над", "Не", "Но", "О", "Об",
|
||||
"От", "По", "При", "Про", "С", "Со", "Так", "Что", "Это", "Этот", "Эта", "Эти",
|
||||
"Видео", "Смотрите", "Хотите", "Открывайте", "Школы", "Геополитики",
|
||||
}
|
||||
|
||||
|
||||
def build_video_tags(title: str | None, description: str | None, limit: int = 12) -> str | None:
|
||||
text = "\n".join(part for part in [title or "", description or ""] if part).replace("ё", "е")
|
||||
if not text.strip():
|
||||
return None
|
||||
|
||||
tags: list[str] = []
|
||||
|
||||
def add(tag: str) -> None:
|
||||
clean = re.sub(r"[^\wА-Яа-яЁё\-\s]+", "", tag)
|
||||
clean = re.sub(r"\s+", " ", clean).strip(" -_")
|
||||
if len(clean) < 3 or clean in TAG_STOPWORDS or clean.lower() in {item.lower() for item in tags}:
|
||||
return
|
||||
tags.append(clean)
|
||||
|
||||
for match in re.finditer(r"\b[А-ЯЁA-Z]{2,}(?:-[А-ЯЁA-Z]{2,})?\b", text):
|
||||
add(match.group(0))
|
||||
|
||||
for match in re.finditer(r"\b[А-ЯЁ][а-яё]+(?:-[А-ЯЁ]?[а-яё]+)?\b", text):
|
||||
add(match.group(0))
|
||||
|
||||
for match in re.finditer(r"\b[А-ЯЁ][а-яё]+(?:\s+[А-ЯЁ][а-яё]+){1,2}\b", text):
|
||||
phrase = " ".join(word for word in match.group(0).split() if word not in TAG_STOPWORDS)
|
||||
if phrase and len(phrase) <= 60:
|
||||
add(phrase)
|
||||
|
||||
tags = tags[:limit]
|
||||
if not tags:
|
||||
return None
|
||||
result = ", ".join(tags)
|
||||
return result[:1000]
|
||||
|
||||
|
||||
def build_sig(params: dict[str, Any], session_secret_key: str) -> str:
|
||||
signable = {
|
||||
key: value
|
||||
for key, value in params.items()
|
||||
if key not in {"access_token", "sig"} and value is not None
|
||||
}
|
||||
payload = "".join(f"{key}={signable[key]}" for key in sorted(signable))
|
||||
return hashlib.md5(f"{payload}{session_secret_key}".encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def call_ok(settings: Settings, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
if not settings.ok_access_token or not settings.ok_session_secret_key or not settings.ok_public_key:
|
||||
raise OkApiError("OK credentials are not configured")
|
||||
|
||||
request_params: dict[str, Any] = {
|
||||
"application_key": settings.ok_public_key,
|
||||
"format": "json",
|
||||
"method": method,
|
||||
"access_token": settings.ok_access_token,
|
||||
}
|
||||
request_params.update(params or {})
|
||||
request_params["sig"] = build_sig(request_params, settings.ok_session_secret_key)
|
||||
|
||||
with httpx.Client(timeout=60) as client:
|
||||
response = client.post(OK_API_URL, data=request_params)
|
||||
response.raise_for_status()
|
||||
if not response.text.strip():
|
||||
return {}
|
||||
data = response.json()
|
||||
if isinstance(data, dict) and data.get("error_code"):
|
||||
raise OkApiError(json.dumps(data, ensure_ascii=False))
|
||||
return data
|
||||
|
||||
|
||||
def upload_photo_to_group(settings: Settings, image_path: Path) -> str:
|
||||
if not settings.ok_group_id:
|
||||
raise OkApiError("OK_GROUP_ID is not configured")
|
||||
|
||||
upload_data = call_ok(settings, "photosV2.getUploadUrl", {"gid": settings.ok_group_id, "count": 1})
|
||||
upload_url = upload_data.get("upload_url")
|
||||
if not upload_url:
|
||||
raise OkApiError(f"OK photo upload_url is missing: {upload_data}")
|
||||
|
||||
with image_path.open("rb") as image_file:
|
||||
files = {"pic1": (image_path.name, image_file, "image/jpeg")}
|
||||
with httpx.Client(timeout=120) as client:
|
||||
response = client.post(upload_url, files=files)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
|
||||
photos = result.get("photos")
|
||||
if isinstance(photos, dict):
|
||||
for photo_data in photos.values():
|
||||
if isinstance(photo_data, dict) and photo_data.get("token"):
|
||||
return str(photo_data["token"])
|
||||
|
||||
token = result.get("token") or result.get("photo_token")
|
||||
if token:
|
||||
return str(token)
|
||||
|
||||
raise OkApiError(f"OK photo token is missing: {result}")
|
||||
|
||||
|
||||
def upload_video_cover(settings: Settings, image_path: Path) -> tuple[str, str]:
|
||||
upload_data = call_ok(settings, "photosV2.getUploadUrl", {"count": 1})
|
||||
upload_url = upload_data.get("upload_url")
|
||||
photo_ids = upload_data.get("photo_ids") or []
|
||||
photo_id = str(photo_ids[0]) if photo_ids else ""
|
||||
if not upload_url or not photo_id:
|
||||
raise OkApiError(f"OK cover upload data is missing: {upload_data}")
|
||||
|
||||
with image_path.open("rb") as image_file:
|
||||
files = {"pic1": (image_path.name, image_file, "image/jpeg")}
|
||||
with httpx.Client(timeout=120) as client:
|
||||
response = client.post(upload_url, files=files)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
photo_data = (result.get("photos") or {}).get(photo_id) or {}
|
||||
token = photo_data.get("token")
|
||||
if not token:
|
||||
raise OkApiError(f"OK cover token is missing: {result}")
|
||||
return photo_id, str(token)
|
||||
|
||||
|
||||
def upload_video_to_group(
|
||||
settings: Settings,
|
||||
video_path: Path,
|
||||
title: str | None,
|
||||
description: str | None = None,
|
||||
cover_path: Path | None = None,
|
||||
publish_to_group_video: bool = True,
|
||||
) -> str:
|
||||
if publish_to_group_video and not settings.ok_group_id:
|
||||
raise OkApiError("OK_GROUP_ID is not configured")
|
||||
|
||||
upload_params: dict[str, Any] = {
|
||||
"file_name": video_path.name,
|
||||
"file_size": video_path.stat().st_size,
|
||||
"post_form": "true",
|
||||
}
|
||||
if publish_to_group_video:
|
||||
upload_params["gid"] = settings.ok_group_id
|
||||
|
||||
upload_data = call_ok(
|
||||
settings,
|
||||
"video.getUploadUrl",
|
||||
upload_params,
|
||||
)
|
||||
upload_url = upload_data.get("upload_url")
|
||||
video_id = upload_data.get("video_id")
|
||||
if not upload_url or not video_id:
|
||||
raise OkApiError(f"OK video upload data is missing: {upload_data}")
|
||||
|
||||
with video_path.open("rb") as video_file:
|
||||
files = {"data": (video_path.name, video_file, "video/mp4")}
|
||||
with httpx.Client(timeout=3600) as client:
|
||||
response = client.post(upload_url, files=files)
|
||||
response.raise_for_status()
|
||||
|
||||
update_params: dict[str, Any] = {
|
||||
"vid": video_id,
|
||||
"title": (title or video_path.stem)[:1000],
|
||||
}
|
||||
if description:
|
||||
update_params["description"] = description[:4000]
|
||||
tags = build_video_tags(title, description)
|
||||
if tags:
|
||||
update_params["tags"] = tags
|
||||
if cover_path and cover_path.exists():
|
||||
cover_photo_id, cover_token = upload_video_cover(settings, cover_path)
|
||||
update_params["cover_photo_id"] = cover_photo_id
|
||||
update_params["cover_photo_upload_token"] = cover_token
|
||||
call_ok(settings, "video.update", update_params)
|
||||
return str(video_id)
|
||||
|
||||
|
||||
def upload_moment_photo(settings: Settings, image_path: Path) -> tuple[str, str]:
|
||||
upload_data = call_ok(settings, "moments.getUploadUrl", {"type": "PHOTO"})
|
||||
upload_url = upload_data.get("upload_url")
|
||||
if not upload_url:
|
||||
raise OkApiError(f"OK moment upload_url is missing: {upload_data}")
|
||||
|
||||
with image_path.open("rb") as image_file:
|
||||
files = {"pic1": (image_path.name, image_file, "image/jpeg")}
|
||||
with httpx.Client(timeout=120) as client:
|
||||
response = client.post(upload_url, files=files)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
|
||||
photos = result.get("photos")
|
||||
if isinstance(photos, dict):
|
||||
for photo_id, photo_data in photos.items():
|
||||
if isinstance(photo_data, dict) and photo_data.get("token"):
|
||||
return str(photo_id), str(photo_data["token"])
|
||||
|
||||
raise OkApiError(f"OK moment photo token is missing: {result}")
|
||||
|
||||
|
||||
def commit_group_moment(settings: Settings, photo_id: str, token: str) -> dict[str, Any]:
|
||||
if not settings.ok_group_id:
|
||||
raise OkApiError("OK_GROUP_ID is not configured")
|
||||
|
||||
photo_items = [{"photo_id": photo_id, "token": token}]
|
||||
params = {
|
||||
"photos": json.dumps(photo_items, ensure_ascii=False),
|
||||
"owner_ref": f"group:{settings.ok_group_id}",
|
||||
}
|
||||
try:
|
||||
return call_ok(settings, "moments.commit", params)
|
||||
except OkApiError:
|
||||
params["photos"] = json.dumps({"photos": photo_items}, ensure_ascii=False)
|
||||
return call_ok(settings, "moments.commit", params)
|
||||
|
||||
|
||||
def post_group_mediatopic(settings: Settings, attachment: dict[str, Any]) -> dict[str, Any]:
|
||||
if not settings.ok_group_id:
|
||||
raise OkApiError("OK_GROUP_ID is not configured")
|
||||
|
||||
return call_ok(
|
||||
settings,
|
||||
"mediatopic.post",
|
||||
{
|
||||
"type": "GROUP_THEME",
|
||||
"gid": settings.ok_group_id,
|
||||
"attachment": json.dumps(attachment, ensure_ascii=False),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def edit_mediatopic(settings: Settings, topic_id: str, attachment: dict[str, Any]) -> dict[str, Any]:
|
||||
return call_ok(
|
||||
settings,
|
||||
"mediatopic.edit",
|
||||
{
|
||||
"topic_id": topic_id,
|
||||
"attachment": json.dumps(attachment, ensure_ascii=False),
|
||||
},
|
||||
)
|
||||
51
app/routes.py
Normal file
51
app/routes.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import json
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.responses import PlainTextResponse
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import Settings, get_settings
|
||||
from app.database import get_session
|
||||
from app.models import VkEvent
|
||||
from app.worker import process_vk_event
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/webhook", response_class=PlainTextResponse)
|
||||
async def vk_webhook(
|
||||
request: Request,
|
||||
session: Session = Depends(get_session),
|
||||
settings: Settings = Depends(get_settings),
|
||||
) -> PlainTextResponse:
|
||||
payload = await request.json()
|
||||
event_type = str(payload.get("type", ""))
|
||||
group_id = str(payload.get("group_id", ""))
|
||||
|
||||
if event_type == "confirmation":
|
||||
if group_id != settings.vk_group_id:
|
||||
raise HTTPException(status_code=403, detail="Unexpected VK group")
|
||||
return PlainTextResponse(settings.vk_confirmation_code)
|
||||
|
||||
if payload.get("secret") != settings.vk_secret:
|
||||
raise HTTPException(status_code=403, detail="Invalid VK secret")
|
||||
|
||||
event = VkEvent(
|
||||
event_id=str(payload.get("event_id") or ""),
|
||||
event_type=event_type,
|
||||
group_id=group_id,
|
||||
raw_payload_json=json.dumps(payload, ensure_ascii=False),
|
||||
)
|
||||
session.add(event)
|
||||
session.commit()
|
||||
|
||||
task = process_vk_event.delay(event.id)
|
||||
event.status = "queued"
|
||||
session.commit()
|
||||
|
||||
return PlainTextResponse("ok", headers={"X-Celery-Task-Id": task.id})
|
||||
1362
app/worker.py
Normal file
1362
app/worker.py
Normal file
File diff suppressed because it is too large
Load diff
59
docker-compose.yml
Normal file
59
docker-compose.yml
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
services:
|
||||
api:
|
||||
build: .
|
||||
container_name: vk2ok-api
|
||||
restart: unless-stopped
|
||||
command: uvicorn app.main:app --host 0.0.0.0 --port 8000
|
||||
env_file: .env
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
- ./storage:/app/storage
|
||||
depends_on:
|
||||
- redis
|
||||
networks:
|
||||
- caddy
|
||||
- vk2ok_internal
|
||||
|
||||
worker:
|
||||
build: .
|
||||
container_name: vk2ok-worker
|
||||
restart: unless-stopped
|
||||
command: celery -A app.worker.celery_app worker --loglevel=info --concurrency=2
|
||||
env_file: .env
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
- ./storage:/app/storage
|
||||
depends_on:
|
||||
- redis
|
||||
networks:
|
||||
- vk2ok_internal
|
||||
|
||||
beat:
|
||||
build: .
|
||||
container_name: vk2ok-beat
|
||||
restart: unless-stopped
|
||||
command: celery -A app.worker.celery_app beat --loglevel=info
|
||||
env_file: .env
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
depends_on:
|
||||
- redis
|
||||
networks:
|
||||
- vk2ok_internal
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
container_name: vk2ok-redis
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
networks:
|
||||
- vk2ok_internal
|
||||
|
||||
volumes:
|
||||
redis_data:
|
||||
|
||||
networks:
|
||||
caddy:
|
||||
external: true
|
||||
vk2ok_internal:
|
||||
65
docs/superpowers/plans/2026-06-27-video-cleanup.md
Normal file
65
docs/superpowers/plans/2026-06-27-video-cleanup.md
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
# Video Cleanup Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Delete downloaded video artifacts after confirmed upload to OK while preserving retry files for failed uploads.
|
||||
|
||||
**Architecture:** Add a focused cleanup helper to `app/worker.py` that validates the target directory is beneath the configured VK storage root, removes that directory, and clears persisted local paths. Invoke it only after `ok_video_id` has been assigned. Cleanup errors are logged without changing the successful upload status.
|
||||
|
||||
**Tech Stack:** Python 3.12, pathlib, shutil, SQLAlchemy, Celery, Docker Compose
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add Safe Artifact Cleanup
|
||||
|
||||
**Files:**
|
||||
- Modify: `app/worker.py`
|
||||
|
||||
- [ ] **Step 1: Import directory removal support**
|
||||
|
||||
Add `import shutil` alongside the existing standard-library imports.
|
||||
|
||||
- [ ] **Step 2: Add the cleanup helper**
|
||||
|
||||
Implement a helper with this contract:
|
||||
|
||||
```python
|
||||
def cleanup_uploaded_video_artifacts(video: Video) -> None:
|
||||
video_root = (settings.storage_path / "vk").resolve()
|
||||
paths = [video.local_video_path, video.local_cover_path]
|
||||
directories = {Path(path).resolve().parent for path in paths if path}
|
||||
for directory in directories:
|
||||
if directory == video_root or video_root not in directory.parents:
|
||||
raise ValueError(f"Refusing to clean path outside video storage: {directory}")
|
||||
if directory.exists():
|
||||
shutil.rmtree(directory)
|
||||
video.local_video_path = None
|
||||
video.local_cover_path = None
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Invoke cleanup after successful upload**
|
||||
|
||||
After assigning `video.ok_video_id` and setting `video.status = "ok_uploaded"`, call the helper inside a `try/except OSError` block. Log failures and retain the successful upload status.
|
||||
|
||||
- [ ] **Step 4: Compile the worker**
|
||||
|
||||
Run: `python3 -m compileall app/worker.py`
|
||||
|
||||
Expected: `Compiling 'app/worker.py'...` with exit code 0.
|
||||
|
||||
### Task 2: Deploy and Clean Existing Successful Downloads
|
||||
|
||||
**Files:**
|
||||
- Deploy: `app/worker.py` to `/var/www/bots/vk2ok/app/worker.py`
|
||||
|
||||
- [ ] **Step 1: Rebuild services**
|
||||
|
||||
Run `docker compose up -d --build api worker beat` in `/var/www/bots/vk2ok`.
|
||||
|
||||
- [ ] **Step 2: Clean existing uploaded artifacts**
|
||||
|
||||
Inside the API container, query `Video` rows where `ok_video_id IS NOT NULL` and either local path is set. Apply `cleanup_uploaded_video_artifacts` and commit each successful cleanup.
|
||||
|
||||
- [ ] **Step 3: Verify health and storage state**
|
||||
|
||||
Confirm all containers are running, Celery recovery returns normally, uploaded rows have null local paths, and no open publication work remains.
|
||||
25
docs/superpowers/specs/2026-06-27-video-cleanup-design.md
Normal file
25
docs/superpowers/specs/2026-06-27-video-cleanup-design.md
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
# Video Cleanup Design
|
||||
|
||||
## Goal
|
||||
|
||||
Remove all local artifacts produced by `yt-dlp` after a video has been successfully uploaded to OK and an `ok_video_id` has been persisted.
|
||||
|
||||
## Behavior
|
||||
|
||||
- Cleanup runs only after the OK upload succeeds.
|
||||
- The complete per-video directory under `storage/vk/<video_id>` is removed, including the MP4, thumbnail, description, and info JSON.
|
||||
- `Video.local_video_path` and `Video.local_cover_path` are set to `None` after cleanup.
|
||||
- Failed or incomplete uploads keep their files for retry and diagnosis.
|
||||
- A cleanup failure does not turn a successful OK upload into a failed upload. It is logged and retained in `Video.error_message` for visibility.
|
||||
- Existing `ok_uploaded` videos are cleaned once during deployment using the same path-safety rules.
|
||||
|
||||
## Safety
|
||||
|
||||
Cleanup may remove only a directory resolved beneath `settings.storage_path / "vk"`. Paths outside that root are rejected. Missing files or directories are treated as already cleaned.
|
||||
|
||||
## Verification
|
||||
|
||||
- Compile the worker module.
|
||||
- Verify cleanup refuses paths outside the video storage root.
|
||||
- Verify an existing per-video directory is removed and model paths are cleared.
|
||||
- Deploy and confirm successful videos retain `ok_video_id`, have null local paths, and leave no corresponding local directory.
|
||||
33
dzen-assistant/.env.example
Normal file
33
dzen-assistant/.env.example
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
APP_ENV=production
|
||||
PUBLIC_BASE_URL=https://dzen.nstarikov.ru
|
||||
SQLITE_PATH=/app/data/dzen.sqlite3
|
||||
STORAGE_DIR=/app/data
|
||||
REDIS_URL=redis://redis:6379/0
|
||||
CELERY_BROKER_URL=redis://redis:6379/0
|
||||
CELERY_RESULT_BACKEND=redis://redis:6379/1
|
||||
|
||||
# Optional: protect admin API later at Caddy or app level.
|
||||
ADMIN_TOKEN=change-me
|
||||
|
||||
# Existing server Whisper command. The file path is appended as the last argument.
|
||||
# Leave empty to generate draft stubs until transcription is wired.
|
||||
WHISPER_COMMAND=
|
||||
|
||||
# yt-dlp cookies if VK needs auth.
|
||||
YTDLP_COOKIES_PATH=/app/data/cookies.txt
|
||||
|
||||
# VK API token for scanning the VK Video group via video.get.
|
||||
VK_API_TOKEN=
|
||||
VK_VIDEO_OWNER_ID=-9828339
|
||||
|
||||
# External OpenAI-compatible article editor agent.
|
||||
LLM_API_URL=
|
||||
LLM_API_KEY=
|
||||
LLM_MODEL=agent
|
||||
LLM_TIMEOUT_SECONDS=120
|
||||
LLM_MAX_TRANSCRIPT_CHARS=45000
|
||||
|
||||
# Processing limits.
|
||||
MAX_CONCURRENT_VIDEOS=1
|
||||
FRAME_CANDIDATES=12
|
||||
RSS_LIMIT=100
|
||||
8
dzen-assistant/.gitignore
vendored
Normal file
8
dzen-assistant/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
__pycache__/
|
||||
*.py[cod]
|
||||
.env
|
||||
data/
|
||||
storage/
|
||||
admin/node_modules/
|
||||
admin/dist/
|
||||
|
||||
548
dzen-assistant/Caddyfile.server
Normal file
548
dzen-assistant/Caddyfile.server
Normal file
|
|
@ -0,0 +1,548 @@
|
|||
{
|
||||
email admin@nstarikov.ru
|
||||
}
|
||||
|
||||
# Сниппет: блокировка SEO-ботов, AI-ботов, сканеров
|
||||
(snippet_block_bots) {
|
||||
# SEO-боты
|
||||
@seo_bots header_regexp User-Agent (?i)(AhrefsBot|SemrushBot|DotBot|MJ12bot|Baiduspider|AwarioBot|SeznamBot|Screaming.Frog|SiteAuditBot|DataForSeoBot|SerpstatBot|Uptimebot|PetalBot|ZoominfoBot|CriteoBot|trendictionbot|oBot|Sogou)
|
||||
abort @seo_bots
|
||||
|
||||
# AI-боты
|
||||
@ai_bots header_regexp User-Agent (?i)(GPTBot|ClaudeBot|Claude-Web|Amazonbot|Applebot-Extended|CCBot|PerplexityBot|YouBot|anthropic)
|
||||
abort @ai_bots
|
||||
|
||||
# Сканеры уязвимостей и скрипты
|
||||
@malicious header_regexp User-Agent (?i)(Nikto|sqlmap|masscan|zgrab|Scrapy|libwww-perl|lwp-trivial|PHP/)
|
||||
abort @malicious
|
||||
|
||||
# Python-скрейперы (не-legitimate)
|
||||
@python_scraper header_regexp User-Agent (?i)(python-requests|python-urllib|aiohttp)
|
||||
abort @python_scraper
|
||||
|
||||
# Блокировка подозрительных путей и сканеров
|
||||
@path_scan path_regexp (?i)(\.env|wp-|phpmyadmin|\.git|\.svn|\.DS_Store|xmlrpc\.php|wp-login|wp-admin|actuator|swagger|/shell\b|/cmd\b|/eval\b|/exec\b|\.asp$|\.aspx$|\.jsp$|\.php$)
|
||||
abort @path_scan
|
||||
}
|
||||
|
||||
# Сниппет: security-заголовки
|
||||
(snippet_security_headers) {
|
||||
header {
|
||||
Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
|
||||
X-Content-Type-Options "nosniff"
|
||||
X-Frame-Options "SAMEORIGIN"
|
||||
Referrer-Policy "strict-origin-when-cross-origin"
|
||||
}
|
||||
}
|
||||
|
||||
# Сниппет: логирование
|
||||
(snippet_log) {
|
||||
log {
|
||||
output file /var/log/caddy/{args[0]}.log
|
||||
}
|
||||
}
|
||||
|
||||
# Сниппет: сжатие
|
||||
(snippet_compress) {
|
||||
encode zstd gzip
|
||||
}
|
||||
|
||||
api.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log api.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
import snippet_security_headers
|
||||
|
||||
# Блокировка сканеров по пути
|
||||
@api_scan path_regexp (?i)(\.env|wp-|phpmyadmin|\.git|\.svn|\.DS_Store|xmlrpc\.php|wp-login|wp-admin|actuator|swagger|\.well-known|\.php$)
|
||||
abort @api_scan
|
||||
|
||||
# Ограничение доступа к /admin/login только с доверенного IP
|
||||
@admin_login path /admin/login /admin/login/*
|
||||
@admin_login_blocked not remote_ip 178.70.50.255
|
||||
handle @admin_login {
|
||||
@blocked not remote_ip 178.70.50.255
|
||||
respond @blocked "Forbidden" 403
|
||||
reverse_proxy directus:8055
|
||||
}
|
||||
|
||||
handle_path /stories/* {
|
||||
reverse_proxy stories-previews:8000
|
||||
}
|
||||
|
||||
handle {
|
||||
reverse_proxy directus:8055
|
||||
}
|
||||
}
|
||||
|
||||
bot.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log bot.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
# 1. Telegram Bot API (local)
|
||||
@bot_api path /bot* /file/bot*
|
||||
handle @bot_api {
|
||||
reverse_proxy crossposter_bot_api:8081
|
||||
}
|
||||
|
||||
# 2. VK Webhook (our service - uses different secret)
|
||||
@vk_webhook path /webhook/37a64119-6241-4892-a379-1fcd4a0395d9
|
||||
handle @vk_webhook {
|
||||
reverse_proxy vk2directus:8000
|
||||
}
|
||||
|
||||
# 3. Legacy webhook for crossposter
|
||||
@webhook path /webhook/*
|
||||
handle @webhook {
|
||||
reverse_proxy crossposter_bot:8000
|
||||
}
|
||||
|
||||
# VK to RuTube webhook and files proxy
|
||||
handle_path /vk2rutube/* {
|
||||
reverse_proxy vk2rutube-app:8000
|
||||
}
|
||||
|
||||
# 4. Everything else -> Forbidden
|
||||
|
||||
handle {
|
||||
respond "Forbidden" 403
|
||||
}
|
||||
}
|
||||
|
||||
comments.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log comments.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
reverse_proxy remark42:8080
|
||||
}
|
||||
|
||||
list.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log list.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
reverse_proxy listmonk:9001
|
||||
}
|
||||
|
||||
n8n.nstarikov.ru {
|
||||
import snippet_security_headers
|
||||
import snippet_log n8n.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
header -Alt-Svc
|
||||
header -Server
|
||||
|
||||
reverse_proxy nstarikov-n8n:5678 {
|
||||
transport http {
|
||||
dial_timeout 5s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
nocodb.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log nocodb.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
@private not remote_ip 178.70.50.255
|
||||
respond @private "Forbidden" 403
|
||||
|
||||
reverse_proxy nocodb:8080
|
||||
}
|
||||
|
||||
nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
# Block and return 404 for the old geopolitics path
|
||||
respond /geopolitics* "Not Found" 404
|
||||
|
||||
# Bot typing WebSocket proxy
|
||||
handle /ws/typing/* {
|
||||
reverse_proxy max-bot:8000
|
||||
}
|
||||
|
||||
# Directus WebSocket proxy
|
||||
handle /ws* {
|
||||
rewrite * /websocket
|
||||
reverse_proxy directus:8055
|
||||
}
|
||||
|
||||
# Toolsy proxy for video proxy and Yandex profile API
|
||||
handle /api/toolsy* {
|
||||
uri strip_prefix /api/toolsy
|
||||
reverse_proxy toolsy-proxy:8001
|
||||
}
|
||||
|
||||
# Catch-all reverse proxy to Astro website
|
||||
handle {
|
||||
reverse_proxy nstarikov-astro:3000
|
||||
}
|
||||
}
|
||||
|
||||
po.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log po.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
@private not remote_ip 178.70.50.255
|
||||
respond @private "Forbidden" 403
|
||||
|
||||
reverse_proxy portainer:9000
|
||||
}
|
||||
|
||||
podcast.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log podcast.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
reverse_proxy podcast.nstarikov.ru:4321
|
||||
}
|
||||
|
||||
read.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log read.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
# Блокировка сканеров уязвимостей — ищут PHP-файлы
|
||||
@php_scan path_regexp (?i)(\.php$|wp-content|wp-admin|wp-login|wordpress|wp-includes|xmlrpc\.php|wp-cron)
|
||||
abort @php_scan
|
||||
|
||||
# Блокировка подозрительных путей
|
||||
@suspicious path_regexp (?i)(\.env|\.git|\.svn|\.DS_Store|actuator|swagger|adminer|phpmyadmin|/shell|/cmd|/eval|/exec|\.asp$|\.aspx$|\.jsp$|goods\.php|\.o\.php)
|
||||
abort @suspicious
|
||||
|
||||
reverse_proxy read.astro.ru:4321
|
||||
}
|
||||
|
||||
tv.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log tv.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
reverse_proxy tv.nstarikov.ru:4321
|
||||
}
|
||||
|
||||
dcr.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log dcr.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
basic_auth {
|
||||
superadmin $2a$14$TtcPlXrL147mKF7FIHD8hOxrMhcmL.PwHT7vjgparlnr81./HqrcG
|
||||
}
|
||||
|
||||
reverse_proxy dcr-registry:5000
|
||||
}
|
||||
|
||||
bot.kseniya-hram.ru {
|
||||
import snippet_compress
|
||||
import snippet_log bot.kseniya-hram.ru
|
||||
import snippet_block_bots
|
||||
|
||||
reverse_proxy kseniyahram-bot:3000
|
||||
}
|
||||
|
||||
netdata.nstarikov.ru {
|
||||
import snippet_log netdata.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
@blocked not remote_ip 178.70.50.255
|
||||
respond @blocked "Forbidden" 403
|
||||
|
||||
reverse_proxy netdata:19999
|
||||
}
|
||||
|
||||
tv2api.bot.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log tv2api.bot.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
@vk_webhook path /webhook/37a64119-6241-4892-a379-1fcd4a0395d9
|
||||
handle @vk_webhook {
|
||||
reverse_proxy vk2directus:8000
|
||||
}
|
||||
|
||||
handle {
|
||||
respond "Not Found" 404
|
||||
}
|
||||
}
|
||||
|
||||
video2audio.bot.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log video2audio.bot.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
reverse_proxy video2audio-bot-api:8081
|
||||
}
|
||||
|
||||
vksigner.bot.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log vksigner.bot.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
# Блокировка сканеров — ищут PHP-файлы и уязвимости
|
||||
@php_scan path_regexp (?i)(\.php$|wp-content|wp-admin|wp-login|wordpress|wp-includes|xmlrpc\.php|wp-cron)
|
||||
abort @php_scan
|
||||
|
||||
# Блокировка подозрительных путей
|
||||
@suspicious path_regexp (?i)(\.env|\.git|\.svn|\.DS_Store|actuator|swagger|adminer|phpmyadmin|/shell|/cmd|/eval|/exec|\.asp$|\.aspx$|\.jsp$)
|
||||
abort @suspicious
|
||||
|
||||
reverse_proxy vk_signer_bot:8000 {
|
||||
header_up X-Real-IP {remote_host}
|
||||
header_up X-Forwarded-For {remote_host}
|
||||
header_up X-Forwarded-Proto {scheme}
|
||||
}
|
||||
}
|
||||
|
||||
vk-wall2stories.bot.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log vk-wall2stories.bot.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
reverse_proxy vk-stories-bot:8000
|
||||
}
|
||||
|
||||
getmy-id.bot.nstarikov.ru {
|
||||
import snippet_log getmy-id.bot.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
@webhook path /webhook/70c4a23a-e5ed-47ee-a60c-c67acba3ec0c
|
||||
handle @webhook {
|
||||
reverse_proxy http://getmy_id-bot:8000
|
||||
}
|
||||
|
||||
handle {
|
||||
reverse_proxy http://getmy_id-bot:8000
|
||||
}
|
||||
}
|
||||
|
||||
max.miniapps.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_security_headers
|
||||
import snippet_log max.miniapps.nstarikov.ru
|
||||
header ?Access-Control-Allow-Origin "*"
|
||||
header /index.html Cache-Control "no-cache"
|
||||
header /sw.js Cache-Control "no-cache"
|
||||
@static-js path_regexp \.js$
|
||||
@static-css path_regexp \.css$
|
||||
header @static-js Cache-Control "public, max-age=31536000, immutable"
|
||||
header @static-css Cache-Control "public, max-age=31536000, immutable"
|
||||
import snippet_block_bots
|
||||
|
||||
tls {
|
||||
issuer acme {
|
||||
email admin@nstarikov.ru
|
||||
}
|
||||
}
|
||||
|
||||
handle /api/toolsy* {
|
||||
uri strip_prefix /api/toolsy
|
||||
reverse_proxy toolsy-proxy:8001
|
||||
}
|
||||
|
||||
# Bot proxy for notifications and typing WS
|
||||
handle_path /bot* {
|
||||
reverse_proxy max-bot:8000
|
||||
}
|
||||
|
||||
handle_path /miniapp* {
|
||||
root * /var/www/gp.nstarikov.ru/miniapps/max
|
||||
@fallback {
|
||||
not file {path}
|
||||
not path_regexp \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|eot|ttf|json|map)$
|
||||
}
|
||||
rewrite @fallback /index.html
|
||||
file_server
|
||||
}
|
||||
|
||||
handle {
|
||||
root * /var/www/gp.nstarikov.ru/miniapps/max
|
||||
@fallback {
|
||||
not file {path}
|
||||
not path_regexp \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|eot|ttf|json|map)$
|
||||
}
|
||||
rewrite @fallback /index.html
|
||||
header -X-Frame-Options
|
||||
header Content-Security-Policy "frame-ancestors 'self' nstarikov.ru *.nstarikov.ru vk.com *.vk.com ok.ru *.ok.ru;"
|
||||
file_server
|
||||
}
|
||||
}
|
||||
|
||||
tg.miniapps.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_security_headers
|
||||
import snippet_log tg.miniapps.nstarikov.ru
|
||||
header ?Access-Control-Allow-Origin "*"
|
||||
header /index.html Cache-Control "no-cache"
|
||||
@static-js path_regexp \.js$
|
||||
@static-css path_regexp \.css$
|
||||
header @static-js Cache-Control "public, max-age=31536000, immutable"
|
||||
header @static-css Cache-Control "public, max-age=31536000, immutable"
|
||||
import snippet_block_bots
|
||||
|
||||
tls {
|
||||
issuer acme {
|
||||
email admin@nstarikov.ru
|
||||
}
|
||||
}
|
||||
|
||||
handle /api/toolsy* {
|
||||
uri strip_prefix /api/toolsy
|
||||
reverse_proxy toolsy-proxy:8001
|
||||
}
|
||||
|
||||
# Bot proxy for notifications and typing WS
|
||||
handle_path /bot* {
|
||||
reverse_proxy max-bot:8000
|
||||
}
|
||||
|
||||
# Telegram Bot webhook reverse proxy
|
||||
handle_path /tg-bot* {
|
||||
reverse_proxy tg-bot:8000
|
||||
}
|
||||
|
||||
handle_path /miniapps/tg* {
|
||||
root * /var/www/gp.nstarikov.ru/miniapps/telegram
|
||||
@fallback {
|
||||
not file {path}
|
||||
not path_regexp \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|eot|ttf|json|map)$
|
||||
}
|
||||
rewrite @fallback /index.html
|
||||
file_server
|
||||
}
|
||||
|
||||
handle {
|
||||
root * /var/www/gp.nstarikov.ru/miniapps/telegram
|
||||
@fallback {
|
||||
not file {path}
|
||||
not path_regexp \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|eot|ttf|json|map)$
|
||||
}
|
||||
rewrite @fallback /index.html
|
||||
header -X-Frame-Options
|
||||
header Content-Security-Policy "frame-ancestors 'self' nstarikov.ru *.nstarikov.ru vk.com *.vk.com ok.ru *.ok.ru;"
|
||||
file_server
|
||||
}
|
||||
}
|
||||
|
||||
vk.miniapps.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_security_headers
|
||||
import snippet_log vk.miniapps.nstarikov.ru
|
||||
header ?Access-Control-Allow-Origin "*"
|
||||
header /index.html Cache-Control "no-cache"
|
||||
@static-js path_regexp \.js$
|
||||
@static-css path_regexp \.css$
|
||||
header @static-js Cache-Control "public, max-age=31536000, immutable"
|
||||
header @static-css Cache-Control "public, max-age=31536000, immutable"
|
||||
import snippet_block_bots
|
||||
|
||||
tls {
|
||||
issuer acme {
|
||||
email admin@nstarikov.ru
|
||||
}
|
||||
}
|
||||
|
||||
handle /api/toolsy* {
|
||||
uri strip_prefix /api/toolsy
|
||||
reverse_proxy toolsy-proxy:8001
|
||||
}
|
||||
|
||||
# Bot proxy for notifications and typing WS
|
||||
handle_path /bot* {
|
||||
reverse_proxy max-bot:8000
|
||||
}
|
||||
|
||||
handle_path /miniapps/vk* {
|
||||
root * /var/www/gp.nstarikov.ru/miniapps/vk
|
||||
@fallback {
|
||||
not file {path}
|
||||
not path_regexp \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|eot|ttf|json|map)$
|
||||
}
|
||||
rewrite @fallback /index.html
|
||||
file_server
|
||||
}
|
||||
|
||||
handle {
|
||||
root * /var/www/gp.nstarikov.ru/miniapps/vk
|
||||
@fallback {
|
||||
not file {path}
|
||||
not path_regexp \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|eot|ttf|json|map)$
|
||||
}
|
||||
rewrite @fallback /index.html
|
||||
header -X-Frame-Options
|
||||
header Content-Security-Policy "frame-ancestors *;"
|
||||
file_server
|
||||
}
|
||||
}
|
||||
|
||||
max.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log max.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
import snippet_security_headers
|
||||
|
||||
handle /api/toolsy* {
|
||||
uri strip_prefix /api/toolsy
|
||||
reverse_proxy toolsy-proxy:8001
|
||||
}
|
||||
|
||||
handle_path /bot* {
|
||||
reverse_proxy max-bot:8000
|
||||
}
|
||||
|
||||
handle_path /miniapp* {
|
||||
root * /var/www/gp.nstarikov.ru/miniapps/max
|
||||
@fallback {
|
||||
not file {path}
|
||||
not path_regexp \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|eot|ttf|json|map)$
|
||||
}
|
||||
rewrite @fallback /index.html
|
||||
file_server
|
||||
}
|
||||
|
||||
handle {
|
||||
root * /var/www/gp.nstarikov.ru/miniapps/max
|
||||
@fallback {
|
||||
not file {path}
|
||||
not path_regexp \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|eot|ttf|json|map)$
|
||||
}
|
||||
rewrite @fallback /index.html
|
||||
file_server
|
||||
}
|
||||
}
|
||||
|
||||
vk2ok.bot.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log vk2ok.bot.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
|
||||
reverse_proxy vk2ok-api:8000
|
||||
}
|
||||
|
||||
http://dzen.nstarikov.ru {
|
||||
@zen_verify path /zen_y2a3098Zp7skRQXDYdkEOwOXFDdQsSzU7bkouM0htBECx6zgC5CCqVZRxslhhjSg.html
|
||||
respond @zen_verify "<meta name=\"zen-verification\" content=\"y2a3098Zp7skRQXDYdkEOwOXFDdQsSzU7bkouM0htBECx6zgC5CCqVZRxslhhjSg\" />" 200
|
||||
|
||||
redir https://dzen.nstarikov.ru{uri} permanent
|
||||
}
|
||||
|
||||
dzen.nstarikov.ru {
|
||||
import snippet_compress
|
||||
import snippet_log dzen.nstarikov.ru
|
||||
import snippet_block_bots
|
||||
import snippet_security_headers
|
||||
|
||||
@admin path /admin* /api*
|
||||
basic_auth @admin {
|
||||
admin $2a$14$P4L2AQE5GrhdJ9UWy2sNHuRryJarO3pReiGVVs3VGe/hX.ObQaqbO
|
||||
}
|
||||
|
||||
handle {
|
||||
reverse_proxy dzen-assistant-api:8000
|
||||
}
|
||||
}
|
||||
13
dzen-assistant/Caddyfile.snippet
Normal file
13
dzen-assistant/Caddyfile.snippet
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
dzen.nstarikov.ru {
|
||||
reverse_proxy dzen-assistant-api:8000
|
||||
}
|
||||
|
||||
# Safer production variant:
|
||||
# dzen.nstarikov.ru {
|
||||
# @admin path /admin* /api*
|
||||
# basic_auth @admin {
|
||||
# admin REPLACE_WITH_CADDY_HASHED_PASSWORD
|
||||
# }
|
||||
#
|
||||
# reverse_proxy dzen-assistant-api:8000
|
||||
# }
|
||||
87
dzen-assistant/DEPLOY.md
Normal file
87
dzen-assistant/DEPLOY.md
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
# Deploy to nstarikov server
|
||||
|
||||
Target path:
|
||||
|
||||
```bash
|
||||
/var/www/dzen.nstarikov.ru
|
||||
```
|
||||
|
||||
## 1. Copy project
|
||||
|
||||
```bash
|
||||
mkdir -p /var/www/dzen.nstarikov.ru
|
||||
cd /var/www/dzen.nstarikov.ru
|
||||
```
|
||||
|
||||
Copy the contents of this `dzen-assistant` directory there.
|
||||
|
||||
## 2. Configure environment
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
nano .env
|
||||
```
|
||||
|
||||
Important values:
|
||||
|
||||
```env
|
||||
PUBLIC_BASE_URL=https://dzen.nstarikov.ru
|
||||
WHISPER_COMMAND=
|
||||
YTDLP_COOKIES_PATH=/app/data/cookies.txt
|
||||
```
|
||||
|
||||
If VK requires an authenticated download, put cookies here:
|
||||
|
||||
```bash
|
||||
/var/www/dzen.nstarikov.ru/data/cookies.txt
|
||||
```
|
||||
|
||||
## 3. Caddy
|
||||
|
||||
Add to the existing Caddyfile:
|
||||
|
||||
```caddyfile
|
||||
dzen.nstarikov.ru {
|
||||
reverse_proxy dzen-assistant-api:8000
|
||||
}
|
||||
```
|
||||
|
||||
Safer variant for production:
|
||||
|
||||
```caddyfile
|
||||
dzen.nstarikov.ru {
|
||||
@admin path /admin* /api*
|
||||
basic_auth @admin {
|
||||
admin REPLACE_WITH_CADDY_HASHED_PASSWORD
|
||||
}
|
||||
|
||||
reverse_proxy dzen-assistant-api:8000
|
||||
}
|
||||
```
|
||||
|
||||
Make sure the app joins the external Docker network named `caddy`.
|
||||
|
||||
## 4. Start
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
## 5. Check
|
||||
|
||||
```bash
|
||||
curl -i https://dzen.nstarikov.ru/health
|
||||
curl -i https://dzen.nstarikov.ru/feed
|
||||
```
|
||||
|
||||
Admin:
|
||||
|
||||
```text
|
||||
https://dzen.nstarikov.ru/admin
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Keep `worker` concurrency at `1` while Whisper/LLM processing is local.
|
||||
- The first MVP can draft article stubs even before Whisper is wired. Add transcription and LLM generation after the RSS import test passes.
|
||||
- Admin protection should be added through Caddy basic auth, VPN, or a separate protected admin subdomain before exposing it publicly.
|
||||
26
dzen-assistant/Dockerfile
Normal file
26
dzen-assistant/Dockerfile
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
FROM node:22-alpine AS admin-build
|
||||
WORKDIR /admin
|
||||
COPY admin/package*.json ./
|
||||
RUN npm install
|
||||
COPY admin ./
|
||||
RUN npm run build
|
||||
|
||||
FROM python:3.12-slim
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ffmpeg ca-certificates curl 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 app ./app
|
||||
COPY --from=admin-build /admin/dist ./admin_dist
|
||||
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
72
dzen-assistant/README.md
Normal file
72
dzen-assistant/README.md
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
# dzen-assistant
|
||||
|
||||
Автоматизированный RSS-конвейер для Дзена:
|
||||
|
||||
- ищет новые ролики в VK/других источниках;
|
||||
- скачивает видео через `yt-dlp`;
|
||||
- транскрибирует через локальный Whisper;
|
||||
- готовит черновики статей;
|
||||
- выбирает и публикует кадры;
|
||||
- отдает RSS по `https://dzen.nstarikov.ru/feed`.
|
||||
|
||||
## Серверный путь
|
||||
|
||||
```bash
|
||||
/var/www/dzen.nstarikov.ru
|
||||
```
|
||||
|
||||
## Быстрый запуск
|
||||
|
||||
```bash
|
||||
cd /var/www/dzen.nstarikov.ru
|
||||
cp .env.example .env
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
## Caddy
|
||||
|
||||
Добавить сервис в общую Docker-сеть Caddy и прописать:
|
||||
|
||||
```caddyfile
|
||||
dzen.nstarikov.ru {
|
||||
reverse_proxy dzen-assistant-api:8000
|
||||
}
|
||||
```
|
||||
|
||||
Публичные URL:
|
||||
|
||||
- `https://dzen.nstarikov.ru/feed`
|
||||
- `https://dzen.nstarikov.ru/posts/{slug}`
|
||||
- `https://dzen.nstarikov.ru/media/{path}`
|
||||
- `https://dzen.nstarikov.ru/admin`
|
||||
|
||||
## Whisper
|
||||
|
||||
Если на сервере уже есть Whisper-команда, укажите её в `.env`:
|
||||
|
||||
```env
|
||||
WHISPER_COMMAND=/path/to/whisper --model medium --language ru --output_format txt
|
||||
```
|
||||
|
||||
Команда должна принимать путь к аудио/видео файлу последним аргументом и печатать/создавать текст.
|
||||
|
||||
## LLM-редактор
|
||||
|
||||
После Whisper воркер может отправлять транскрипт во внешний OpenAI-compatible агент:
|
||||
|
||||
```env
|
||||
LLM_API_URL=https://agent.example/v1
|
||||
LLM_API_KEY=...
|
||||
LLM_MODEL=agent
|
||||
```
|
||||
|
||||
Агент должен отвечать JSON со списком статей. Если агент временно недоступен, конвейер создаст простой
|
||||
fallback-черновик из транскрипта.
|
||||
|
||||
## MVP-поток
|
||||
|
||||
1. Добавить источники в админке.
|
||||
2. Запустить проверку источников.
|
||||
3. Обработать найденный ролик.
|
||||
4. Проверить черновик и кадры.
|
||||
5. Опубликовать статью в RSS.
|
||||
24
dzen-assistant/admin/.gitignore
vendored
Normal file
24
dzen-assistant/admin/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
7
dzen-assistant/admin/.prettierignore
Normal file
7
dzen-assistant/admin/.prettierignore
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
node_modules/
|
||||
coverage/
|
||||
.pnpm-store/
|
||||
pnpm-lock.yaml
|
||||
package-lock.json
|
||||
pnpm-lock.yaml
|
||||
yarn.lock
|
||||
11
dzen-assistant/admin/.prettierrc
Normal file
11
dzen-assistant/admin/.prettierrc
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
{
|
||||
"endOfLine": "lf",
|
||||
"semi": false,
|
||||
"singleQuote": false,
|
||||
"tabWidth": 2,
|
||||
"trailingComma": "es5",
|
||||
"printWidth": 80,
|
||||
"plugins": ["prettier-plugin-tailwindcss"],
|
||||
"tailwindStylesheet": "src/index.css",
|
||||
"tailwindFunctions": ["cn", "cva"]
|
||||
}
|
||||
21
dzen-assistant/admin/README.md
Normal file
21
dzen-assistant/admin/README.md
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
# React + TypeScript + Vite + shadcn/ui
|
||||
|
||||
This is a template for a new Vite project with React, TypeScript, and shadcn/ui.
|
||||
|
||||
## Adding components
|
||||
|
||||
To add components to your app, run the following command:
|
||||
|
||||
```bash
|
||||
npx shadcn@latest add button
|
||||
```
|
||||
|
||||
This will place the ui components in the `src/components` directory.
|
||||
|
||||
## Using components
|
||||
|
||||
To use the components in your app, import them as follows:
|
||||
|
||||
```tsx
|
||||
import { Button } from "@/components/ui/button"
|
||||
```
|
||||
21
dzen-assistant/admin/components.json
Normal file
21
dzen-assistant/admin/components.json
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "nova",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "tailwind.config.js",
|
||||
"css": "src/index.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
22
dzen-assistant/admin/eslint.config.js
Normal file
22
dzen-assistant/admin/eslint.config.js
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
13
dzen-assistant/admin/index.html
Normal file
13
dzen-assistant/admin/index.html
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Дзен-ассистент</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
2783
dzen-assistant/admin/package-lock.json
generated
Normal file
2783
dzen-assistant/admin/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
36
dzen-assistant/admin/package.json
Normal file
36
dzen-assistant/admin/package.json
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
{
|
||||
"name": "dzen-assistant-admin",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 0.0.0.0",
|
||||
"build": "tsc -p tsconfig.app.json && vite build",
|
||||
"preview": "vite preview --host 0.0.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@editorjs/editorjs": "^2.30.8",
|
||||
"@editorjs/header": "^2.8.8",
|
||||
"@editorjs/image": "^2.10.3",
|
||||
"@editorjs/list": "^1.10.0",
|
||||
"@editorjs/quote": "^2.7.6",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^0.468.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"tailwind-merge": "^2.6.0",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"vite": "^6.0.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/react": "^19.0.2",
|
||||
"@types/react-dom": "^19.0.2",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"postcss": "^8.4.49",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"typescript": "^5.7.2"
|
||||
}
|
||||
}
|
||||
7
dzen-assistant/admin/postcss.config.js
Normal file
7
dzen-assistant/admin/postcss.config.js
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
|
||||
1
dzen-assistant/admin/public/vite.svg
Normal file
1
dzen-assistant/admin/public/vite.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
1208
dzen-assistant/admin/src/App.tsx
Normal file
1208
dzen-assistant/admin/src/App.tsx
Normal file
File diff suppressed because it is too large
Load diff
1
dzen-assistant/admin/src/assets/react.svg
Normal file
1
dzen-assistant/admin/src/assets/react.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4 KiB |
230
dzen-assistant/admin/src/components/theme-provider.tsx
Normal file
230
dzen-assistant/admin/src/components/theme-provider.tsx
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
/* eslint-disable react-refresh/only-export-components */
|
||||
import * as React from "react"
|
||||
|
||||
type Theme = "dark" | "light" | "system"
|
||||
type ResolvedTheme = "dark" | "light"
|
||||
|
||||
type ThemeProviderProps = {
|
||||
children: React.ReactNode
|
||||
defaultTheme?: Theme
|
||||
storageKey?: string
|
||||
disableTransitionOnChange?: boolean
|
||||
}
|
||||
|
||||
type ThemeProviderState = {
|
||||
theme: Theme
|
||||
setTheme: (theme: Theme) => void
|
||||
}
|
||||
|
||||
const COLOR_SCHEME_QUERY = "(prefers-color-scheme: dark)"
|
||||
const THEME_VALUES: Theme[] = ["dark", "light", "system"]
|
||||
|
||||
const ThemeProviderContext = React.createContext<
|
||||
ThemeProviderState | undefined
|
||||
>(undefined)
|
||||
|
||||
function isTheme(value: string | null): value is Theme {
|
||||
if (value === null) {
|
||||
return false
|
||||
}
|
||||
|
||||
return THEME_VALUES.includes(value as Theme)
|
||||
}
|
||||
|
||||
function getSystemTheme(): ResolvedTheme {
|
||||
if (window.matchMedia(COLOR_SCHEME_QUERY).matches) {
|
||||
return "dark"
|
||||
}
|
||||
|
||||
return "light"
|
||||
}
|
||||
|
||||
function disableTransitionsTemporarily() {
|
||||
const style = document.createElement("style")
|
||||
style.appendChild(
|
||||
document.createTextNode(
|
||||
"*,*::before,*::after{-webkit-transition:none!important;transition:none!important}"
|
||||
)
|
||||
)
|
||||
document.head.appendChild(style)
|
||||
|
||||
return () => {
|
||||
window.getComputedStyle(document.body)
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
style.remove()
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function isEditableTarget(target: EventTarget | null) {
|
||||
if (!(target instanceof HTMLElement)) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (target.isContentEditable) {
|
||||
return true
|
||||
}
|
||||
|
||||
const editableParent = target.closest(
|
||||
"input, textarea, select, [contenteditable='true']"
|
||||
)
|
||||
if (editableParent) {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
export function ThemeProvider({
|
||||
children,
|
||||
defaultTheme = "system",
|
||||
storageKey = "theme",
|
||||
disableTransitionOnChange = true,
|
||||
...props
|
||||
}: ThemeProviderProps) {
|
||||
const [theme, setThemeState] = React.useState<Theme>(() => {
|
||||
const storedTheme = localStorage.getItem(storageKey)
|
||||
if (isTheme(storedTheme)) {
|
||||
return storedTheme
|
||||
}
|
||||
|
||||
return defaultTheme
|
||||
})
|
||||
|
||||
const setTheme = React.useCallback(
|
||||
(nextTheme: Theme) => {
|
||||
localStorage.setItem(storageKey, nextTheme)
|
||||
setThemeState(nextTheme)
|
||||
},
|
||||
[storageKey]
|
||||
)
|
||||
|
||||
const applyTheme = React.useCallback(
|
||||
(nextTheme: Theme) => {
|
||||
const root = document.documentElement
|
||||
const resolvedTheme =
|
||||
nextTheme === "system" ? getSystemTheme() : nextTheme
|
||||
const restoreTransitions = disableTransitionOnChange
|
||||
? disableTransitionsTemporarily()
|
||||
: null
|
||||
|
||||
root.classList.remove("light", "dark")
|
||||
root.classList.add(resolvedTheme)
|
||||
|
||||
if (restoreTransitions) {
|
||||
restoreTransitions()
|
||||
}
|
||||
},
|
||||
[disableTransitionOnChange]
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
applyTheme(theme)
|
||||
|
||||
if (theme !== "system") {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const mediaQuery = window.matchMedia(COLOR_SCHEME_QUERY)
|
||||
const handleChange = () => {
|
||||
applyTheme("system")
|
||||
}
|
||||
|
||||
mediaQuery.addEventListener("change", handleChange)
|
||||
|
||||
return () => {
|
||||
mediaQuery.removeEventListener("change", handleChange)
|
||||
}
|
||||
}, [theme, applyTheme])
|
||||
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.repeat) {
|
||||
return
|
||||
}
|
||||
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) {
|
||||
return
|
||||
}
|
||||
|
||||
if (isEditableTarget(event.target)) {
|
||||
return
|
||||
}
|
||||
|
||||
if (event.key.toLowerCase() !== "d") {
|
||||
return
|
||||
}
|
||||
|
||||
setThemeState((currentTheme) => {
|
||||
const nextTheme =
|
||||
currentTheme === "dark"
|
||||
? "light"
|
||||
: currentTheme === "light"
|
||||
? "dark"
|
||||
: getSystemTheme() === "dark"
|
||||
? "light"
|
||||
: "dark"
|
||||
|
||||
localStorage.setItem(storageKey, nextTheme)
|
||||
return nextTheme
|
||||
})
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("keydown", handleKeyDown)
|
||||
}
|
||||
}, [storageKey])
|
||||
|
||||
React.useEffect(() => {
|
||||
const handleStorageChange = (event: StorageEvent) => {
|
||||
if (event.storageArea !== localStorage) {
|
||||
return
|
||||
}
|
||||
|
||||
if (event.key !== storageKey) {
|
||||
return
|
||||
}
|
||||
|
||||
if (isTheme(event.newValue)) {
|
||||
setThemeState(event.newValue)
|
||||
return
|
||||
}
|
||||
|
||||
setThemeState(defaultTheme)
|
||||
}
|
||||
|
||||
window.addEventListener("storage", handleStorageChange)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("storage", handleStorageChange)
|
||||
}
|
||||
}, [defaultTheme, storageKey])
|
||||
|
||||
const value = React.useMemo(
|
||||
() => ({
|
||||
theme,
|
||||
setTheme,
|
||||
}),
|
||||
[theme, setTheme]
|
||||
)
|
||||
|
||||
return (
|
||||
<ThemeProviderContext.Provider {...props} value={value}>
|
||||
{children}
|
||||
</ThemeProviderContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export const useTheme = () => {
|
||||
const context = React.useContext(ThemeProviderContext)
|
||||
|
||||
if (context === undefined) {
|
||||
throw new Error("useTheme must be used within a ThemeProvider")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
30
dzen-assistant/admin/src/components/ui/badge.tsx
Normal file
30
dzen-assistant/admin/src/components/ui/badge.tsx
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
|
||||
secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
outline: "text-foreground",
|
||||
destructive: "border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
export interface BadgeProps extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {}
|
||||
|
||||
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
return <div className={cn(badgeVariants({ variant }), className)} {...props} />
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
|
||||
43
dzen-assistant/admin/src/components/ui/button.tsx
Normal file
43
dzen-assistant/admin/src/components/ui/button.tsx
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
|
||||
destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
|
||||
outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
|
||||
secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2",
|
||||
sm: "h-8 rounded-md px-3 text-xs",
|
||||
lg: "h-10 rounded-md px-8",
|
||||
icon: "size-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, ...props }, ref) => (
|
||||
<button className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />
|
||||
)
|
||||
)
|
||||
Button.displayName = "Button"
|
||||
|
||||
export { Button, buttonVariants }
|
||||
|
||||
45
dzen-assistant/admin/src/components/ui/card.tsx
Normal file
45
dzen-assistant/admin/src/components/ui/card.tsx
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("rounded-lg border bg-card text-card-foreground shadow-sm", className)} {...props} />
|
||||
)
|
||||
)
|
||||
Card.displayName = "Card"
|
||||
|
||||
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("flex flex-col gap-1.5 p-5", className)} {...props} />
|
||||
)
|
||||
)
|
||||
CardHeader.displayName = "CardHeader"
|
||||
|
||||
const CardTitle = React.forwardRef<HTMLHeadingElement, React.HTMLAttributes<HTMLHeadingElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<h3 ref={ref} className={cn("text-base font-semibold leading-none tracking-normal", className)} {...props} />
|
||||
)
|
||||
)
|
||||
CardTitle.displayName = "CardTitle"
|
||||
|
||||
const CardDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
|
||||
)
|
||||
)
|
||||
CardDescription.displayName = "CardDescription"
|
||||
|
||||
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => <div ref={ref} className={cn("p-5 pt-0", className)} {...props} />
|
||||
)
|
||||
CardContent.displayName = "CardContent"
|
||||
|
||||
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("flex items-center gap-2 p-5 pt-0", className)} {...props} />
|
||||
)
|
||||
)
|
||||
CardFooter.displayName = "CardFooter"
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
|
||||
21
dzen-assistant/admin/src/components/ui/input.tsx
Normal file
21
dzen-assistant/admin/src/components/ui/input.tsx
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
|
||||
({ className, type, ...props }, ref) => (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
)
|
||||
Input.displayName = "Input"
|
||||
|
||||
export { Input }
|
||||
|
||||
44
dzen-assistant/admin/src/components/ui/table.tsx
Normal file
44
dzen-assistant/admin/src/components/ui/table.tsx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div className="relative w-full overflow-auto">
|
||||
<table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
|
||||
</div>
|
||||
)
|
||||
)
|
||||
Table.displayName = "Table"
|
||||
|
||||
const TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
|
||||
({ className, ...props }, ref) => <thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
|
||||
)
|
||||
TableHeader.displayName = "TableHeader"
|
||||
|
||||
const TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
|
||||
({ className, ...props }, ref) => <tbody ref={ref} className={cn("[&_tr:last-child]:border-0", className)} {...props} />
|
||||
)
|
||||
TableBody.displayName = "TableBody"
|
||||
|
||||
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<tr ref={ref} className={cn("border-b transition-colors hover:bg-muted/50", className)} {...props} />
|
||||
)
|
||||
)
|
||||
TableRow.displayName = "TableRow"
|
||||
|
||||
const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<th ref={ref} className={cn("h-10 px-2 text-left align-middle font-medium text-muted-foreground", className)} {...props} />
|
||||
)
|
||||
)
|
||||
TableHead.displayName = "TableHead"
|
||||
|
||||
const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>(
|
||||
({ className, ...props }, ref) => <td ref={ref} className={cn("p-2 align-middle", className)} {...props} />
|
||||
)
|
||||
TableCell.displayName = "TableCell"
|
||||
|
||||
export { Table, TableHeader, TableBody, TableHead, TableRow, TableCell }
|
||||
|
||||
20
dzen-assistant/admin/src/components/ui/textarea.tsx
Normal file
20
dzen-assistant/admin/src/components/ui/textarea.tsx
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Textarea = React.forwardRef<HTMLTextAreaElement, React.TextareaHTMLAttributes<HTMLTextAreaElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<textarea
|
||||
className={cn(
|
||||
"flex min-h-20 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
)
|
||||
Textarea.displayName = "Textarea"
|
||||
|
||||
export { Textarea }
|
||||
|
||||
286
dzen-assistant/admin/src/index.css
Normal file
286
dzen-assistant/admin/src/index.css
Normal file
|
|
@ -0,0 +1,286 @@
|
|||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 0 0% 99%;
|
||||
--foreground: 224 13% 12%;
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 224 13% 12%;
|
||||
--primary: 11 86% 55%;
|
||||
--primary-foreground: 0 0% 100%;
|
||||
--secondary: 210 16% 93%;
|
||||
--secondary-foreground: 224 13% 12%;
|
||||
--muted: 210 16% 94%;
|
||||
--muted-foreground: 220 8% 43%;
|
||||
--accent: 210 16% 92%;
|
||||
--accent-foreground: 224 13% 12%;
|
||||
--destructive: 0 84% 60%;
|
||||
--destructive-foreground: 0 0% 100%;
|
||||
--border: 210 14% 88%;
|
||||
--input: 210 14% 88%;
|
||||
--ring: 11 86% 55%;
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
font-feature-settings: "rlig" 1, "calt" 1;
|
||||
}
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.modal-overlay {
|
||||
animation: modal-overlay-in 140ms ease-out both;
|
||||
}
|
||||
|
||||
.modal-panel {
|
||||
animation: modal-panel-in 170ms cubic-bezier(0.16, 1, 0.3, 1) both;
|
||||
transform-origin: center;
|
||||
}
|
||||
|
||||
.article-preview {
|
||||
@apply text-zinc-900;
|
||||
}
|
||||
|
||||
.article-preview > :where(p, h2, h3, ul, ol) {
|
||||
@apply mx-auto max-w-3xl;
|
||||
}
|
||||
|
||||
.article-preview p {
|
||||
@apply mt-4 text-lg leading-8;
|
||||
}
|
||||
|
||||
.article-preview h2 {
|
||||
@apply mx-auto mt-10 max-w-3xl text-3xl font-bold leading-tight tracking-normal;
|
||||
}
|
||||
|
||||
.article-preview h3 {
|
||||
@apply mx-auto mt-8 max-w-3xl text-2xl font-semibold leading-tight tracking-normal;
|
||||
}
|
||||
|
||||
.article-preview figure {
|
||||
@apply my-8 w-full;
|
||||
}
|
||||
|
||||
.article-preview img {
|
||||
@apply aspect-video w-full rounded-md border bg-muted object-cover;
|
||||
}
|
||||
|
||||
.article-preview figcaption {
|
||||
@apply mx-auto mt-2 max-w-3xl text-sm leading-6 text-muted-foreground;
|
||||
}
|
||||
|
||||
.article-preview .premium-cta {
|
||||
@apply mt-10 rounded-lg border border-amber-700 bg-zinc-950 p-6 text-zinc-50;
|
||||
}
|
||||
|
||||
.article-preview .premium-cover {
|
||||
@apply m-0 mb-8 w-full;
|
||||
}
|
||||
|
||||
.article-preview .premium-cover + h2 {
|
||||
@apply mt-8;
|
||||
}
|
||||
|
||||
.article-preview .premium-cover figcaption {
|
||||
@apply mb-6;
|
||||
}
|
||||
|
||||
.article-preview .premium-cta h2 {
|
||||
@apply mt-0 text-zinc-50;
|
||||
}
|
||||
|
||||
.article-preview .premium-cta p {
|
||||
@apply text-zinc-200;
|
||||
}
|
||||
|
||||
.article-preview .premium-cta a {
|
||||
@apply font-bold text-amber-300 underline underline-offset-4;
|
||||
}
|
||||
|
||||
.article-preview .video-embed {
|
||||
@apply mt-10 border-t pt-8;
|
||||
}
|
||||
|
||||
.article-preview .video-embed h2 {
|
||||
@apply mx-auto max-w-3xl text-3xl font-bold leading-tight tracking-normal;
|
||||
}
|
||||
|
||||
.article-preview .video-embed__frame {
|
||||
@apply mt-4 aspect-video w-full overflow-hidden rounded-md border bg-zinc-950;
|
||||
}
|
||||
|
||||
.article-preview iframe {
|
||||
@apply block h-full w-full;
|
||||
}
|
||||
|
||||
.article-preview strong {
|
||||
@apply font-semibold;
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
|
||||
.article-preview ul,
|
||||
.article-preview ol {
|
||||
@apply mt-4 pl-6 text-lg leading-8;
|
||||
}
|
||||
|
||||
.article-preview li {
|
||||
@apply mt-2;
|
||||
}
|
||||
|
||||
.article-editor {
|
||||
@apply min-h-[420px] cursor-text rounded-md outline-none transition-colors;
|
||||
}
|
||||
|
||||
.article-editor:hover {
|
||||
@apply bg-amber-50/25;
|
||||
}
|
||||
|
||||
.article-editor:focus {
|
||||
@apply bg-amber-50/40 outline-none ring-1 ring-amber-200;
|
||||
}
|
||||
|
||||
.article-editor :where(p, h2, h3, figcaption, li) {
|
||||
@apply outline-none;
|
||||
}
|
||||
|
||||
.article-editor :where(p, h2, h3, figcaption, li):focus {
|
||||
@apply rounded-sm bg-amber-50/60;
|
||||
}
|
||||
|
||||
.article-editor figure {
|
||||
@apply cursor-text;
|
||||
}
|
||||
|
||||
.article-editor img {
|
||||
@apply cursor-pointer select-auto transition-shadow;
|
||||
}
|
||||
|
||||
.article-editor img:hover {
|
||||
@apply shadow-[0_0_0_3px_rgba(245,158,11,0.25)];
|
||||
}
|
||||
|
||||
.article-editorjs {
|
||||
@apply min-h-[520px] rounded-md px-0 py-2;
|
||||
}
|
||||
|
||||
.article-editorjs .codex-editor {
|
||||
@apply text-zinc-900;
|
||||
}
|
||||
|
||||
.article-editorjs .codex-editor__redactor {
|
||||
padding-bottom: 120px !important;
|
||||
}
|
||||
|
||||
.article-editorjs .ce-block__content,
|
||||
.article-editorjs .ce-toolbar__content {
|
||||
max-width: 768px;
|
||||
}
|
||||
|
||||
.article-editorjs .ce-paragraph {
|
||||
@apply text-lg leading-8;
|
||||
}
|
||||
|
||||
.article-editorjs .ce-header {
|
||||
@apply font-bold leading-tight tracking-normal text-zinc-950;
|
||||
}
|
||||
|
||||
.article-editorjs h2.ce-header {
|
||||
@apply text-3xl;
|
||||
}
|
||||
|
||||
.article-editorjs h3.ce-header {
|
||||
@apply text-2xl;
|
||||
}
|
||||
|
||||
.article-editorjs .cdx-quote {
|
||||
@apply border-l-4 border-zinc-300 pl-5;
|
||||
}
|
||||
|
||||
.article-editorjs .cdx-quote__text {
|
||||
@apply min-h-0 text-lg italic leading-8 text-zinc-700;
|
||||
}
|
||||
|
||||
.article-editorjs .image-tool__image {
|
||||
@apply relative overflow-hidden rounded-md border bg-muted;
|
||||
}
|
||||
|
||||
.article-editorjs .image-tool__image-picture {
|
||||
@apply aspect-video w-full object-cover;
|
||||
}
|
||||
|
||||
.article-editorjs .ce-block.is-random-frame-loading .image-tool__image::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 2;
|
||||
pointer-events: none;
|
||||
background:
|
||||
linear-gradient(90deg, transparent 0%, rgb(255 255 255 / 0.42) 46%, rgb(255 255 255 / 0.72) 50%, rgb(255 255 255 / 0.42) 54%, transparent 100%),
|
||||
rgb(250 250 250 / 0.34);
|
||||
background-size: 220% 100%;
|
||||
animation: random-frame-wave 1.15s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.article-editorjs .ce-block.is-random-frame-loading .image-tool__image::before {
|
||||
content: "Подбираю кадр";
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
z-index: 3;
|
||||
transform: translate(-50%, -50%);
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgb(255 255 255 / 0.68);
|
||||
background: rgb(24 24 27 / 0.72);
|
||||
padding: 0.45rem 0.8rem;
|
||||
color: white;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
letter-spacing: 0;
|
||||
box-shadow: 0 12px 30px rgb(0 0 0 / 0.22);
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
.article-editorjs .image-tool__caption {
|
||||
@apply mx-auto mt-2 max-w-3xl border-0 px-0 text-sm leading-6 text-muted-foreground shadow-none;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes modal-overlay-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes modal-panel-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(8px) scale(0.985);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes random-frame-wave {
|
||||
from {
|
||||
background-position: 140% 0;
|
||||
}
|
||||
to {
|
||||
background-position: -80% 0;
|
||||
}
|
||||
}
|
||||
7
dzen-assistant/admin/src/lib/utils.ts
Normal file
7
dzen-assistant/admin/src/lib/utils.ts
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
11
dzen-assistant/admin/src/main.tsx
Normal file
11
dzen-assistant/admin/src/main.tsx
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import React from "react"
|
||||
import ReactDOM from "react-dom/client"
|
||||
|
||||
import App from "./App"
|
||||
import "./index.css"
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root")!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
)
|
||||
48
dzen-assistant/admin/tailwind.config.js
Normal file
48
dzen-assistant/admin/tailwind.config.js
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import animate from "tailwindcss-animate"
|
||||
|
||||
export default {
|
||||
darkMode: ["class"],
|
||||
content: ["./index.html", "./src/**/*.{ts,tsx}"],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
border: "hsl(var(--border))",
|
||||
input: "hsl(var(--input))",
|
||||
ring: "hsl(var(--ring))",
|
||||
background: "hsl(var(--background))",
|
||||
foreground: "hsl(var(--foreground))",
|
||||
primary: {
|
||||
DEFAULT: "hsl(var(--primary))",
|
||||
foreground: "hsl(var(--primary-foreground))",
|
||||
},
|
||||
secondary: {
|
||||
DEFAULT: "hsl(var(--secondary))",
|
||||
foreground: "hsl(var(--secondary-foreground))",
|
||||
},
|
||||
muted: {
|
||||
DEFAULT: "hsl(var(--muted))",
|
||||
foreground: "hsl(var(--muted-foreground))",
|
||||
},
|
||||
accent: {
|
||||
DEFAULT: "hsl(var(--accent))",
|
||||
foreground: "hsl(var(--accent-foreground))",
|
||||
},
|
||||
destructive: {
|
||||
DEFAULT: "hsl(var(--destructive))",
|
||||
foreground: "hsl(var(--destructive-foreground))",
|
||||
},
|
||||
card: {
|
||||
DEFAULT: "hsl(var(--card))",
|
||||
foreground: "hsl(var(--card-foreground))",
|
||||
},
|
||||
},
|
||||
borderRadius: {
|
||||
lg: "var(--radius)",
|
||||
md: "calc(var(--radius) - 2px)",
|
||||
sm: "calc(var(--radius) - 4px)",
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [animate],
|
||||
}
|
||||
|
||||
30
dzen-assistant/admin/tsconfig.app.json
Normal file
30
dzen-assistant/admin/tsconfig.app.json
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"baseUrl": ".",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": false,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
25
dzen-assistant/admin/tsconfig.json
Normal file
25
dzen-assistant/admin/tsconfig.json
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ES2020"],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": []
|
||||
}
|
||||
24
dzen-assistant/admin/tsconfig.node.json
Normal file
24
dzen-assistant/admin/tsconfig.node.json
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "esnext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
18
dzen-assistant/admin/vite.config.ts
Normal file
18
dzen-assistant/admin/vite.config.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import react from "@vitejs/plugin-react"
|
||||
import path from "node:path"
|
||||
import { defineConfig } from "vite"
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": path.resolve(__dirname, "./src"),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
proxy: {
|
||||
"/api": "http://localhost:8000",
|
||||
"/feed": "http://localhost:8000",
|
||||
},
|
||||
},
|
||||
})
|
||||
1
dzen-assistant/app/__init__.py
Normal file
1
dzen-assistant/app/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
|||
|
||||
94
dzen-assistant/app/captions.py
Normal file
94
dzen-assistant/app/captions.py
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import re
|
||||
from html import escape, unescape
|
||||
|
||||
|
||||
def clean_caption_text(value: str) -> str:
|
||||
text = re.sub(r"<.*?>", "", value, flags=re.S)
|
||||
text = unescape(text)
|
||||
text = re.sub(r"\s+", " ", text).strip()
|
||||
return re.sub(r"^(?:#{1,6}\s*)+", "", text).strip()
|
||||
|
||||
|
||||
def normalized_plain_text(value: str) -> str:
|
||||
return clean_caption_text(value).lower().replace("ё", "е")
|
||||
|
||||
|
||||
def strip_leading_duplicate_title(html: str, article_title: str) -> str:
|
||||
title = normalized_plain_text(article_title)
|
||||
if not html or not title:
|
||||
return html
|
||||
|
||||
def remove_if_duplicate(match: re.Match[str]) -> str:
|
||||
text = normalized_plain_text(match.group("content"))
|
||||
if text == title:
|
||||
return match.group("tail").lstrip()
|
||||
return match.group(0)
|
||||
|
||||
return re.sub(
|
||||
r"^\s*<(?P<tag>p|h1|h2|h3)\b[^>]*>(?P<content>.*?)</(?P=tag)>\s*(?P<tail>.*)$",
|
||||
remove_if_duplicate,
|
||||
html,
|
||||
count=1,
|
||||
flags=re.I | re.S,
|
||||
).strip()
|
||||
|
||||
|
||||
def normalize_heading_tags(html: str) -> str:
|
||||
def replace_heading(match: re.Match[str]) -> str:
|
||||
tag = match.group(1).lower()
|
||||
heading = clean_caption_text(match.group(2))
|
||||
return f"<{tag}>{escape(heading)}</{tag}>" if heading else ""
|
||||
|
||||
return re.sub(r"<(h[1-6])\b[^>]*>(.*?)</\1>", replace_heading, html, flags=re.I | re.S)
|
||||
|
||||
|
||||
def replace_figcaption(figure_html: str, caption: str) -> str:
|
||||
caption_html = f"<figcaption>{escape(caption)}</figcaption>"
|
||||
if re.search(r"<figcaption\b.*?</figcaption>", figure_html, flags=re.I | re.S):
|
||||
return re.sub(
|
||||
r"<figcaption\b[^>]*>.*?</figcaption>",
|
||||
caption_html,
|
||||
figure_html,
|
||||
count=1,
|
||||
flags=re.I | re.S,
|
||||
)
|
||||
return re.sub(r"</figure>", f"{caption_html}</figure>", figure_html, count=1, flags=re.I)
|
||||
|
||||
|
||||
def normalize_article_captions(html: str, article_title: str) -> str:
|
||||
title = clean_caption_text(article_title)
|
||||
if not html or not title:
|
||||
return html
|
||||
html = normalize_heading_tags(html)
|
||||
|
||||
figure_pattern = r"<figure\b[^>]*>.*?</figure>"
|
||||
|
||||
def normalize_cover(match: re.Match[str]) -> str:
|
||||
figure = match.group(0)
|
||||
if "article-cover" not in figure:
|
||||
return figure
|
||||
return replace_figcaption(figure, title)
|
||||
|
||||
html = re.sub(figure_pattern, normalize_cover, html, flags=re.I | re.S)
|
||||
|
||||
def normalize_uncaptioned_or_generic(match: re.Match[str]) -> str:
|
||||
figure = match.group(0)
|
||||
if "premium-cover" in figure:
|
||||
return figure
|
||||
return replace_figcaption(figure, title)
|
||||
|
||||
html = re.sub(figure_pattern, normalize_uncaptioned_or_generic, html, flags=re.I | re.S)
|
||||
|
||||
heading_with_figure_pattern = rf"(<h2\b[^>]*>(?P<heading>.*?)</h2>\s*)(?P<figure>{figure_pattern})"
|
||||
|
||||
def normalize_section_figure(match: re.Match[str]) -> str:
|
||||
prefix = match.group(1)
|
||||
figure = match.group("figure")
|
||||
if "premium-cover" in figure or "article-cover" in figure:
|
||||
return match.group(0)
|
||||
heading = clean_caption_text(match.group("heading"))
|
||||
if not heading:
|
||||
heading = title
|
||||
return f"{prefix}{replace_figcaption(figure, heading)}"
|
||||
|
||||
return re.sub(heading_with_figure_pattern, normalize_section_figure, html, flags=re.I | re.S)
|
||||
63
dzen-assistant/app/config.py
Normal file
63
dzen-assistant/app/config.py
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
|
||||
|
||||
app_env: str = "production"
|
||||
public_base_url: str = "https://dzen.nstarikov.ru"
|
||||
|
||||
sqlite_path: str = "/app/data/dzen.sqlite3"
|
||||
storage_dir: str = "/app/data"
|
||||
|
||||
redis_url: str = "redis://redis:6379/0"
|
||||
celery_broker_url: str = "redis://redis:6379/0"
|
||||
celery_result_backend: str = "redis://redis:6379/1"
|
||||
|
||||
admin_token: str = "change-me"
|
||||
whisper_command: str = "/LLM/Whisper/whisper --model medium --language ru --output_format txt"
|
||||
ytdlp_cookies_path: str = "/app/data/cookies.txt"
|
||||
vk_api_token: str = ""
|
||||
vk_video_owner_id: str = "-9828339"
|
||||
|
||||
llm_api_url: str = ""
|
||||
llm_api_key: str = ""
|
||||
llm_model: str = "agent"
|
||||
llm_timeout_seconds: int = 120
|
||||
llm_max_transcript_chars: int = 45000
|
||||
|
||||
max_concurrent_videos: int = 1
|
||||
frame_candidates: int = 12
|
||||
rss_limit: int = 100
|
||||
|
||||
@property
|
||||
def sqlite_url(self) -> str:
|
||||
return f"sqlite:///{self.sqlite_path}"
|
||||
|
||||
@property
|
||||
def storage_path(self) -> Path:
|
||||
return Path(self.storage_dir)
|
||||
|
||||
@property
|
||||
def media_path(self) -> Path:
|
||||
return self.storage_path / "media"
|
||||
|
||||
@property
|
||||
def videos_path(self) -> Path:
|
||||
return self.storage_path / "videos"
|
||||
|
||||
@property
|
||||
def transcripts_path(self) -> Path:
|
||||
return self.storage_path / "transcripts"
|
||||
|
||||
@property
|
||||
def posts_path(self) -> Path:
|
||||
return self.storage_path / "posts"
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
65
dzen-assistant/app/database.py
Normal file
65
dzen-assistant/app/database.py
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
from collections.abc import Generator
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import create_engine, event, text
|
||||
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
Path(settings.sqlite_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
engine = create_engine(
|
||||
settings.sqlite_url,
|
||||
connect_args={"check_same_thread": False},
|
||||
future=True,
|
||||
)
|
||||
|
||||
|
||||
@event.listens_for(engine, "connect")
|
||||
def configure_sqlite(dbapi_connection, _connection_record) -> None:
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA journal_mode=WAL")
|
||||
cursor.execute("PRAGMA busy_timeout=5000")
|
||||
cursor.execute("PRAGMA foreign_keys=ON")
|
||||
cursor.close()
|
||||
|
||||
|
||||
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False)
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
from app import models # noqa: F401
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
migrate_db()
|
||||
|
||||
|
||||
def migrate_db() -> None:
|
||||
migrations = {
|
||||
"videos": {
|
||||
"thumbnail_url": "TEXT NOT NULL DEFAULT ''",
|
||||
"progress_percent": "INTEGER NOT NULL DEFAULT 0",
|
||||
"progress_stage": "TEXT NOT NULL DEFAULT ''",
|
||||
"progress_log": "TEXT NOT NULL DEFAULT ''",
|
||||
}
|
||||
}
|
||||
with engine.begin() as connection:
|
||||
for table, columns in migrations.items():
|
||||
existing = {
|
||||
row[1]
|
||||
for row in connection.execute(text(f"PRAGMA table_info({table})")).fetchall()
|
||||
}
|
||||
for column, definition in columns.items():
|
||||
if column not in existing:
|
||||
connection.execute(text(f"ALTER TABLE {table} ADD COLUMN {column} {definition}"))
|
||||
|
||||
|
||||
def get_session() -> Generator[Session, None, None]:
|
||||
with SessionLocal() as session:
|
||||
yield session
|
||||
45
dzen-assistant/app/main.py
Normal file
45
dzen-assistant/app/main.py
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
from contextlib import asynccontextmanager
|
||||
import mimetypes
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from app.config import get_settings
|
||||
from app.database import init_db
|
||||
from app.routes import router
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
settings = get_settings()
|
||||
init_db()
|
||||
for path in [
|
||||
settings.storage_path,
|
||||
settings.media_path,
|
||||
settings.videos_path,
|
||||
settings.transcripts_path,
|
||||
settings.posts_path,
|
||||
]:
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="dzen-assistant", version="0.1.0", lifespan=lifespan)
|
||||
app.include_router(router)
|
||||
|
||||
settings = get_settings()
|
||||
mimetypes.add_type("image/webp", ".webp")
|
||||
app.mount("/media", StaticFiles(directory=settings.media_path, check_dir=False), name="media")
|
||||
app.mount("/posts-static", StaticFiles(directory=settings.posts_path, check_dir=False), name="posts-static")
|
||||
|
||||
admin_dist = Path("/app/admin_dist")
|
||||
if admin_dist.exists():
|
||||
app.mount("/assets", StaticFiles(directory=admin_dist / "assets"), name="admin-assets")
|
||||
|
||||
|
||||
@app.get("/admin")
|
||||
@app.get("/admin/{path:path}")
|
||||
def admin_index() -> FileResponse:
|
||||
return FileResponse(admin_dist / "index.html")
|
||||
81
dzen-assistant/app/models.py
Normal file
81
dzen-assistant/app/models.py
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class Source(Base):
|
||||
__tablename__ = "sources"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(160))
|
||||
url: Mapped[str] = mapped_column(Text)
|
||||
source_type: Mapped[str] = mapped_column(String(32), default="yt_dlp")
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
last_checked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
videos: Mapped[list["Video"]] = relationship(back_populates="source")
|
||||
|
||||
|
||||
class Video(Base):
|
||||
__tablename__ = "videos"
|
||||
__table_args__ = (UniqueConstraint("source_id", "external_id", name="uq_videos_source_external"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
source_id: Mapped[int | None] = mapped_column(ForeignKey("sources.id", ondelete="SET NULL"), index=True)
|
||||
external_id: Mapped[str] = mapped_column(String(256), index=True)
|
||||
source_url: Mapped[str] = mapped_column(Text)
|
||||
thumbnail_url: Mapped[str] = mapped_column(Text, default="")
|
||||
title: Mapped[str] = mapped_column(Text, default="")
|
||||
description: Mapped[str] = mapped_column(Text, default="")
|
||||
duration_seconds: Mapped[int | None] = mapped_column(Integer)
|
||||
published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
local_video_path: Mapped[str | None] = mapped_column(Text)
|
||||
transcript_path: Mapped[str | None] = mapped_column(Text)
|
||||
status: Mapped[str] = mapped_column(String(32), default="new", index=True)
|
||||
progress_percent: Mapped[int] = mapped_column(Integer, default=0)
|
||||
progress_stage: Mapped[str] = mapped_column(Text, default="")
|
||||
progress_log: Mapped[str] = mapped_column(Text, default="")
|
||||
error_message: Mapped[str | None] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||
|
||||
source: Mapped[Source | None] = relationship(back_populates="videos")
|
||||
articles: Mapped[list["Article"]] = relationship(back_populates="video")
|
||||
frames: Mapped[list["Frame"]] = relationship(back_populates="video", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class Frame(Base):
|
||||
__tablename__ = "frames"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
video_id: Mapped[int] = mapped_column(ForeignKey("videos.id", ondelete="CASCADE"), index=True)
|
||||
local_path: Mapped[str] = mapped_column(Text)
|
||||
public_url: Mapped[str | None] = mapped_column(Text)
|
||||
timestamp_seconds: Mapped[int] = mapped_column(Integer)
|
||||
score: Mapped[int] = mapped_column(Integer, default=0)
|
||||
reason: Mapped[str] = mapped_column(Text, default="")
|
||||
selected: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
video: Mapped[Video] = relationship(back_populates="frames")
|
||||
|
||||
|
||||
class Article(Base):
|
||||
__tablename__ = "articles"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
video_id: Mapped[int | None] = mapped_column(ForeignKey("videos.id", ondelete="SET NULL"), index=True)
|
||||
slug: Mapped[str] = mapped_column(String(240), unique=True, index=True)
|
||||
title: Mapped[str] = mapped_column(Text)
|
||||
lead: Mapped[str] = mapped_column(Text, default="")
|
||||
body_html: Mapped[str] = mapped_column(Text, default="")
|
||||
cta_html: 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())
|
||||
published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
video: Mapped[Video | None] = relationship(back_populates="articles")
|
||||
22
dzen-assistant/app/normalize_captions.py
Normal file
22
dzen-assistant/app/normalize_captions.py
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
from app.captions import normalize_article_captions
|
||||
from app.database import SessionLocal, init_db
|
||||
from app.models import Article
|
||||
|
||||
|
||||
def main() -> None:
|
||||
init_db()
|
||||
changed = 0
|
||||
with SessionLocal() as session:
|
||||
articles = session.query(Article).order_by(Article.id.asc()).all()
|
||||
for article in articles:
|
||||
normalized = normalize_article_captions(article.body_html or "", article.title)
|
||||
if normalized == (article.body_html or ""):
|
||||
continue
|
||||
article.body_html = normalized
|
||||
changed += 1
|
||||
session.commit()
|
||||
print(f"Updated article captions: {changed}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
32
dzen-assistant/app/quality.py
Normal file
32
dzen-assistant/app/quality.py
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import re
|
||||
|
||||
|
||||
TRANSCRIPT_PLACEHOLDERS = [
|
||||
"Транскрибация еще не подключена. Это технический черновик для проверки RSS-конвейера.",
|
||||
]
|
||||
|
||||
|
||||
def contains_transcript_placeholder(text: str | None) -> bool:
|
||||
value = text or ""
|
||||
return any(placeholder in value for placeholder in TRANSCRIPT_PLACEHOLDERS)
|
||||
|
||||
|
||||
def meaningful_text_length(text: str | None) -> int:
|
||||
value = re.sub(r"<[^>]+>", " ", text or "")
|
||||
value = re.sub(r"\s+", " ", value).strip()
|
||||
return len(value)
|
||||
|
||||
|
||||
def validate_transcript_text(text: str) -> None:
|
||||
if contains_transcript_placeholder(text):
|
||||
raise RuntimeError("Транскрибация не выполнена: найден технический placeholder вместо текста.")
|
||||
if meaningful_text_length(text) < 500:
|
||||
raise RuntimeError("Транскрибация слишком короткая для создания статьи.")
|
||||
|
||||
|
||||
def validate_article_content(title: str, lead: str, body_html: str) -> None:
|
||||
content = "\n".join([title or "", lead or "", body_html or ""])
|
||||
if contains_transcript_placeholder(content):
|
||||
raise RuntimeError("Статья содержит технический текст вместо транскрибации.")
|
||||
if meaningful_text_length((lead or "") + "\n" + (body_html or "")) < 800:
|
||||
raise RuntimeError("Статья слишком короткая для публикации в RSS.")
|
||||
45
dzen-assistant/app/reject_placeholder_articles.py
Normal file
45
dzen-assistant/app/reject_placeholder_articles.py
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
|
||||
from app.database import SessionLocal, init_db
|
||||
from app.models import Article, Video
|
||||
from app.quality import TRANSCRIPT_PLACEHOLDERS, contains_transcript_placeholder
|
||||
|
||||
|
||||
def main() -> None:
|
||||
init_db()
|
||||
changed_articles = 0
|
||||
changed_videos = 0
|
||||
now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
|
||||
with SessionLocal() as session:
|
||||
filters = []
|
||||
for placeholder in TRANSCRIPT_PLACEHOLDERS:
|
||||
pattern = f"%{placeholder}%"
|
||||
filters.extend([Article.lead.like(pattern), Article.body_html.like(pattern), Article.title.like(pattern)])
|
||||
articles = session.scalars(select(Article).where(or_(*filters)).order_by(Article.id.asc())).all()
|
||||
for article in articles:
|
||||
if not contains_transcript_placeholder("\n".join([article.title or "", article.lead or "", article.body_html or ""])):
|
||||
continue
|
||||
if article.status != "rejected":
|
||||
article.status = "rejected"
|
||||
article.published_at = None
|
||||
changed_articles += 1
|
||||
if article.video_id:
|
||||
video = session.get(Video, article.video_id)
|
||||
if video:
|
||||
video.status = "error"
|
||||
video.progress_percent = 65
|
||||
video.progress_stage = "Ошибка транскрибации"
|
||||
video.error_message = "Статья отклонена: вместо транскрибации был технический placeholder."
|
||||
video.progress_log = (video.progress_log or "") + (
|
||||
f"\n[{now}] Ошибка транскрибации: статья {article.id} отклонена из-за placeholder."
|
||||
)
|
||||
changed_videos += 1
|
||||
session.commit()
|
||||
print(f"Rejected placeholder articles: {changed_articles}")
|
||||
print(f"Marked videos as error: {changed_videos}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
856
dzen-assistant/app/routes.py
Normal file
856
dzen-assistant/app/routes.py
Normal file
|
|
@ -0,0 +1,856 @@
|
|||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from html import escape, unescape
|
||||
from html.parser import HTMLParser
|
||||
import os
|
||||
from pathlib import Path
|
||||
import random
|
||||
import re
|
||||
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 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.database import SessionLocal, get_session
|
||||
from app.models import 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
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
ZEN_VERIFICATION_FILE = "zen_y2a3098Zp7skRQXDYdkEOwOXFDdQsSzU7bkouMOhtBECx6zgC5CCqVZRxslhhjSg.html"
|
||||
ZEN_VERIFICATION_FILE_LOWER = "zen_y2a3098zp7skrqxdydkeowoxfddqsszu7bkoumohtbecx6zgc5ccqvzrxslhhjsg.html"
|
||||
ZEN_VERIFICATION_FILE_LEGACY = "zen_y2a3098Zp7skRQXDYdkEOwOXFDdQsSzU7bkouM0htBECx6zgC5CCqVZRxslhhjSg.html"
|
||||
ZEN_VERIFICATION_META = (
|
||||
'<meta name="zen-verification" '
|
||||
'content="y2a3098Zp7skRQXDYdkEOwOXFDdQsSzU7bkouMOhtBECx6zgC5CCqVZRxslhhjSg" />'
|
||||
)
|
||||
|
||||
|
||||
class SourceIn(BaseModel):
|
||||
name: str
|
||||
url: str
|
||||
source_type: str = "yt_dlp"
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class ChatIn(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
class ArticleUpdateIn(BaseModel):
|
||||
title: str
|
||||
editableHtml: str
|
||||
|
||||
|
||||
class ArticlePublishIn(BaseModel):
|
||||
publishedAt: datetime | None = None
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@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")
|
||||
|
||||
|
||||
@router.head("/feed")
|
||||
def feed_head(session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> Response:
|
||||
content = build_feed_xml(session, settings).encode("utf-8")
|
||||
return Response(
|
||||
headers={"Content-Length": str(len(content))},
|
||||
media_type="application/rss+xml; charset=utf-8",
|
||||
)
|
||||
|
||||
|
||||
@router.get("/robots.txt")
|
||||
def robots_txt(settings: Settings = Depends(get_settings)) -> Response:
|
||||
content = f"""User-agent: *
|
||||
Allow: /
|
||||
Allow: /feed
|
||||
|
||||
Sitemap: {settings.public_base_url.rstrip("/")}/feed
|
||||
"""
|
||||
return Response(content, media_type="text/plain; charset=utf-8")
|
||||
|
||||
|
||||
@router.head("/robots.txt")
|
||||
def robots_txt_head(settings: Settings = Depends(get_settings)) -> Response:
|
||||
content = f"""User-agent: *
|
||||
Allow: /
|
||||
Allow: /feed
|
||||
|
||||
Sitemap: {settings.public_base_url.rstrip("/")}/feed
|
||||
""".encode("utf-8")
|
||||
return Response(headers={"Content-Length": str(len(content))}, media_type="text/plain; charset=utf-8")
|
||||
|
||||
|
||||
def plain_excerpt(html: str, limit: int = 260) -> str:
|
||||
text = re.sub(r"<[^>]+>", " ", html)
|
||||
text = re.sub(r"\s+", " ", unescape(text)).strip()
|
||||
if len(text) <= limit:
|
||||
return text
|
||||
return text[:limit].rsplit(" ", 1)[0].strip() + "..."
|
||||
|
||||
|
||||
class ArticleHtmlSanitizer(HTMLParser):
|
||||
allowed_tags = {
|
||||
"p",
|
||||
"br",
|
||||
"h2",
|
||||
"h3",
|
||||
"strong",
|
||||
"b",
|
||||
"em",
|
||||
"i",
|
||||
"u",
|
||||
"s",
|
||||
"ul",
|
||||
"ol",
|
||||
"li",
|
||||
"blockquote",
|
||||
"figure",
|
||||
"figcaption",
|
||||
"img",
|
||||
"a",
|
||||
}
|
||||
void_tags = {"br", "img"}
|
||||
allowed_attrs = {
|
||||
"a": {"href", "title"},
|
||||
"img": {"src", "alt"},
|
||||
}
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(convert_charrefs=False)
|
||||
self.parts: list[str] = []
|
||||
self.skip_depth = 0
|
||||
|
||||
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||
tag = tag.lower()
|
||||
if tag in {"script", "style", "iframe", "object", "embed"}:
|
||||
self.skip_depth += 1
|
||||
return
|
||||
if self.skip_depth or tag not in self.allowed_tags:
|
||||
return
|
||||
clean_attrs: list[str] = []
|
||||
for name, value in attrs:
|
||||
name = name.lower()
|
||||
if value is None or name not in self.allowed_attrs.get(tag, set()):
|
||||
continue
|
||||
value = value.strip()
|
||||
if name in {"href", "src"} and not re.match(r"^(https?://|/media/)", value, flags=re.I):
|
||||
continue
|
||||
clean_attrs.append(f'{name}="{escape(value, quote=True)}"')
|
||||
attr_text = f" {' '.join(clean_attrs)}" if clean_attrs else ""
|
||||
self.parts.append(f"<{tag}{attr_text}>")
|
||||
|
||||
def handle_endtag(self, tag: str) -> None:
|
||||
tag = tag.lower()
|
||||
if tag in {"script", "style", "iframe", "object", "embed"} and self.skip_depth:
|
||||
self.skip_depth -= 1
|
||||
return
|
||||
if self.skip_depth or tag not in self.allowed_tags or tag in self.void_tags:
|
||||
return
|
||||
self.parts.append(f"</{tag}>")
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
if not self.skip_depth:
|
||||
self.parts.append(escape(data))
|
||||
|
||||
def handle_entityref(self, name: str) -> None:
|
||||
if not self.skip_depth:
|
||||
self.parts.append(f"&{name};")
|
||||
|
||||
def handle_charref(self, name: str) -> None:
|
||||
if not self.skip_depth:
|
||||
self.parts.append(f"&#{name};")
|
||||
|
||||
|
||||
def sanitize_article_editor_html(html: str) -> str:
|
||||
sanitizer = ArticleHtmlSanitizer()
|
||||
sanitizer.feed(html)
|
||||
sanitized = "".join(sanitizer.parts)
|
||||
sanitized = re.sub(r"<p>\s*</p>", "", sanitized)
|
||||
sanitized = re.sub(r"\n{3,}", "\n\n", sanitized).strip()
|
||||
return sanitized
|
||||
|
||||
|
||||
def editable_article_html(article: Article) -> str:
|
||||
html = "\n".join(part for part in [article.lead, article.body_html] if part).strip()
|
||||
return strip_leading_duplicate_title(html, article.title)
|
||||
|
||||
|
||||
def split_lead_and_body(html: str) -> tuple[str, str]:
|
||||
match = re.match(r"\s*(<p\b[^>]*>.*?</p>)(.*)\s*$", html, flags=re.I | re.S)
|
||||
if not match:
|
||||
return "", html.strip()
|
||||
return match.group(1).strip(), match.group(2).strip()
|
||||
|
||||
|
||||
def article_cover_url(session: Session, article: Article) -> str | None:
|
||||
if article.video and article.video.thumbnail_url:
|
||||
return article.video.thumbnail_url
|
||||
if not article.video_id:
|
||||
return None
|
||||
frame = session.scalar(
|
||||
select(Frame)
|
||||
.where(Frame.video_id == article.video_id, Frame.selected == True) # noqa: E712
|
||||
.order_by(Frame.score.desc(), Frame.id.asc())
|
||||
.limit(1)
|
||||
)
|
||||
return frame.public_url if frame else None
|
||||
|
||||
|
||||
def local_video_file(video: Video, settings: Settings) -> Path | None:
|
||||
if video.local_video_path:
|
||||
path = Path(video.local_video_path)
|
||||
if path.exists():
|
||||
return path
|
||||
video_dir = settings.videos_path / str(video.id)
|
||||
for candidate in sorted(video_dir.glob("video.*")):
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def create_random_frame(video: Video, settings: Settings) -> tuple[Path, str, int]:
|
||||
video_path = local_video_file(video, settings)
|
||||
if not video_path:
|
||||
raise HTTPException(status_code=422, detail="Локальный видеофайл еще не найден. Сначала обработайте ролик.")
|
||||
duration = max(1, video.duration_seconds or 60)
|
||||
start = 2 if duration > 6 else 0
|
||||
end = max(start, duration - 2)
|
||||
timestamp = random.randint(start, end)
|
||||
target_dir = settings.media_path / "videos" / str(video.id) / "manual"
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = target_dir / f"frame-{timestamp}-{uuid4().hex[:8]}.webp"
|
||||
command = [
|
||||
"ffmpeg",
|
||||
"-y",
|
||||
"-ss",
|
||||
str(timestamp),
|
||||
"-i",
|
||||
str(video_path),
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-vf",
|
||||
"scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2",
|
||||
"-c:v",
|
||||
"libwebp",
|
||||
"-quality",
|
||||
"84",
|
||||
str(target),
|
||||
]
|
||||
result = subprocess.run(command, text=True, capture_output=True)
|
||||
if result.returncode or not target.exists():
|
||||
detail = (result.stderr or result.stdout or "ffmpeg не смог создать кадр").strip()
|
||||
raise HTTPException(status_code=500, detail=detail[-1200:])
|
||||
public_url = f"{settings.public_base_url.rstrip('/')}/media/videos/{video.id}/manual/{target.name}"
|
||||
return target, public_url, timestamp
|
||||
|
||||
|
||||
@router.get(f"/{ZEN_VERIFICATION_FILE}", response_class=HTMLResponse)
|
||||
@router.get(f"/{ZEN_VERIFICATION_FILE_LOWER}", response_class=HTMLResponse)
|
||||
@router.get(f"/{ZEN_VERIFICATION_FILE_LEGACY}", response_class=HTMLResponse)
|
||||
def zen_verification() -> str:
|
||||
return ZEN_VERIFICATION_META
|
||||
|
||||
|
||||
@router.head(f"/{ZEN_VERIFICATION_FILE}")
|
||||
@router.head(f"/{ZEN_VERIFICATION_FILE_LOWER}")
|
||||
@router.head(f"/{ZEN_VERIFICATION_FILE_LEGACY}")
|
||||
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.head("/")
|
||||
def home_head() -> Response:
|
||||
return Response(media_type="text/html; charset=utf-8")
|
||||
|
||||
|
||||
@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.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")
|
||||
|
||||
|
||||
@router.get("/api/dashboard")
|
||||
def dashboard(session: Session = Depends(get_session)) -> dict:
|
||||
now = datetime.now(timezone.utc)
|
||||
return {
|
||||
"sources": session.scalar(select(func.count(Source.id))),
|
||||
"videos": session.scalar(select(func.count(Video.id)).where(Video.status != "ignored")),
|
||||
"newVideos": session.scalar(select(func.count(Video.id)).where(Video.status == "new")),
|
||||
"processingVideos": session.scalar(select(func.count(Video.id)).where(Video.status.in_(["queued", "processing"]))),
|
||||
"drafts": session.scalar(select(func.count(Article.id)).where(Article.status == "draft")),
|
||||
"scheduled": session.scalar(select(func.count(Article.id)).where(Article.status == "published", Article.published_at > now)),
|
||||
"published": session.scalar(
|
||||
select(func.count(Article.id)).where(
|
||||
Article.status == "published",
|
||||
Article.published_at.is_not(None),
|
||||
Article.published_at <= now,
|
||||
)
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/sources")
|
||||
def list_sources(session: Session = Depends(get_session)) -> list[dict]:
|
||||
sources = session.scalars(select(Source).order_by(Source.id.desc())).all()
|
||||
return [
|
||||
{
|
||||
"id": source.id,
|
||||
"name": source.name,
|
||||
"url": source.url,
|
||||
"sourceType": source.source_type,
|
||||
"enabled": source.enabled,
|
||||
"lastCheckedAt": source.last_checked_at,
|
||||
}
|
||||
for source in sources
|
||||
]
|
||||
|
||||
|
||||
@router.post("/api/sources")
|
||||
def create_source(payload: SourceIn, session: Session = Depends(get_session)) -> dict:
|
||||
source = Source(
|
||||
name=payload.name,
|
||||
url=payload.url,
|
||||
source_type=payload.source_type,
|
||||
enabled=payload.enabled,
|
||||
)
|
||||
session.add(source)
|
||||
session.commit()
|
||||
return {"id": source.id}
|
||||
|
||||
|
||||
@router.post("/api/sources/scan")
|
||||
def scan_all_sources() -> dict[str, str]:
|
||||
task = scan_sources.delay()
|
||||
return {"taskId": task.id}
|
||||
|
||||
|
||||
@router.get("/api/videos")
|
||||
def list_videos(session: Session = Depends(get_session)) -> list[dict]:
|
||||
videos = session.scalars(
|
||||
select(Video)
|
||||
.where(Video.status != "ignored")
|
||||
.order_by(func.coalesce(Video.published_at, Video.created_at).desc(), Video.id.desc())
|
||||
.limit(200)
|
||||
).all()
|
||||
return [
|
||||
{
|
||||
"id": video.id,
|
||||
"title": video.title,
|
||||
"sourceUrl": video.source_url,
|
||||
"status": video.status,
|
||||
"progressPercent": video.progress_percent,
|
||||
"progressStage": video.progress_stage,
|
||||
"durationSeconds": video.duration_seconds,
|
||||
"createdAt": video.created_at,
|
||||
"publishedAt": video.published_at,
|
||||
"errorMessage": video.error_message,
|
||||
"articleIds": [article.id for article in video.articles if article.status != "rejected"],
|
||||
"articles": [
|
||||
{
|
||||
"id": article.id,
|
||||
"title": article.title,
|
||||
"status": article.status,
|
||||
}
|
||||
for article in video.articles
|
||||
if article.status != "rejected"
|
||||
],
|
||||
}
|
||||
for video in videos
|
||||
]
|
||||
|
||||
|
||||
@router.post("/api/videos/{video_id}/process")
|
||||
def process_video_route(video_id: int) -> 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")
|
||||
was_active = video.status in {"queued", "processing"}
|
||||
video.status = "queued"
|
||||
video.progress_percent = 1
|
||||
video.progress_stage = "В очереди"
|
||||
action = "задача перезапущена" if was_active else "задача поставлена в обработку"
|
||||
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)
|
||||
return {"taskId": task.id}
|
||||
|
||||
|
||||
@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)
|
||||
if not video:
|
||||
raise HTTPException(status_code=404, detail="Video not found")
|
||||
video.status = "ignored"
|
||||
video.progress_percent = 0
|
||||
video.progress_stage = "Удалено"
|
||||
video.error_message = None
|
||||
video.progress_log = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}] Удалено: ролик исключен из обработки и повторного импорта"
|
||||
for article in video.articles:
|
||||
if article.status != "published":
|
||||
article.status = "rejected"
|
||||
session.commit()
|
||||
return {"id": video.id, "status": video.status}
|
||||
|
||||
|
||||
def delete_source_video_file(video: Video | None) -> None:
|
||||
if not video or not video.local_video_path:
|
||||
return
|
||||
path = Path(video.local_video_path)
|
||||
if path.exists() and path.is_file():
|
||||
path.unlink()
|
||||
video.local_video_path = None
|
||||
|
||||
|
||||
def video_log_payload(video: Video) -> dict[str, str | int | None]:
|
||||
return {
|
||||
"id": video.id,
|
||||
"title": video.title,
|
||||
"status": video.status,
|
||||
"progressPercent": video.progress_percent,
|
||||
"progressStage": video.progress_stage,
|
||||
"progressLog": video.progress_log or "",
|
||||
"errorMessage": video.error_message,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/videos/{video_id}/logs")
|
||||
def video_logs(video_id: int, session: Session = Depends(get_session)) -> dict[str, str | int | None]:
|
||||
video = session.get(Video, video_id)
|
||||
if not video:
|
||||
raise HTTPException(status_code=404, detail="Video not found")
|
||||
return video_log_payload(video)
|
||||
|
||||
|
||||
@router.websocket("/api/videos/{video_id}/logs/ws")
|
||||
async def video_logs_ws(websocket: WebSocket, video_id: int) -> None:
|
||||
await websocket.accept()
|
||||
last_payload: dict[str, str | int | None] | None = None
|
||||
try:
|
||||
while True:
|
||||
with SessionLocal() as session:
|
||||
video = session.get(Video, video_id)
|
||||
if not video:
|
||||
await websocket.send_json({"errorMessage": "Video not found", "status": "error"})
|
||||
await websocket.close(code=1008)
|
||||
return
|
||||
payload = video_log_payload(video)
|
||||
if payload != last_payload:
|
||||
await websocket.send_json(payload)
|
||||
last_payload = payload
|
||||
await asyncio.sleep(1)
|
||||
except WebSocketDisconnect:
|
||||
return
|
||||
|
||||
|
||||
@router.get("/api/articles")
|
||||
def list_articles(
|
||||
status: str | None = Query(default=None),
|
||||
limit: int = Query(default=10, ge=1, le=50),
|
||||
offset: int = Query(default=0, ge=0),
|
||||
session: Session = Depends(get_session),
|
||||
settings: Settings = Depends(get_settings),
|
||||
) -> dict:
|
||||
filters = [Article.status != "rejected"]
|
||||
if status:
|
||||
filters.append(Article.status == status)
|
||||
total = session.scalar(select(func.count(Article.id)).where(*filters)) or 0
|
||||
articles = session.scalars(
|
||||
select(Article)
|
||||
.where(*filters)
|
||||
.order_by(func.coalesce(Article.published_at, Article.created_at).desc(), Article.id.desc())
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
).all()
|
||||
items = [
|
||||
{
|
||||
"id": article.id,
|
||||
"title": article.title,
|
||||
"slug": article.slug,
|
||||
"status": article.status,
|
||||
"url": article_url(settings, article),
|
||||
"createdAt": article.created_at,
|
||||
"publishedAt": article.published_at,
|
||||
}
|
||||
for article in articles
|
||||
]
|
||||
return {"items": items, "total": total, "limit": limit, "offset": offset, "hasMore": offset + len(items) < total}
|
||||
|
||||
|
||||
@router.get("/api/articles/{article_id}")
|
||||
def get_article(article_id: int, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict:
|
||||
article = session.get(Article, article_id)
|
||||
if not article:
|
||||
raise HTTPException(status_code=404, detail="Article not found")
|
||||
return {
|
||||
"id": article.id,
|
||||
"title": article.title,
|
||||
"slug": article.slug,
|
||||
"status": article.status,
|
||||
"videoId": article.video_id,
|
||||
"url": article_url(settings, article),
|
||||
"createdAt": article.created_at,
|
||||
"publishedAt": article.published_at,
|
||||
"contentHtml": render_article_html(article),
|
||||
"editableHtml": editable_article_html(article),
|
||||
}
|
||||
|
||||
|
||||
@router.patch("/api/articles/{article_id}")
|
||||
def update_article(article_id: int, payload: ArticleUpdateIn, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict:
|
||||
article = session.get(Article, article_id)
|
||||
if not article:
|
||||
raise HTTPException(status_code=404, detail="Article not found")
|
||||
title = payload.title.strip()
|
||||
body = sanitize_article_editor_html(payload.editableHtml)
|
||||
body = strip_leading_duplicate_title(body, title)
|
||||
if not title:
|
||||
raise HTTPException(status_code=422, detail="Title is required")
|
||||
lead, body_html = split_lead_and_body(body)
|
||||
try:
|
||||
validate_article_content(title, lead, body_html)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
article.title = title
|
||||
article.lead = lead
|
||||
article.body_html = body_html
|
||||
session.commit()
|
||||
session.refresh(article)
|
||||
return {
|
||||
"id": article.id,
|
||||
"title": article.title,
|
||||
"slug": article.slug,
|
||||
"status": article.status,
|
||||
"videoId": article.video_id,
|
||||
"url": article_url(settings, article),
|
||||
"createdAt": article.created_at,
|
||||
"publishedAt": article.published_at,
|
||||
"contentHtml": render_article_html(article),
|
||||
"editableHtml": editable_article_html(article),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/articles/{article_id}/random-frame")
|
||||
def random_article_frame(article_id: int, session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> dict[str, str | int]:
|
||||
article = session.get(Article, article_id)
|
||||
if not article:
|
||||
raise HTTPException(status_code=404, detail="Article not found")
|
||||
if not article.video:
|
||||
raise HTTPException(status_code=422, detail="У статьи нет исходного видео.")
|
||||
path, public_url, timestamp = create_random_frame(article.video, settings)
|
||||
frame = Frame(
|
||||
video_id=article.video.id,
|
||||
local_path=str(path),
|
||||
public_url=public_url,
|
||||
timestamp_seconds=timestamp,
|
||||
score=1,
|
||||
reason="Кадр выбран вручную редактором через случайную замену в админке.",
|
||||
selected=False,
|
||||
)
|
||||
session.add(frame)
|
||||
session.commit()
|
||||
return {
|
||||
"url": public_url,
|
||||
"timestampSeconds": timestamp,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/api/articles/{article_id}")
|
||||
def delete_article(article_id: int, session: Session = Depends(get_session)) -> dict[str, str | int]:
|
||||
article = session.get(Article, article_id)
|
||||
if not article:
|
||||
raise HTTPException(status_code=404, detail="Article not found")
|
||||
article.status = "rejected"
|
||||
article.published_at = None
|
||||
article.rss_guid = None
|
||||
session.commit()
|
||||
return {"id": article.id, "status": "deleted"}
|
||||
|
||||
|
||||
@router.post("/api/uploads/images")
|
||||
async def upload_image(file: UploadFile = File(...), settings: Settings = Depends(get_settings)) -> dict[str, str]:
|
||||
if not file.content_type or not file.content_type.startswith("image/"):
|
||||
raise HTTPException(status_code=422, detail="Only image files are supported")
|
||||
suffix = Path(file.filename or "").suffix.lower()
|
||||
if suffix not in {".jpg", ".jpeg", ".png", ".webp", ".gif"}:
|
||||
suffix = ".jpg"
|
||||
date_dir = datetime.now(timezone.utc).strftime("%Y%m%d")
|
||||
upload_dir = settings.media_path / "uploads" / date_dir
|
||||
upload_dir.mkdir(parents=True, exist_ok=True)
|
||||
filename = f"{uuid4().hex}{suffix}"
|
||||
target = upload_dir / filename
|
||||
size = 0
|
||||
with target.open("wb") as output:
|
||||
while chunk := await file.read(1024 * 1024):
|
||||
size += len(chunk)
|
||||
if size > 12 * 1024 * 1024:
|
||||
output.close()
|
||||
target.unlink(missing_ok=True)
|
||||
raise HTTPException(status_code=413, detail="Image is too large")
|
||||
output.write(chunk)
|
||||
os.chmod(target, 0o644)
|
||||
return {"url": f"{settings.public_base_url.rstrip('/')}/media/uploads/{date_dir}/{filename}"}
|
||||
|
||||
|
||||
@router.post("/api/articles/{article_id}/publish")
|
||||
def publish_article(
|
||||
article_id: int,
|
||||
payload: ArticlePublishIn | None = Body(default=None),
|
||||
session: Session = Depends(get_session),
|
||||
settings: Settings = Depends(get_settings),
|
||||
) -> dict:
|
||||
article = session.get(Article, article_id)
|
||||
if not article:
|
||||
raise HTTPException(status_code=404, detail="Article not found")
|
||||
try:
|
||||
validate_article_content(article.title, article.lead, article.body_html)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
published_at = payload.publishedAt if payload and payload.publishedAt else datetime.now(timezone.utc)
|
||||
if published_at.tzinfo is None:
|
||||
published_at = published_at.replace(tzinfo=timezone.utc)
|
||||
published_at = published_at.astimezone(timezone.utc)
|
||||
article.status = "published"
|
||||
article.published_at = published_at
|
||||
article.rss_guid = f"{article_url(settings, article)}?rss_guid={int(published_at.timestamp())}-{article.id}"
|
||||
delete_source_video_file(article.video)
|
||||
session.commit()
|
||||
return {"status": "published", "url": article_url(settings, article), "publishedAt": article.published_at}
|
||||
|
||||
|
||||
@router.post("/api/chat")
|
||||
def chat(payload: ChatIn) -> dict[str, str]:
|
||||
text = payload.message.strip().lower()
|
||||
if "скан" in text or "проверь" in text:
|
||||
task = scan_sources.delay()
|
||||
return {"message": f"Запустил проверку источников. Task: {task.id}"}
|
||||
return {
|
||||
"message": "Я пока MVP-ассистент: умею запускать проверку источников, показывать ролики, черновики и публиковать статьи в RSS.",
|
||||
}
|
||||
218
dzen-assistant/app/rss.py
Normal file
218
dzen-assistant/app/rss.py
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
from datetime import datetime, timezone
|
||||
from html import escape
|
||||
import re
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.captions import strip_leading_duplicate_title
|
||||
from app.config import Settings
|
||||
from app.models import Article, Frame
|
||||
|
||||
|
||||
def rfc822(dt: datetime | None) -> str:
|
||||
value = dt or datetime.now(timezone.utc)
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.strftime("%a, %d %b %Y %H:%M:%S %z")
|
||||
|
||||
|
||||
def article_url(settings: Settings, article: Article) -> str:
|
||||
return f"{settings.public_base_url.rstrip('/')}/posts/{article.slug}"
|
||||
|
||||
|
||||
def image_mime_type(url: str) -> str:
|
||||
if url.lower().split("?", 1)[0].endswith(".webp"):
|
||||
return "image/webp"
|
||||
if url.lower().split("?", 1)[0].endswith(".png"):
|
||||
return "image/png"
|
||||
return "image/jpeg"
|
||||
|
||||
|
||||
def vk_video_embed_url(source_url: str) -> str | None:
|
||||
match = re.search(r"video(-?\d+)_(\d+)(?:_([A-Za-z0-9]+))?", source_url)
|
||||
if not match:
|
||||
return None
|
||||
owner_id, video_id, access_hash = match.groups()
|
||||
params = {
|
||||
"oid": owner_id,
|
||||
"id": video_id,
|
||||
"hd": "3",
|
||||
}
|
||||
if access_hash:
|
||||
params["hash"] = access_hash
|
||||
return f"https://vkvideo.ru/video_ext.php?{urlencode(params)}"
|
||||
|
||||
|
||||
def video_embed_html(article: Article, rss_safe: bool = False) -> str:
|
||||
if not article.video or not article.video.source_url:
|
||||
return ""
|
||||
embed_url = vk_video_embed_url(article.video.source_url)
|
||||
if rss_safe:
|
||||
iframe = ""
|
||||
if embed_url:
|
||||
iframe = (
|
||||
f'<p><iframe src="{escape(embed_url)}" width="1280" height="720" '
|
||||
'allow="autoplay; encrypted-media; fullscreen; picture-in-picture; screen-wake-lock;" '
|
||||
'frameborder="0" allowfullscreen></iframe></p>'
|
||||
)
|
||||
return f"""
|
||||
<h2>Смотреть видео</h2>
|
||||
{iframe}
|
||||
<p><a href="{escape(article.video.source_url)}">Смотреть исходное видео VK Видео</a></p>""".strip()
|
||||
if not embed_url:
|
||||
return ""
|
||||
title = escape(f"Видео: {article.title}")
|
||||
return f"""
|
||||
<section class="video-embed">
|
||||
<h2>Смотреть видео</h2>
|
||||
<div class="video-embed__frame">
|
||||
<iframe src="{escape(embed_url)}" title="{title}" width="1280" height="720" allow="autoplay; encrypted-media; fullscreen; picture-in-picture; screen-wake-lock;" frameborder="0" allowfullscreen></iframe>
|
||||
</div>
|
||||
</section>""".strip()
|
||||
|
||||
|
||||
def premium_cta_html() -> str:
|
||||
return """
|
||||
<section class="premium-cta">
|
||||
<figure class="premium-cover"><img src="https://dzen.nstarikov.ru/media/site/dzen-premium-cover.webp" alt="Школа Геополитики Николая Старикова в Дзене Премиум"></figure>
|
||||
<h2>Больше материалов в Дзене Премиум</h2>
|
||||
<p>В премиум-разделе канала Николая Старикова уже доступно более 120 закрытых материалов: лекции, разборы и публикации, которые не выходят в общей ленте.</p>
|
||||
<p>Раздел регулярно обновляется. Подписка открывает доступ к новым премиум-материалам и архиву уже опубликованных выпусков.</p>
|
||||
<p><a href="https://dzen.ru/nstarikovru?tab=premium">Перейти в Дзен Премиум</a></p>
|
||||
</section>""".strip()
|
||||
|
||||
|
||||
def premium_cta_rss_html() -> str:
|
||||
return """
|
||||
<h2>Школа Геополитики в Дзене Премиум</h2>
|
||||
<figure style="margin-bottom: 28px;"><img src="https://dzen.nstarikov.ru/media/site/dzen-premium-cover.webp" alt="Школа Геополитики Николая Старикова в Дзене Премиум"><figcaption style="margin-bottom: 24px;">Школа Геополитики Николая Старикова в Дзене Премиум</figcaption></figure>
|
||||
<p>В премиум-разделе канала Николая Старикова уже доступно более 120 материалов: лекции, разборы и публикации, которые не выходят в общей ленте.</p>
|
||||
<p>Раздел регулярно обновляется. Подписка открывает доступ к новым премиум-материалам и архиву уже опубликованных выпусков.</p>
|
||||
<p><a href="https://dzen.ru/nstarikovru?tab=premium">Перейти в Дзен Премиум</a></p>""".strip()
|
||||
|
||||
|
||||
def is_po_suti_dela_article(article: Article) -> bool:
|
||||
if not article.video:
|
||||
return False
|
||||
text = f"{article.video.title or ''}\n{article.video.description or ''}".lower()
|
||||
return "по сути дела" in text
|
||||
|
||||
|
||||
def cultural_initiatives_html() -> str:
|
||||
return """
|
||||
<section class="cultural-initiatives">
|
||||
<p>Проект реализуется при поддержке <a href="https://фондкультурныхинициатив.рф/">Президентского Фонда культурных инициатив</a>.</p>
|
||||
<p>#Фондкультурныхинициатив<br>#Грантдлякреативныхкоманд</p>
|
||||
</section>""".strip()
|
||||
|
||||
|
||||
def cultural_initiatives_rss_html() -> str:
|
||||
return """
|
||||
<p>Проект реализуется при поддержке <a href="https://фондкультурныхинициатив.рф/">Президентского Фонда культурных инициатив</a>.</p>
|
||||
<p>#Фондкультурныхинициатив<br>#Грантдлякреативныхкоманд</p>""".strip()
|
||||
|
||||
|
||||
def cover_html(article: Article, rss_safe: bool = False) -> str:
|
||||
if not article.video or not article.video.thumbnail_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:
|
||||
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"<figcaption>{escape(article.title)}</figcaption></figure>"
|
||||
)
|
||||
|
||||
|
||||
def sanitize_rss_html(html: str) -> str:
|
||||
html = re.sub(r"\s+class=\"[^\"]*\"", "", html)
|
||||
html = re.sub(r"\s+class='[^']*'", "", html)
|
||||
html = re.sub(r"</?(?:section|div)\b[^>]*>", "", html, flags=re.I)
|
||||
return html
|
||||
|
||||
|
||||
def media_player_xml(article: Article) -> str:
|
||||
if not article.video or not article.video.source_url:
|
||||
return ""
|
||||
embed_url = vk_video_embed_url(article.video.source_url)
|
||||
if not embed_url:
|
||||
return ""
|
||||
return f'<media:player url="{escape(embed_url)}" width="1280" height="720" />'
|
||||
|
||||
|
||||
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
|
||||
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))
|
||||
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
|
||||
|
||||
|
||||
def build_feed_xml(session: Session, settings: Settings) -> str:
|
||||
now = datetime.now(timezone.utc)
|
||||
articles = session.scalars(
|
||||
select(Article)
|
||||
.where(Article.status == "published", Article.published_at.is_not(None), Article.published_at <= now)
|
||||
.order_by(Article.published_at.desc(), Article.id.desc())
|
||||
.limit(settings.rss_limit)
|
||||
).all()
|
||||
|
||||
items: list[str] = []
|
||||
for article in articles:
|
||||
link = article_url(settings, article)
|
||||
content = f"<h1>{escape(article.title)}</h1>\n{render_article_html(article, rss_safe=True)}"
|
||||
frames = []
|
||||
if article.video_id:
|
||||
frames = session.scalars(
|
||||
select(Frame)
|
||||
.where(Frame.video_id == article.video_id, Frame.selected == True) # noqa: E712
|
||||
.order_by(Frame.score.desc(), Frame.id.asc())
|
||||
.limit(1)
|
||||
).all()
|
||||
enclosure = ""
|
||||
cover_url = article.video.thumbnail_url if article.video and article.video.thumbnail_url else ""
|
||||
if cover_url:
|
||||
enclosure = f'<enclosure url="{escape(cover_url)}" type="{image_mime_type(cover_url)}" />'
|
||||
elif frames and frames[0].public_url:
|
||||
enclosure = f'<enclosure url="{escape(frames[0].public_url)}" type="{image_mime_type(frames[0].public_url)}" />'
|
||||
media_player = media_player_xml(article)
|
||||
items.append(
|
||||
f"""
|
||||
<item>
|
||||
<title>{escape(article.title)}</title>
|
||||
<link>{escape(link)}</link>
|
||||
<guid isPermaLink="false">{escape(article.rss_guid or link)}</guid>
|
||||
<pubDate>{rfc822(article.published_at)}</pubDate>
|
||||
<category>format-article</category>
|
||||
<category>index</category>
|
||||
<category>comment-all</category>
|
||||
<media:rating scheme="urn:simple">nonadult</media:rating>
|
||||
{media_player}
|
||||
<description><![CDATA[{article.lead or article.title}]]></description>
|
||||
<content:encoded><![CDATA[{content}]]></content:encoded>
|
||||
{enclosure}
|
||||
</item>""".strip()
|
||||
)
|
||||
|
||||
return f"""<?xml version="1.0" encoding="UTF-8"?>
|
||||
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:media="http://search.yahoo.com/mrss/">
|
||||
<channel>
|
||||
<title>Николай Стариков</title>
|
||||
<link>{escape(settings.public_base_url)}</link>
|
||||
<description>Автоматические материалы канала Николая Старикова для Дзена</description>
|
||||
<language>ru</language>
|
||||
<lastBuildDate>{rfc822(datetime.now(timezone.utc))}</lastBuildDate>
|
||||
{chr(10).join(items)}
|
||||
</channel>
|
||||
</rss>
|
||||
"""
|
||||
60
dzen-assistant/app/whisper_cli.py
Normal file
60
dzen-assistant/app/whisper_cli.py
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
from faster_whisper import WhisperModel
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description="Transcribe a media file with faster-whisper.")
|
||||
parser.add_argument("media_path", help="Path to the video or audio file.")
|
||||
parser.add_argument(
|
||||
"--model",
|
||||
default="/llm/models/whisper/models--mobiuslabsgmbh--faster-whisper-large-v3-turbo/snapshots/0a363e9161cbc7ed1431c9597a8ceaf0c4f78fcf",
|
||||
help="Local faster-whisper model directory.",
|
||||
)
|
||||
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("--output", default="transcript.txt")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
model_path = Path(args.model)
|
||||
media_path = Path(args.media_path)
|
||||
output_path = Path(args.output)
|
||||
if not model_path.exists():
|
||||
raise SystemExit(f"Model path does not exist: {model_path}")
|
||||
if not media_path.exists():
|
||||
raise SystemExit(f"Media path does not exist: {media_path}")
|
||||
|
||||
model = WhisperModel(
|
||||
str(model_path),
|
||||
device=args.device,
|
||||
compute_type=args.compute_type,
|
||||
local_files_only=True,
|
||||
)
|
||||
segments, info = model.transcribe(
|
||||
str(media_path),
|
||||
language=args.language,
|
||||
beam_size=args.beam_size,
|
||||
vad_filter=True,
|
||||
)
|
||||
lines: list[str] = []
|
||||
print(f"Detected language: {info.language} ({info.language_probability:.2f})")
|
||||
for segment in segments:
|
||||
text = segment.text.strip()
|
||||
if not text:
|
||||
continue
|
||||
lines.append(text)
|
||||
print(f"[{segment.start:.2f} -> {segment.end:.2f}] {text}")
|
||||
|
||||
output_path.write_text("\n".join(lines).strip() + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
763
dzen-assistant/app/worker.py
Normal file
763
dzen-assistant/app/worker.py
Normal file
|
|
@ -0,0 +1,763 @@
|
|||
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"<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 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'<figure class="article-cover"><img src="{escape(video.thumbnail_url)}" alt="{escape(title)}">'
|
||||
f"<figcaption>{escape(title)}</figcaption></figure>"
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
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 "Полный разбор темы и новые закрытые лекции доступны в платных материалах Николая Старикова."
|
||||
59
dzen-assistant/docker-compose.yml
Normal file
59
dzen-assistant/docker-compose.yml
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
services:
|
||||
api:
|
||||
build: .
|
||||
container_name: dzen-assistant-api
|
||||
restart: unless-stopped
|
||||
command: uvicorn app.main:app --host 0.0.0.0 --port 8000
|
||||
env_file: .env
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
- /llm:/llm:ro
|
||||
depends_on:
|
||||
- redis
|
||||
networks:
|
||||
- caddy
|
||||
- dzen_internal
|
||||
|
||||
worker:
|
||||
build: .
|
||||
container_name: dzen-assistant-worker
|
||||
restart: unless-stopped
|
||||
command: celery -A app.worker.celery_app worker --loglevel=info --concurrency=1
|
||||
env_file: .env
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
- /llm:/llm:ro
|
||||
depends_on:
|
||||
- redis
|
||||
networks:
|
||||
- dzen_internal
|
||||
|
||||
beat:
|
||||
build: .
|
||||
container_name: dzen-assistant-beat
|
||||
restart: unless-stopped
|
||||
command: celery -A app.worker.celery_app beat --loglevel=info
|
||||
env_file: .env
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
depends_on:
|
||||
- redis
|
||||
networks:
|
||||
- dzen_internal
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
container_name: dzen-assistant-redis
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
networks:
|
||||
- dzen_internal
|
||||
|
||||
volumes:
|
||||
redis_data:
|
||||
|
||||
networks:
|
||||
caddy:
|
||||
external: true
|
||||
dzen_internal:
|
||||
12
dzen-assistant/requirements.txt
Normal file
12
dzen-assistant/requirements.txt
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
celery[redis]==5.5.3
|
||||
fastapi==0.115.12
|
||||
faster-whisper==1.1.1
|
||||
feedgen==1.0.0
|
||||
httpx==0.28.1
|
||||
Jinja2==3.1.6
|
||||
Pillow==11.2.1
|
||||
pydantic-settings==2.9.1
|
||||
python-multipart==0.0.20
|
||||
requests==2.32.5
|
||||
SQLAlchemy==2.0.41
|
||||
uvicorn[standard]==0.34.2
|
||||
BIN
generated/shkola-geopolitiki-2560x1280.png
Normal file
BIN
generated/shkola-geopolitiki-2560x1280.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.8 MiB |
BIN
generated/shkola-geopolitiki-centered-original.png
Normal file
BIN
generated/shkola-geopolitiki-centered-original.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2 MiB |
BIN
output/afisha.jpg
Normal file
BIN
output/afisha.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 152 KiB |
BIN
output/extracted_0_Image9.jpg
Normal file
BIN
output/extracted_0_Image9.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 73 KiB |
31
output/text-dlya-socsetey.txt
Normal file
31
output/text-dlya-socsetey.txt
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
🤝 Вместе помогаем людям на Донбассе
|
||||
|
||||
Тысячи пострадавших лишились дома, здоровья, потеряли родных. Им нужна наша помощь, чтобы продолжать жить.
|
||||
|
||||
Патриаршая гуманитарная миссия приглашает волонтеров для помощи людям на Донбассе.
|
||||
|
||||
🙏 Нужны волонтеры:
|
||||
🏠 восстановление частных домов;
|
||||
🏥 помощь в госпиталях и больницах;
|
||||
👵 уход за одинокими стариками на дому;
|
||||
📦 работа в гуманитарных центрах;
|
||||
🚗 помощь на своих автомобилях.
|
||||
|
||||
📍 География выездов:
|
||||
Мариуполь, Донецк, Северодонецк, Скадовск, Токмак, Курск, Белгород и другие города.
|
||||
|
||||
✅ Условия:
|
||||
📅 смены 7-14 дней;
|
||||
🔁 выезды еженедельно;
|
||||
🙌 специальные навыки не требуются;
|
||||
🧭 координаторы помогают на каждой смене;
|
||||
🍽 проживание и питание предоставляются;
|
||||
🎫 проезд оплачивается полностью или частично, в зависимости от региона проживания.
|
||||
|
||||
📝 Заполнить анкету можно на сайте:
|
||||
помочьвбеде.рф
|
||||
|
||||
☎️ Телефон:
|
||||
8 800 70 70 222
|
||||
|
||||
#волонтеры #Донбасс #помощьлюдям #ПатриаршаяГуманитарнаяМиссия #помочьвбеде
|
||||
8
requirements.txt
Normal file
8
requirements.txt
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
celery[redis]==5.5.3
|
||||
fastapi==0.115.12
|
||||
httpx==0.28.1
|
||||
Pillow==11.2.1
|
||||
pydantic-settings==2.9.1
|
||||
python-multipart==0.0.20
|
||||
SQLAlchemy==2.0.41
|
||||
uvicorn[standard]==0.34.2
|
||||
Loading…
Reference in a new issue