Compare commits

..

7 commits

9 changed files with 1233 additions and 26 deletions

View file

@ -0,0 +1,154 @@
# Nstarikov Storage Migration 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:** Relocate non-latency-sensitive persistent files from the root disk to the mounted 100 GB storage volume, retain Directus backups predictably, and preserve service paths.
**Architecture:** Use `/var/www/dzen.nstarikov.ru/storage` as the single storage root. Copy online first; stop only the relevant process for a final `rsync --delete`; preserve the former path as a symlink or explicit Compose bind mount. Keep timestamped rollback directories until every post-check passes.
**Tech Stack:** ext4, rsync, Docker Compose, gzip, shell, Caddy.
---
### Task 1: Validate storage and create isolated target directories
**Files:**
- Modify: `/etc/fstab` only if the existing storage mount is not persistent; otherwise no config change.
- [ ] **Step 1: Confirm the mounted volume and free capacity**
Run: `findmnt -no SOURCE,TARGET /var/www/dzen.nstarikov.ru/storage && df -h / /var/www/dzen.nstarikov.ru/storage`
Expected: the storage target is on its own filesystem with at least 80 GB free.
- [ ] **Step 2: Create only named category directories**
Run: `install -d -m 0755 /var/www/dzen.nstarikov.ru/storage/{directus-backup,geopolitics-story-temp,vk2ok-storage,dzen-media,n8n-archive,caddy-logs}`
Expected: all target directories exist on the storage filesystem; nothing is stored directly in the videos directory.
### Task 2: Migrate Directus dumps and apply explicit retention
**Files:**
- Modify: `/var/www/api.nstarikov.ru/backup/backup.sh`
- Move: `/var/www/api.nstarikov.ru/backup` to `/var/www/dzen.nstarikov.ru/storage/directus-backup`
- [ ] **Step 1: Back up the backup script and add deterministic retention**
Retain the latest `directus_*.sql.gz` from every one of the latest 14 calendar days. For files older than those days, retain the latest file from each of the three newest ISO weeks. Delete all other matching dumps only after a successful dump and gzip integrity check. Do not delete `backup.sh` or non-matching files.
- [ ] **Step 2: Make an online copy and record a manifest**
Run: `rsync -aHAX --info=progress2 /var/www/api.nstarikov.ru/backup/ /var/www/dzen.nstarikov.ru/storage/directus-backup/ && (cd /var/www/dzen.nstarikov.ru/storage/directus-backup && sha256sum directus_*.sql.gz > .migration-sha256)`
Expected: destination contains every source dump and a checksum manifest.
- [ ] **Step 3: Stop only the dump writer, final-sync, and switch compatibility path**
Run from `/var/www/api.nstarikov.ru`: `docker compose stop backup-pg`; run `rsync -aHAX --delete`; rename source to `backup.pre-storage-YYYYmmddHHMMSS`; create `backup -> /var/www/dzen.nstarikov.ru/storage/directus-backup`; then `docker compose up -d backup-pg`.
Expected: `backup-pg` is running and `/backup` resolves to the storage filesystem.
- [ ] **Step 4: Verify data and retention contract**
Run: `sha256sum -c .migration-sha256`, `gzip -t directus_*.sql.gz`, inspect the next `backup-pg` log, and count selected daily/weekly files after retention logic runs.
Expected: all pre-migration dumps validate; future runs keep 14 daily plus 3 older weekly dumps.
### Task 3: Migrate bot media without changing application paths
**Files:**
- Move: `/var/www/bots/geopolitics_tg_story/temp_videos` to `storage/geopolitics-story-temp`
- Move: `/var/www/bots/vk2ok/storage` to `storage/vk2ok-storage`
- [ ] **Step 1: Copy both sources online**
Run `rsync -aHAX --info=progress2` for each source into its named target directory.
Expected: target file counts and byte totals match their sources before cutover.
- [ ] **Step 2: Cut over geopolitics temporary-video storage**
Stop `geopolitics_story_app`, final-sync with `--delete`, rename the old source with a timestamp, create a symlink at `temp_videos`, then start the container.
Expected: the bot resumes and new writes follow the symlink onto storage.
- [ ] **Step 3: Cut over vk2ok storage**
From `/var/www/bots/vk2ok`, stop `api`, `worker`, and `beat`; final-sync with `--delete`; rename the old source with a timestamp; create the `storage` symlink; start the three services.
Expected: API, worker, and beat are healthy and all storage paths resolve to the target filesystem.
### Task 4: Migrate Dzen media using Compose mounts
**Files:**
- Modify: `/var/www/dzen.nstarikov.ru/docker-compose.yml`
- Move: `/var/www/dzen.nstarikov.ru/data/media` to `storage/dzen-media`
- [ ] **Step 1: Copy current media and prepare the explicit mount**
Copy `data/media/` to `storage/dzen-media/`. Add `/var/www/dzen.nstarikov.ru/storage/dzen-media:/app/data/media` to API, worker, and beat while keeping the existing data and videos mounts unchanged.
- [ ] **Step 2: Recreate only Dzen API, worker, and beat**
Stop those three services, run a final `rsync -aHAX --delete`, rename the old media directory to a timestamped rollback name, then recreate the three services with the changed Compose file.
Expected: uploads and generated media resolve from the new bind mount; Redis remains untouched.
- [ ] **Step 3: Verify Dzen application health and a known media response**
Run the existing health endpoint and an HTTP request to one existing media asset.
Expected: health is successful and the media asset returns its expected content type and successful status.
### Task 5: Move inactive n8n archive
**Files:**
- Move: `/var/www/n8n.nstarikov.ru/archive` to `storage/n8n-archive`
- [ ] **Step 1: Confirm no active Compose service consumes `archive`**
Run `docker compose ps` from `/var/www/n8n.nstarikov.ru` and inspect mounts for active n8n containers.
Expected: no active container uses the archival directory.
- [ ] **Step 2: Copy, validate, and switch the compatibility path**
Use rsync, compare file counts and byte totals, rename source to a timestamped rollback directory, and create `archive -> /var/www/dzen.nstarikov.ru/storage/n8n-archive`.
Expected: no application downtime and the archive path resolves to storage.
### Task 6: Migrate Caddy logs last and prove external reachability
**Files:**
- Modify: `/var/www/caddy/docker-compose.yml` or the equivalent active Compose file
- Move: `/var/www/caddy/logs` to `storage/caddy-logs`
- [ ] **Step 1: Inspect the active Caddy logging policy before alteration**
Read Caddy log blocks and preserve their existing rolling/retention settings. Do not add generic logrotate or use `copytruncate`.
- [ ] **Step 2: Copy and switch the single Caddy log bind mount**
Perform online rsync, stop/recreate Caddy for a final rsync and an updated log-source bind mount (or an equivalent parent-level compatibility symlink). Preserve the old directory as a rollback name.
Expected: only a brief proxy interruption; new log writes appear under `storage/caddy-logs`.
- [ ] **Step 3: Verify Caddy and public hosts**
Check container health/logs, request `https://nstarikov.ru/`, `https://api.nstarikov.ru/`, and `https://dzen.nstarikov.ru/`, and confirm each response is successful.
### Task 7: Final accounting and deferred cleanup
**Files:**
- No source-code changes.
- [ ] **Step 1: Verify every migration target and service**
Run `df -h / /var/www/dzen.nstarikov.ru/storage`; `findmnt`; `readlink -f` for every compatibility path; and targeted Docker health/log checks.
Expected: root usage has decreased by the moved data size, targets live on storage, and all affected services are healthy.
- [ ] **Step 2: Retain rollback sources until explicit cleanup approval**
Keep every timestamped `*.pre-storage-*` directory untouched after verification. Report their paths and sizes. Do not remove them in this migration because removal is destructive and needs a final explicit decision.

View file

@ -0,0 +1,50 @@
# Nstarikov storage migration
## Goal
Free space on the root disk without relocating active database, Redis, Docker
runtime, or Meilisearch data. The persistent 100 GB volume mounted at
`/var/www/dzen.nstarikov.ru/storage` is the destination. It has about 91 GB
available at the time of this design.
## Scope and ordering
1. Directus PostgreSQL dumps: move `api.nstarikov.ru/backup` to
`storage/directus-backup`; retain 14 most-recent calendar-day dumps and one
dump from each of the three most-recent older ISO weeks. The compatibility
path remains `/var/www/api.nstarikov.ru/backup` through a symlink, so the
existing `backup-pg` bind mount continues to work.
2. Move bot working media with compatibility symlinks:
`geopolitics_tg_story/temp_videos` to `storage/geopolitics-story-temp` and
`vk2ok/storage` to `storage/vk2ok-storage`.
3. Move Dzen media to `storage/dzen-media` using explicit Compose bind mounts;
do not use a symlink below the parent `data` bind mount.
4. Move the inactive n8n `archive` directory to `storage/n8n-archive` with a
compatibility symlink.
5. Move Caddy logs last to `storage/caddy-logs`, preserving Caddy's own
rotation configuration. This requires a brief proxy restart.
## Safety and verification
Each migration uses an online `rsync`, a short service stop where relevant, a
final `rsync --delete`, then source rename and symlink or Compose rebind. The
original source is retained as a timestamped rollback directory until file
counts, checksums/integrity checks, service health, and the mount target have
been verified. Directus backups are additionally gzip-tested. The original
directory is removed only after those checks pass and explicit cleanup is in
scope.
## Exclusions
Do not move `/var/lib/docker`, Docker volumes, PostgreSQL, Redis, or
Meilisearch in this operation. These are latency-sensitive runtime data and
require a separate migration and rollback plan. Root, apt, and container
image caches are cleaned only through their own safe retention mechanisms;
they are not archived to the storage volume.
## Expected result
The initial relocation moves roughly 11 GB from root storage: about 5.9 GB of
Directus dumps, 4.1 GB of bot media, 0.8 GB of inactive n8n archive, and
0.45 GB of Dzen media. Caddy logs add about 1.5 GB when moved. Sizes are
time-dependent and the final `df` result is authoritative.

View file

@ -22,6 +22,7 @@ import {
Save, Save,
Settings2, Settings2,
Trash2, Trash2,
Upload,
X, X,
} from "lucide-react" } from "lucide-react"
@ -137,6 +138,21 @@ type VideoChaptersResponse = {
canSplit: boolean canSplit: boolean
} }
type VideoStorage = {
totalBytes: number
usedBytes: number
freeBytes: number
usedPercent: number
}
type LocalVideoUpload = {
name: string
loaded: number
total: number
status: "uploading" | "complete" | "cancelled" | "error"
errorMessage?: string
}
type EditorBlock = OutputData["blocks"][number] type EditorBlock = OutputData["blocks"][number]
type RandomFrameTuneConfig = { type RandomFrameTuneConfig = {
@ -176,6 +192,8 @@ class VkVideoTool {
const ARTICLES_PAGE_SIZE = 10 const ARTICLES_PAGE_SIZE = 10
const CHAPTER_SELECTION_STORAGE_PREFIX = "dzen:selected-chapters:" const CHAPTER_SELECTION_STORAGE_PREFIX = "dzen:selected-chapters:"
const LOCAL_VIDEO_EXTENSIONS = new Set(["mp4", "webm", "mov", "mkv"])
const LOW_STORAGE_WARNING_BYTES = 10 * 1024 * 1024 * 1024
function chapterSelectionStorageKey(videoId: number) { function chapterSelectionStorageKey(videoId: number) {
return `${CHAPTER_SELECTION_STORAGE_PREFIX}${videoId}` return `${CHAPTER_SELECTION_STORAGE_PREFIX}${videoId}`
@ -1011,6 +1029,30 @@ function formatDuration(seconds?: number) {
return `${minutes}:${String(rest).padStart(2, "0")}` return `${minutes}:${String(rest).padStart(2, "0")}`
} }
function formatFileSize(bytes?: number) {
const value = Math.max(0, bytes || 0)
if (value >= 1024 * 1024 * 1024) {
return `${(value / (1024 * 1024 * 1024)).toLocaleString("ru-RU", { maximumFractionDigits: 1 })} ГБ`
}
if (value >= 1024 * 1024) {
return `${(value / (1024 * 1024)).toLocaleString("ru-RU", { maximumFractionDigits: 1 })} МБ`
}
return `${Math.round(value / 1024).toLocaleString("ru-RU")} КБ`
}
function uploadErrorMessage(responseText: string) {
try {
const payload = JSON.parse(responseText) as { detail?: string }
return payload.detail || responseText
} catch {
return responseText || "Не удалось загрузить видео."
}
}
function localVideoExtension(file: File) {
return file.name.split(".").pop()?.toLowerCase() || ""
}
function parseApiDate(value?: string) { function parseApiDate(value?: string) {
if (!value) return null if (!value) return null
const normalized = /(?:z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value}Z` const normalized = /(?:z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value}Z`
@ -1104,6 +1146,22 @@ function StatusBadge({ status }: { status: string }) {
</Badge> </Badge>
) )
} }
if (normalized === "planning") {
return (
<Badge className="gap-1.5 border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-50" variant="outline">
<Loader2 className="size-3.5 animate-spin" />
Хронометраж
</Badge>
)
}
if (normalized === "planned") {
return (
<Badge className="gap-1.5 border-sky-200 bg-sky-50 text-sky-700 hover:bg-sky-50" variant="outline">
<CheckCircle2 className="size-3.5" />
Темы готовы
</Badge>
)
}
return <Badge variant={statusVariant(status)}>{status}</Badge> return <Badge variant={statusVariant(status)}>{status}</Badge>
} }
@ -1162,10 +1220,15 @@ export default function App() {
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const [manualVideoUrl, setManualVideoUrl] = useState("") const [manualVideoUrl, setManualVideoUrl] = useState("")
const [manualVideoBusy, setManualVideoBusy] = useState(false) const [manualVideoBusy, setManualVideoBusy] = useState(false)
const [videoStorage, setVideoStorage] = useState<VideoStorage | null>(null)
const [localVideoUpload, setLocalVideoUpload] = useState<LocalVideoUpload | null>(null)
const [localVideoDragActive, setLocalVideoDragActive] = useState(false)
const [videoActionId, setVideoActionId] = useState<number | null>(null) const [videoActionId, setVideoActionId] = useState<number | null>(null)
const editorHolderRef = useRef<HTMLDivElement | null>(null) const editorHolderRef = useRef<HTMLDivElement | null>(null)
const editorInstanceRef = useRef<EditorJS | null>(null) const editorInstanceRef = useRef<EditorJS | null>(null)
const featureImageInputRef = useRef<HTMLInputElement | null>(null) const featureImageInputRef = useRef<HTMLInputElement | null>(null)
const localVideoInputRef = useRef<HTMLInputElement | null>(null)
const localVideoUploadRequestRef = useRef<XMLHttpRequest | null>(null)
const featureImageHoverRef = useRef(false) const featureImageHoverRef = useRef(false)
const editorImageHoverBlockRef = useRef<BlockAPI | null>(null) const editorImageHoverBlockRef = useRef<BlockAPI | null>(null)
const pasteImageTargetRef = useRef<"feature" | "editor" | null>(null) const pasteImageTargetRef = useRef<"feature" | "editor" | null>(null)
@ -1209,6 +1272,9 @@ export default function App() {
.sort((a, b) => dateSortValue(b.publishedAt || b.createdAt) - dateSortValue(a.publishedAt || a.createdAt)), .sort((a, b) => dateSortValue(b.publishedAt || b.createdAt) - dateSortValue(a.publishedAt || a.createdAt)),
[articles] [articles]
) )
const localUploadPercent = localVideoUpload?.total ? Math.min(100, Math.round((localVideoUpload.loaded / localVideoUpload.total) * 100)) : 0
const videoStoragePercent = Math.max(0, Math.min(100, videoStorage?.usedPercent ?? 0))
const videoStorageLow = Boolean(videoStorage && videoStorage.freeBytes < LOW_STORAGE_WARNING_BYTES)
async function loadArticlesPage(reset = false) { async function loadArticlesPage(reset = false) {
if (articlesLoadingRef.current) return if (articlesLoadingRef.current) return
@ -1253,6 +1319,14 @@ export default function App() {
} }
} }
async function loadVideoStorage() {
try {
setVideoStorage(await api<VideoStorage>("/api/storage/videos"))
} catch {
setVideoStorage(null)
}
}
useEffect(() => { useEffect(() => {
api<{ authenticated: boolean; hasPasskeys: boolean }>("/api/auth/status") api<{ authenticated: boolean; hasPasskeys: boolean }>("/api/auth/status")
.then((status) => { .then((status) => {
@ -1268,6 +1342,7 @@ export default function App() {
useEffect(() => { useEffect(() => {
if (authState !== "authenticated") return if (authState !== "authenticated") return
refresh().catch((error) => setStatusMessage(`Ошибка загрузки: ${error.message}`)) refresh().catch((error) => setStatusMessage(`Ошибка загрузки: ${error.message}`))
void loadVideoStorage()
api<AppSettings>("/api/settings").then(setAppSettings).catch(() => undefined) api<AppSettings>("/api/settings").then(setAppSettings).catch(() => undefined)
}, [authState]) }, [authState])
@ -1297,6 +1372,7 @@ export default function App() {
useEffect(() => () => { useEffect(() => () => {
logSocketRef.current?.close() logSocketRef.current?.close()
localVideoUploadRequestRef.current?.abort()
clearImageCaptionNormalizationTimers() clearImageCaptionNormalizationTimers()
}, []) }, [])
@ -1354,6 +1430,87 @@ export default function App() {
} }
} }
function uploadLocalVideo(file: File) {
if (localVideoUpload?.status === "uploading") return
if (!LOCAL_VIDEO_EXTENSIONS.has(localVideoExtension(file))) {
setLocalVideoUpload({
name: file.name,
loaded: 0,
total: file.size,
status: "error",
errorMessage: "Поддерживаются файлы MP4, WebM, MOV и MKV.",
})
return
}
setLocalVideoUpload({ name: file.name, loaded: 0, total: file.size, status: "uploading" })
const request = new XMLHttpRequest()
localVideoUploadRequestRef.current = request
request.open("POST", "/api/videos/upload")
request.responseType = "text"
request.withCredentials = true
request.upload.onprogress = (event) => {
setLocalVideoUpload((current) => {
if (!current || current.status !== "uploading") return current
return {
...current,
loaded: event.loaded,
total: event.lengthComputable ? event.total : file.size,
}
})
}
request.onload = () => {
if (localVideoUploadRequestRef.current === request) {
localVideoUploadRequestRef.current = null
}
if (request.status < 200 || request.status >= 300) {
setLocalVideoUpload({
name: file.name,
loaded: 0,
total: file.size,
status: "error",
errorMessage: uploadErrorMessage(request.responseText),
})
return
}
setLocalVideoUpload({ name: file.name, loaded: file.size, total: file.size, status: "complete" })
setStatusMessage(`Видео «${file.name}» загружено и готово к обработке.`)
void Promise.all([refresh(), loadVideoStorage()]).catch((error) => {
setStatusMessage(`Видео загружено, но список не обновился: ${error instanceof Error ? error.message : String(error)}`)
})
}
request.onerror = () => {
if (localVideoUploadRequestRef.current === request) {
localVideoUploadRequestRef.current = null
}
setLocalVideoUpload({
name: file.name,
loaded: 0,
total: file.size,
status: "error",
errorMessage: "Сеть прервала загрузку. Попробуйте ещё раз.",
})
}
request.onabort = () => {
if (localVideoUploadRequestRef.current === request) {
localVideoUploadRequestRef.current = null
}
setLocalVideoUpload((current) => current ? { ...current, status: "cancelled" } : current)
}
const formData = new FormData()
formData.append("file", file)
request.send(formData)
}
function selectLocalVideo(file?: File | null) {
if (!file) return
uploadLocalVideo(file)
}
function cancelLocalVideoUpload() {
localVideoUploadRequestRef.current?.abort()
}
async function prepareVideoProcessing(video: Video, recreateDrafts = false) { async function prepareVideoProcessing(video: Video, recreateDrafts = false) {
if ((video.durationSeconds || 0) < 20 * 60) { if ((video.durationSeconds || 0) < 20 * 60) {
await processVideo(video.id, recreateDrafts) await processVideo(video.id, recreateDrafts)
@ -1363,6 +1520,12 @@ export default function App() {
try { try {
const result = await api<VideoChaptersResponse>(`/api/videos/${video.id}/chapters`) const result = await api<VideoChaptersResponse>(`/api/videos/${video.id}/chapters`)
if (!result.canSplit || result.chapters.length < 2) { if (!result.canSplit || result.chapters.length < 2) {
if (video.sourceUrl.startsWith("upload://")) {
const task = await api<{ taskId: string }>(`/api/videos/${video.id}/chapter-plan`, { method: "POST" })
setStatusMessage(`Строю хронометраж ролика. Транскрибация и темы появятся в журнале. Task: ${task.taskId}`)
await refresh()
return
}
await processVideo(video.id) await processVideo(video.id)
return return
} }
@ -1997,6 +2160,7 @@ export default function App() {
clearStoredChapterSelection(id) clearStoredChapterSelection(id)
setStatusMessage(`Удалил ролик${title ? `: ${title}` : ""}. Он исключен из повторного импорта.`) setStatusMessage(`Удалил ролик${title ? `: ${title}` : ""}. Он исключен из повторного импорта.`)
await refresh() await refresh()
await loadVideoStorage()
} finally { } finally {
setVideoActionId(null) setVideoActionId(null)
} }
@ -2078,6 +2242,114 @@ export default function App() {
</div> </div>
</CardHeader> </CardHeader>
<CardContent className="work-list flex max-h-[72vh] flex-col gap-2 overflow-y-auto"> <CardContent className="work-list flex max-h-[72vh] flex-col gap-2 overflow-y-auto">
<div className="grid gap-2 xl:grid-cols-[minmax(0,1fr)_13rem]">
<section
className={`local-video-upload rounded-md border border-dashed p-3 transition-colors ${
localVideoDragActive ? "border-primary bg-primary/5" : "border-border bg-background"
}`}
onDragEnter={(event) => {
event.preventDefault()
if (localVideoUpload?.status !== "uploading") setLocalVideoDragActive(true)
}}
onDragOver={(event) => {
event.preventDefault()
event.dataTransfer.dropEffect = "copy"
if (localVideoUpload?.status !== "uploading") setLocalVideoDragActive(true)
}}
onDragLeave={(event) => {
if (event.currentTarget.contains(event.relatedTarget as Node)) return
setLocalVideoDragActive(false)
}}
onDrop={(event) => {
event.preventDefault()
setLocalVideoDragActive(false)
if (localVideoUpload?.status === "uploading") return
selectLocalVideo(event.dataTransfer.files?.[0])
}}
>
<input
ref={localVideoInputRef}
className="hidden"
type="file"
accept="video/mp4,video/webm,video/quicktime,video/x-matroska,.mp4,.webm,.mov,.mkv"
onChange={(event) => {
const file = event.currentTarget.files?.[0]
event.currentTarget.value = ""
selectLocalVideo(file)
}}
/>
<div className="flex flex-wrap items-center gap-3">
<span className="flex size-9 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
<Upload className="size-4" />
</span>
<div className="min-w-0 flex-1">
<p className="text-sm font-semibold">Загрузить видео с компьютера</p>
<p className="mt-0.5 text-xs text-muted-foreground">MP4, WebM, MOV или MKV. Перетащите файл сюда или выберите его.</p>
</div>
<Button size="sm" variant="outline" disabled={localVideoUpload?.status === "uploading"} onClick={() => localVideoInputRef.current?.click()}>
<Upload data-icon="inline-start" />
Выбрать файл
</Button>
</div>
{localVideoUpload ? (
<div className="mt-3 border-t pt-3" aria-live="polite">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="truncate text-sm font-medium" title={localVideoUpload.name}>{localVideoUpload.name}</p>
<p className={`mt-0.5 text-xs ${localVideoUpload.status === "error" ? "text-destructive" : "text-muted-foreground"}`}>
{localVideoUpload.status === "uploading"
? `Загружено ${formatFileSize(localVideoUpload.loaded)} из ${formatFileSize(localVideoUpload.total)}`
: localVideoUpload.status === "complete"
? `Загружено ${formatFileSize(localVideoUpload.total)}. Файл готов к обработке.`
: localVideoUpload.status === "cancelled"
? "Загрузка отменена."
: localVideoUpload.errorMessage || "Не удалось загрузить файл."}
</p>
</div>
{localVideoUpload.status === "uploading" ? (
<Button size="icon" variant="outline" title="Отменить загрузку" aria-label="Отменить загрузку" onClick={cancelLocalVideoUpload}>
<X className="size-4" />
</Button>
) : (
<Button size="icon" variant="ghost" title="Скрыть статус" aria-label="Скрыть статус" onClick={() => setLocalVideoUpload(null)}>
<X className="size-4" />
</Button>
)}
</div>
<div className="mt-2 flex items-center gap-3">
<div className="h-1.5 flex-1 overflow-hidden rounded-full bg-muted">
<div
className={localVideoUpload.status === "error" ? "h-full rounded-full bg-destructive transition-all" : "h-full rounded-full bg-primary transition-all"}
style={{ width: `${localVideoUpload.status === "complete" ? 100 : localUploadPercent}%` }}
/>
</div>
<span className="w-10 text-right text-xs tabular-nums text-muted-foreground">
{localVideoUpload.status === "uploading" ? `${localUploadPercent}%` : localVideoUpload.status === "complete" ? "100%" : ""}
</span>
</div>
</div>
) : null}
</section>
<section className={`rounded-md border bg-background p-3 ${videoStorageLow ? "border-amber-300 bg-amber-50/60" : "border-border"}`} aria-live="polite">
<div className="flex items-center justify-between gap-2">
<p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Видео на диске</p>
{videoStorage ? <span className="text-xs tabular-nums text-muted-foreground">{videoStoragePercent}%</span> : null}
</div>
{videoStorage ? (
<>
<div className="mt-3 h-1.5 overflow-hidden rounded-full bg-muted">
<div className={`h-full rounded-full transition-all ${videoStorageLow ? "bg-amber-500" : "bg-primary"}`} style={{ width: `${videoStoragePercent}%` }} />
</div>
<p className={`mt-2 text-xs leading-5 ${videoStorageLow ? "text-amber-800" : "text-muted-foreground"}`}>
Свободно {formatFileSize(videoStorage.freeBytes)} из {formatFileSize(videoStorage.totalBytes)}
</p>
</>
) : (
<p className="mt-3 text-xs leading-5 text-muted-foreground">Данные о диске недоступны.</p>
)}
</section>
</div>
{productionVideos.length > 0 ? ( {productionVideos.length > 0 ? (
productionVideos.map((video) => { productionVideos.map((video) => {
const draftArticles = video.articles?.filter((article) => article.status !== "published") ?? [] const draftArticles = video.articles?.filter((article) => article.status !== "published") ?? []
@ -2086,7 +2358,7 @@ export default function App() {
const draftArticleId = draftArticles[0]?.id ?? (publishedArticle ? undefined : fallbackArticleId) const draftArticleId = draftArticles[0]?.id ?? (publishedArticle ? undefined : fallbackArticleId)
const progress = Math.max(0, Math.min(100, video.progressPercent || 0)) const progress = Math.max(0, Math.min(100, video.progressPercent || 0))
const hasStarted = video.status !== "new" || progress > 0 const hasStarted = video.status !== "new" || progress > 0
const isActive = ["queued", "processing"].includes(video.status) const isActive = ["queued", "processing", "planning"].includes(video.status)
const isSubmitting = videoActionId === video.id const isSubmitting = videoActionId === video.id
const hasDraftAction = draftArticles.length > 0 || Boolean(draftArticleId) const hasDraftAction = draftArticles.length > 0 || Boolean(draftArticleId)
return ( return (
@ -2165,12 +2437,12 @@ export default function App() {
<Button <Button
size="sm" size="sm"
variant="outline" variant="outline"
disabled={isSubmitting} disabled={isSubmitting || video.status === "planning"}
className="border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-100 hover:text-amber-900" className="border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-100 hover:text-amber-900"
onClick={() => processVideo(video.id, true)} onClick={() => processVideo(video.id, true)}
> >
<RefreshCw data-icon="inline-start" className={isSubmitting ? "animate-spin" : ""} /> <RefreshCw data-icon="inline-start" className={isSubmitting || video.status === "planning" ? "animate-spin" : ""} />
Перезапустить {video.status === "planning" ? "Хронометраж" : "Перезапустить"}
</Button> </Button>
) : ( ) : (
<Button <Button

View file

@ -8,6 +8,7 @@ import os
from pathlib import Path from pathlib import Path
import random import random
import re import re
import shutil
import subprocess import subprocess
from typing import Any from typing import Any
from uuid import uuid4 from uuid import uuid4
@ -38,7 +39,7 @@ from app.models import AppSetting, Article, Frame, ImageGenerationBatch, ImageGe
from app.image_generation import DEFAULT_API_URL, DEFAULT_MODEL, build_prompt, normalize_api_url from app.image_generation import DEFAULT_API_URL, DEFAULT_MODEL, build_prompt, normalize_api_url
from app.quality import validate_article_content from app.quality import validate_article_content
from app.rss import VIDEO_PLACEHOLDER, article_url, build_feed_xml, render_article_html, split_audience_question_html from app.rss import VIDEO_PLACEHOLDER, article_url, build_feed_xml, render_article_html, split_audience_question_html
from app.worker import best_thumbnail_url, generate_article_image, parse_upload_date, process_video, scan_sources, ytdlp_base_args from app.worker import best_thumbnail_url, create_chapter_plan, generate_article_image, parse_upload_date, process_video, scan_sources, ytdlp_base_args
router = APIRouter() router = APIRouter()
@ -50,6 +51,10 @@ ZEN_VERIFICATION_META = (
'content="y2a3098Zp7skRQXDYdkEOwOXFDdQsSzU7bkouMOhtBECx6zgC5CCqVZRxslhhjSg" />' 'content="y2a3098Zp7skRQXDYdkEOwOXFDdQsSzU7bkouMOhtBECx6zgC5CCqVZRxslhhjSg" />'
) )
PUBLIC_REDIRECT_URL = "https://nstarikov.ru" PUBLIC_REDIRECT_URL = "https://nstarikov.ru"
ALLOWED_VIDEO_EXTENSIONS = {".mp4", ".webm", ".mov", ".mkv"}
MAX_VIDEO_UPLOAD_BYTES = 10 * 1024 * 1024 * 1024
VIDEO_UPLOAD_CHUNK_BYTES = 1024 * 1024
VIDEO_UPLOAD_LOG_INTERVAL_BYTES = 5 * 1024 * 1024
class SourceIn(BaseModel): class SourceIn(BaseModel):
@ -427,6 +432,46 @@ def local_video_file(video: Video, settings: Settings) -> Path | None:
return None return None
def video_storage_payload(settings: Settings) -> dict[str, int]:
settings.videos_path.mkdir(parents=True, exist_ok=True)
usage = shutil.disk_usage(settings.videos_path)
used_percent = round(usage.used / usage.total * 100) if usage.total else 0
free_percent = round(usage.free / usage.total * 100) if usage.total else 0
return {
"totalBytes": usage.total,
"usedBytes": usage.used,
"freeBytes": usage.free,
"usedPercent": used_percent,
"freePercent": free_percent,
}
def uploaded_video_duration(path: Path) -> int:
command = [
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
str(path),
]
try:
result = subprocess.run(command, capture_output=True, text=True, timeout=30, check=False)
duration = float(result.stdout.strip()) if result.returncode == 0 else 0
except (OSError, subprocess.TimeoutExpired, ValueError):
duration = 0
if duration <= 0:
raise HTTPException(status_code=422, detail="Не удалось определить длительность видео через ffprobe.")
return round(duration)
def upload_log_line(stage: str, message: str) -> str:
now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
return f"[{now}] {stage}: {message}"
def create_random_frame(video: Video, settings: Settings) -> tuple[Path, str, int]: def create_random_frame(video: Video, settings: Settings) -> tuple[Path, str, int]:
video_path = local_video_file(video, settings) video_path = local_video_file(video, settings)
if not video_path: if not video_path:
@ -616,6 +661,111 @@ def import_video(payload: ManualVideoIn, session: Session = Depends(get_session)
} }
@router.get("/api/storage/videos")
def video_storage(settings: Settings = Depends(get_settings)) -> dict[str, int]:
return video_storage_payload(settings)
@router.post("/api/videos/upload")
async def upload_video(
file: UploadFile = File(...),
session: Session = Depends(get_session),
settings: Settings = Depends(get_settings),
) -> dict[str, int | str | None]:
filename = Path(file.filename or "").name
suffix = Path(filename).suffix.lower()
if suffix not in ALLOWED_VIDEO_EXTENSIONS:
raise HTTPException(status_code=422, detail="Поддерживаются только MP4, WebM, MOV и MKV.")
settings.videos_path.mkdir(parents=True, exist_ok=True)
if shutil.disk_usage(settings.videos_path).free <= 0:
raise HTTPException(status_code=507, detail="На диске для видео нет свободного места.")
external_id = f"upload:{uuid4().hex}"
title = Path(filename).stem.strip() or "Загруженный ролик"
video = Video(
source_id=None,
external_id=external_id,
source_url=f"upload://{external_id}",
title=title,
description="",
published_at=datetime.now(timezone.utc),
status="new",
progress_percent=0,
progress_stage="Загрузка файла",
progress_log=upload_log_line("Загрузка", f"Начинаю прием файла: {filename}"),
)
session.add(video)
session.commit()
session.refresh(video)
root = settings.videos_path.resolve()
video_dir = (settings.videos_path / str(video.id)).resolve()
target = video_dir / f"video{suffix}"
bytes_written = 0
bytes_at_last_log = 0
declared_size = getattr(file, "size", None)
total_bytes = declared_size if isinstance(declared_size, int) and declared_size > 0 else None
try:
if not video_dir.is_relative_to(root):
raise RuntimeError("Небезопасный путь для загруженного видео.")
video_dir.mkdir(parents=True, exist_ok=False)
with target.open("xb") as output:
while chunk := await file.read(VIDEO_UPLOAD_CHUNK_BYTES):
next_size = bytes_written + len(chunk)
if next_size > MAX_VIDEO_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="Размер видео не должен превышать 10 ГБ.")
if len(chunk) > shutil.disk_usage(settings.videos_path).free:
raise HTTPException(status_code=507, detail="На диске для видео закончилось свободное место.")
output.write(chunk)
bytes_written = next_size
if bytes_written - bytes_at_last_log >= VIDEO_UPLOAD_LOG_INTERVAL_BYTES:
uploaded_mb = bytes_written / 1024 / 1024
size_note = f" из {total_bytes / 1024 / 1024:.1f} МБ" if total_bytes else ""
video.progress_percent = min(99, round(bytes_written / total_bytes * 100)) if total_bytes else 0
video.progress_log = "\n".join(
[video.progress_log, upload_log_line("Загрузка", f"Получено {uploaded_mb:.1f} МБ{size_note}")]
)
session.commit()
bytes_at_last_log = bytes_written
if not bytes_written:
raise HTTPException(status_code=422, detail="Загруженный файл пуст.")
duration = uploaded_video_duration(target)
os.chmod(target, 0o644)
size_mb = bytes_written / 1024 / 1024
video.local_video_path = str(target)
video.duration_seconds = duration
video.progress_percent = 0
video.progress_stage = "Готов к обработке"
video.progress_log = "\n".join(
[
video.progress_log,
upload_log_line("Загрузка", f"Файл сохранен: {size_mb:.1f} МБ"),
upload_log_line("Подготовка", f"Длительность определена: {duration} сек. Ролик готов к обработке."),
]
)
session.commit()
return {
"id": video.id,
"title": video.title,
"sourceUrl": video.source_url,
"durationSeconds": video.duration_seconds,
"status": video.status,
}
except Exception:
if video_dir.is_relative_to(root):
shutil.rmtree(video_dir, ignore_errors=True)
session.delete(video)
session.commit()
raise
finally:
await file.close()
@router.get("/api/videos") @router.get("/api/videos")
def list_videos(session: Session = Depends(get_session)) -> list[dict]: def list_videos(session: Session = Depends(get_session)) -> list[dict]:
videos = session.scalars( videos = session.scalars(
@ -675,7 +825,8 @@ def process_video_route(video_id: int, payload: VideoProcessIn | None = Body(def
action = "старые черновики отправлены на переделку" action = "старые черновики отправлены на переделку"
if selected_chapters: if selected_chapters:
action += f", выбрано глав: {len(selected_chapters)}" action += f", выбрано глав: {len(selected_chapters)}"
video.progress_log = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}] В очереди: {action}" queue_log = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}] В очереди: {action}"
video.progress_log = "\n".join(part for part in [video.progress_log, queue_log] if part)
video.error_message = None video.error_message = None
session.commit() session.commit()
task = process_video.delay(video_id, selected_chapters or None) task = process_video.delay(video_id, selected_chapters or None)
@ -697,8 +848,40 @@ def video_chapters(video_id: int, session: Session = Depends(get_session)) -> di
} }
@router.post("/api/videos/{video_id}/chapter-plan")
def create_video_chapter_plan(video_id: int, session: Session = Depends(get_session)) -> dict[str, str]:
video = session.get(Video, video_id)
if not video:
raise HTTPException(status_code=404, detail="Video not found")
if not video.duration_seconds or video.duration_seconds < 20 * 60:
raise HTTPException(status_code=422, detail="Хронометраж нужен только для роликов длиннее 20 минут.")
if video.status in {"queued", "processing", "planning"}:
raise HTTPException(status_code=409, detail="Ролик уже находится в обработке.")
video.status = "planning"
video.progress_percent = 1
video.progress_stage = "В очереди на хронометраж"
video.error_message = None
plan_log = upload_log_line("Хронометраж", "Задача поставлена в очередь: транскрибация и анализ тем")
video.progress_log = "\n".join(part for part in [video.progress_log, plan_log] if part)
session.commit()
task = create_chapter_plan.delay(video_id)
return {"taskId": task.id}
def delete_video_storage_dir(video: Video, settings: Settings) -> None:
root = settings.videos_path.resolve()
video_dir = (root / str(video.id)).resolve()
if video_dir != root and video_dir.is_relative_to(root):
shutil.rmtree(video_dir, ignore_errors=True)
video.local_video_path = None
@router.delete("/api/videos/{video_id}") @router.delete("/api/videos/{video_id}")
def ignore_video(video_id: int, session: Session = Depends(get_session)) -> dict[str, int | str]: def ignore_video(
video_id: int,
session: Session = Depends(get_session),
settings: Settings = Depends(get_settings),
) -> dict[str, int | str]:
video = session.get(Video, video_id) video = session.get(Video, video_id)
if not video: if not video:
raise HTTPException(status_code=404, detail="Video not found") raise HTTPException(status_code=404, detail="Video not found")
@ -710,6 +893,7 @@ def ignore_video(video_id: int, session: Session = Depends(get_session)) -> dict
for article in video.articles: for article in video.articles:
if article.status != "published": if article.status != "published":
article.status = "rejected" article.status = "rejected"
delete_video_storage_dir(video, settings)
session.commit() session.commit()
return {"id": video.id, "status": video.status} return {"id": video.id, "status": video.status}

View file

@ -264,6 +264,7 @@ ENTITY_CORRECTIONS = {
} }
QUALITY_REWRITE_ATTEMPTS = 3 QUALITY_REWRITE_ATTEMPTS = 3
CHAPTER_PLAN_MIN_DURATION_SECONDS = 20 * 60
QUALITY_ERROR_MARKERS = [ QUALITY_ERROR_MARKERS = [
"LLM вернул невалидный JSON", "LLM вернул невалидный JSON",
"Статья содержит первое лицо", "Статья содержит первое лицо",
@ -273,6 +274,25 @@ QUALITY_ERROR_MARKERS = [
"Статья слишком короткая", "Статья слишком короткая",
] ]
CHAPTER_PLAN_SYSTEM_PROMPT = """Ты редактор хронометража для русскоязычных видео.
По расшифровке длинного видео выдели самостоятельные тематические эпизоды. Каждый
эпизод должен отражать смену темы, а не паузу, приветствие или техническую реплику.
Верни только валидный JSON без Markdown и пояснений:
{
"chapters": [
{"title": "Краткое название темы", "startSeconds": 0}
]
}
Правила:
- первая глава всегда начинается с 0;
- startSeconds - целое число секунд, главы идут строго по возрастанию;
- не добавляй вымышленных фактов, дат и имён;
- заголовок главы краткий, на русском языке, без точки в конце;
- для длинного выпуска выделяй только содержательные темы, обычно от 3 до 10 глав.
"""
def run(command: list[str], cwd: Path | None = None) -> subprocess.CompletedProcess[str]: 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) return subprocess.run(command, cwd=cwd, text=True, capture_output=True, check=True)
@ -515,11 +535,12 @@ def process_video(video_id: int, selected_chapters: list[dict[str, Any]] | None
video.status = "processing" video.status = "processing"
video.progress_percent = 5 video.progress_percent = 5
video.progress_stage = "Подготовка" video.progress_stage = "Подготовка"
video.progress_log = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}] Подготовка: задача взята worker" worker_log = f"[{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')}] Подготовка: задача взята worker"
video.progress_log = "\n".join(part for part in [video.progress_log, worker_log] if part)
video.error_message = None video.error_message = None
session.commit() session.commit()
try: try:
append_progress(video_id, 10, "Скачивание", "Скачиваю видео из VK") append_progress(video_id, 10, "Подготовка видео", "Проверяю локальный файл или источник")
local_video = download_video(video) local_video = download_video(video)
video.local_video_path = str(local_video) video.local_video_path = str(local_video)
session.commit() session.commit()
@ -560,15 +581,79 @@ def process_video(video_id: int, selected_chapters: list[dict[str, Any]] | None
raise raise
@celery_app.task(name="app.worker.create_chapter_plan")
def create_chapter_plan(video_id: int) -> dict[str, int | str]:
"""Create a reusable, parseable chapter plan from a saved long-video transcript."""
init_db()
with SessionLocal() as session:
video = session.get(Video, video_id)
if not video:
return {"status": "missing", "videoId": video_id}
duration = video.duration_seconds
if duration is None and video.local_video_path:
duration = media_duration_seconds(Path(video.local_video_path))
video.duration_seconds = duration
session.commit()
if not duration or duration < CHAPTER_PLAN_MIN_DURATION_SECONDS:
append_progress(
video_id,
None,
"Хронометраж",
"План глав не нужен: длительность ролика меньше 20 минут",
)
return {"status": "skipped", "videoId": video_id}
try:
video.status = "planning"
video.progress_percent = max(video.progress_percent or 0, 5)
video.progress_stage = "Подготовка хронометража"
session.commit()
append_progress(video_id, 10, "Подготовка видео", "Проверяю локальный файл или источник")
local_video = download_video(video)
video.local_video_path = str(local_video)
session.commit()
append_progress(video_id, 35, "Транскрибация", "Проверяю сохраненную расшифровку")
transcript_path = transcribe_video(local_video, video_id, video.transcript_path)
video.transcript_path = str(transcript_path)
session.commit()
append_progress(video_id, 62, "Хронометраж", "Анализирую темы в сохраненной транскрибации")
transcript = transcript_path.read_text(encoding="utf-8", errors="ignore")
chapters = generate_chapter_plan(video, transcript)
video.description = render_chapter_plan(chapters)
video.progress_percent = max(video.progress_percent or 0, 72)
video.progress_stage = "Хронометраж готов"
video.status = "planned"
session.commit()
append_progress(
video_id,
72,
"Хронометраж",
f"Готов план: {len(chapters)} тематических глав",
)
return {"status": "ready", "videoId": video_id, "chapterCount": len(chapters)}
except Exception as exc:
session.rollback()
video = session.get(Video, video_id)
if video:
video.status = "error"
video.error_message = str(exc)
video.progress_stage = "Ошибка"
session.commit()
append_progress(video_id, None, "Ошибка", str(exc), status="error")
raise
def download_video(video: Video) -> Path: def download_video(video: Video) -> Path:
if video.local_video_path: if video.local_video_path:
candidate = Path(video.local_video_path) candidate = Path(video.local_video_path)
if candidate.exists() and candidate.is_file() and candidate.stat().st_size > 0: if candidate.exists() and candidate.is_file() and candidate.stat().st_size > 0:
append_progress(video.id, 35, "Скачивание", f"Использую уже скачанный файл: {candidate}") append_progress(video.id, 35, "Подготовка видео", f"Использую сохраненный локальный файл: {candidate.name}")
return candidate return candidate
target_dir = settings.videos_path / str(video.id) target_dir = settings.videos_path / str(video.id)
target_dir.mkdir(parents=True, exist_ok=True) target_dir.mkdir(parents=True, exist_ok=True)
target = target_dir / "video.%(ext)s" target = target_dir / "video.%(ext)s"
append_progress(video.id, 10, "Скачивание", "Локального файла нет, скачиваю видео из источника")
command = ytdlp_base_args() + [ command = ytdlp_base_args() + [
"-f", "-f",
"bestvideo[height<=720]+bestaudio/best[height<=720]/best", "bestvideo[height<=720]+bestaudio/best[height<=720]/best",
@ -850,6 +935,69 @@ def normalize_selected_chapters(chapters: list[dict[str, Any]] | None, duration_
return sorted(normalized, key=lambda chapter: chapter["startSeconds"]) return sorted(normalized, key=lambda chapter: chapter["startSeconds"])
def generate_chapter_plan(video: Video, transcript: str) -> list[dict[str, int | str]]:
if not settings.llm_api_url.strip() or not settings.llm_api_key.strip():
raise RuntimeError("LLM-редактор не настроен. Хронометраж не создан.")
duration = video.duration_seconds
if not duration or duration < CHAPTER_PLAN_MIN_DURATION_SECONDS:
return []
transcript = transcript.strip()
if len(transcript) > settings.llm_max_transcript_chars:
transcript = transcript[: settings.llm_max_transcript_chars] + "\n\n[Транскрипт обрезан по лимиту контекста.]"
user_prompt = f"""Название ролика:
{video.title}
Длительность ролика: {format_video_duration(duration)}.
Транскрипт:
{transcript}
Составь тематический хронометраж ролика. Верни только JSON указанного формата."""
payload = parse_llm_json(
call_llm(
user_prompt,
system_prompt=CHAPTER_PLAN_SYSTEM_PROMPT,
include_editor_instructions=False,
)
)
return normalize_chapter_plan(payload, duration)
def normalize_chapter_plan(payload: dict[str, Any], duration_seconds: int) -> list[dict[str, int | str]]:
raw_chapters = payload.get("chapters")
if not isinstance(raw_chapters, list):
raise RuntimeError("LLM не вернул массив chapters для хронометража.")
by_start: dict[int, dict[str, int | str]] = {}
for item in raw_chapters:
if not isinstance(item, dict):
continue
try:
start = int(item.get("startSeconds"))
except (TypeError, ValueError):
continue
if start < 0 or start >= duration_seconds or start in by_start:
continue
title = clean_generated_text(str(item.get("title") or ""))
title = re.sub(r"\s+", " ", title).strip(" -—–\t\n")[:180]
if not title:
continue
by_start[start] = {"title": title, "startSeconds": start}
chapters = [by_start[start] for start in sorted(by_start)]
if len(chapters) < 2:
raise RuntimeError("LLM вернул слишком мало тематических глав для длинного ролика.")
chapters[0]["startSeconds"] = 0
return chapters
def render_chapter_plan(chapters: list[dict[str, int | str]]) -> str:
return "\n".join(
f"{seconds_to_timecode(int(chapter['startSeconds']))} {chapter['title']}"
for chapter in chapters
)
def transcript_slice_by_time(transcript: str, start_seconds: int, end_seconds: int | None, duration_seconds: int | None) -> str: def transcript_slice_by_time(transcript: str, start_seconds: int, end_seconds: int | None, duration_seconds: int | None) -> str:
if not duration_seconds or duration_seconds <= 0: if not duration_seconds or duration_seconds <= 0:
return transcript return transcript
@ -996,30 +1144,35 @@ def article_count_instruction(video: Video) -> str:
return "Сделай одну цельную статью, если нет явно отдельной второй темы." return "Сделай одну цельную статью, если нет явно отдельной второй темы."
def call_llm(user_prompt: str) -> str: def call_llm(
user_prompt: str,
system_prompt: str | None = None,
include_editor_instructions: bool = True,
) -> str:
url = settings.llm_api_url.rstrip("/") + "/chat/completions" url = settings.llm_api_url.rstrip("/") + "/chat/completions"
headers = { headers = {
"Authorization": f"Bearer {settings.llm_api_key}", "Authorization": f"Bearer {settings.llm_api_key}",
"Content-Type": "application/json", "Content-Type": "application/json",
} }
system_prompt = ARTICLE_SYSTEM_PROMPT resolved_system_prompt = system_prompt or ARTICLE_SYSTEM_PROMPT
with SessionLocal() as session: if include_editor_instructions:
extra_instructions = session.scalar( with SessionLocal() as session:
select(AppSetting.value).where(AppSetting.key == "llm_instructions") extra_instructions = session.scalar(
) or "" select(AppSetting.value).where(AppSetting.key == "llm_instructions")
if extra_instructions.strip(): ) or ""
system_prompt += ( if extra_instructions.strip():
"\n\nДОПОЛНИТЕЛЬНЫЕ ИНСТРУКЦИИ РЕДАКТОРА:\n" resolved_system_prompt += (
"Ниже приведены настройки редактора. Учитывай их вместе с основными правилами, " "\n\nДОПОЛНИТЕЛЬНЫЕ ИНСТРУКЦИИ РЕДАКТОРА:\n"
"если они не противоречат формату JSON и системным ограничениям.\n" "Ниже приведены настройки редактора. Учитывай их вместе с основными правилами, "
"---\n" "если они не противоречат формату JSON и системным ограничениям.\n"
f"{extra_instructions.strip()}\n" "---\n"
"---" f"{extra_instructions.strip()}\n"
) "---"
)
payload = { payload = {
"model": settings.llm_model, "model": settings.llm_model,
"messages": [ "messages": [
{"role": "system", "content": system_prompt}, {"role": "system", "content": resolved_system_prompt},
{"role": "user", "content": user_prompt}, {"role": "user", "content": user_prompt},
], ],
"temperature": 0.15, "temperature": 0.15,

View file

@ -0,0 +1,224 @@
# Local Video Upload Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use subagent-driven development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Let an authenticated administrator upload local video files to the Dzen Assistant, process them through the existing Whisper and Timeweb pipeline, track every stage, and store files exclusively on the dedicated 100 GB disk.
**Architecture:** API streams an uploaded file into the already-mounted `/app/data/videos/{video_id}` directory and creates the existing `Video` record. The current worker sees `local_video_path`, skips yt-dlp and continues from transcription. React uses XMLHttpRequest for byte-level upload progress, then switches the same card to its existing API/WebSocket processing log. A small capacity endpoint reads filesystem statistics for `videos_path`.
**Tech Stack:** FastAPI, Python multipart upload, ffprobe, SQLAlchemy/SQLite, Celery/Redis, React 19, TypeScript, Tailwind, Lucide, pytest, Docker Compose bind mounts.
---
### Task 1: Test and implement storage helpers
**Files:**
- Modify: `app/config.py`
- Create: `tests/test_video_storage.py`
- [ ] **Step 1: Write failing tests for allowed local video extensions and disk capacity payload.**
```python
from pathlib import Path
from app.config import Settings
def test_video_storage_path_is_the_dedicated_videos_mount(tmp_path: Path):
settings = Settings(storage_dir=str(tmp_path / "data"), video_storage_dir=str(tmp_path / "disk" / "videos"))
assert settings.videos_path == tmp_path / "disk" / "videos"
```
- [ ] **Step 2: Run the focused test and confirm it fails because `video_storage_dir` does not exist.**
Run: `python -m unittest tests.test_video_storage -v`
- [ ] **Step 3: Add `video_storage_dir` to Settings and make `videos_path` resolve it.**
```python
video_storage_dir: str = "/app/data/videos"
@property
def videos_path(self) -> Path:
return Path(self.video_storage_dir)
```
- [ ] **Step 4: Run `python -m unittest tests.test_video_storage -v` and commit the focused configuration change.**
### Task 2: Implement uploaded-video API and capacity endpoint
**Files:**
- Modify: `app/routes.py`
- Create: `tests/test_video_upload_routes.py`
- [ ] **Step 1: Add failing route tests with a temporary Settings fixture.**
```python
def test_upload_rejects_unsupported_extension(client):
response = client.post("/api/videos/upload", files={"file": ("notes.txt", b"text", "text/plain")})
assert response.status_code == 422
def test_storage_endpoint_returns_byte_counts(client):
response = client.get("/api/storage/videos")
assert response.status_code == 200
assert {"totalBytes", "usedBytes", "freeBytes", "usedPercent"} <= response.json().keys()
```
- [ ] **Step 2: Run `python -m unittest tests.test_video_upload_routes -v`; expect missing route failures.**
- [ ] **Step 3: Add upload constants, safe extension validation and an ffprobe helper.**
```python
ALLOWED_VIDEO_EXTENSIONS = {".mp4", ".webm", ".mov", ".mkv"}
MAX_UPLOAD_BYTES = 10 * 1024 * 1024 * 1024
def uploaded_video_duration(path: Path) -> int | None:
result = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", str(path)],
capture_output=True, text=True, timeout=30, check=False,
)
return round(float(result.stdout.strip())) if result.returncode == 0 and result.stdout.strip() else None
```
- [ ] **Step 4: Add `POST /api/videos/upload`.**
The route must create the `Video` row first with `external_id="upload:{uuid4().hex}"`, `source_url="upload://{id}"`, `published_at=datetime.now(timezone.utc)`, `status="new"` and a start log. Stream the upload in 1 MiB chunks into `settings.videos_path / str(video.id) / "video{suffix}"`; update no more than once per 5 MiB in `progress_log`, enforce the 10 GiB limit and current `shutil.disk_usage(settings.videos_path).free`. On success run ffprobe, set `local_video_path`, duration, `progress_percent=0`, `progress_stage="Готов к обработке"`, title from the basename and a completion log. On every failure remove only the created video directory and roll back the new row.
- [ ] **Step 5: Add `GET /api/storage/videos`.**
```python
usage = shutil.disk_usage(settings.videos_path)
return {
"totalBytes": usage.total,
"usedBytes": usage.used,
"freeBytes": usage.free,
"usedPercent": round(usage.used / usage.total * 100) if usage.total else 0,
}
```
- [ ] **Step 6: Run the route tests, `python -m compileall app`, and commit.**
### Task 3: Complete worker and deletion semantics for uploaded files
**Files:**
- Modify: `app/worker.py`
- Modify: `app/routes.py`
- Create: `tests/test_local_video_lifecycle.py`
- [ ] **Step 1: Write failing tests for local-file processing and safe deletion.**
```python
def test_download_video_reuses_uploaded_file(video, tmp_path):
uploaded = tmp_path / "12" / "video.mp4"
uploaded.parent.mkdir()
uploaded.write_bytes(b"video")
video.local_video_path = str(uploaded)
assert download_video(video) == uploaded
def test_delete_uploaded_video_removes_only_its_directory(client, uploaded_video):
response = client.delete(f"/api/videos/{uploaded_video.id}")
assert response.status_code == 200
assert not Path(uploaded_video.local_video_path).parent.exists()
```
- [ ] **Step 2: Run `python -m unittest tests.test_local_video_lifecycle -v`; expect the delete-file assertion to fail.**
- [ ] **Step 3: Update `download_video` log text to distinguish a manually uploaded local file from an already-downloaded VK file.**
```python
append_progress(video.id, 35, "Подготовка", "Использую загруженный видеофайл")
```
- [ ] **Step 4: Update `DELETE /api/videos/{video_id}` to remove `settings.videos_path / str(video.id)` only after resolving it and verifying it is a child of `settings.videos_path`.**
```python
video_dir = (settings.videos_path / str(video.id)).resolve()
root = settings.videos_path.resolve()
if video_dir.is_relative_to(root):
shutil.rmtree(video_dir, ignore_errors=True)
```
- [ ] **Step 5: Run lifecycle tests and commit.**
### Task 4: Build the upload and disk UI
**Files:**
- Modify: `admin/src/App.tsx`
- Modify: `admin/src/index.css` only if a reusable drop-zone style is needed
- [ ] **Step 1: Define TypeScript contracts and state.**
```ts
type VideoStorage = {
totalBytes: number
usedBytes: number
freeBytes: number
usedPercent: number
}
type UploadProgress = {
name: string
loaded: number
total: number
}
```
- [ ] **Step 2: Add an XMLHttpRequest upload helper.**
```ts
function uploadVideoFile(file: File) {
return new Promise<Video>((resolve, reject) => {
const request = new XMLHttpRequest()
request.upload.onprogress = (event) => {
if (event.lengthComputable) setUploadProgress({ name: file.name, loaded: event.loaded, total: event.total })
}
request.open("POST", "/api/videos/upload")
request.withCredentials = true
request.onload = () => request.status >= 200 && request.status < 300 ? resolve(JSON.parse(request.responseText)) : reject(new Error(request.responseText))
request.onerror = () => reject(new Error("Не удалось загрузить видео."))
const data = new FormData(); data.append("file", file); request.send(data)
})
}
```
- [ ] **Step 3: Add a compact drop zone above the left list.**
It accepts click-to-select and drag-and-drop, uses the `Upload` Lucide icon, presents the file name and exact MB count during transfer, disables duplicate submissions and uses existing toast notifications. It is responsive: input and progress stack on mobile.
- [ ] **Step 4: Add the dedicated-disk progress indicator beside the upload zone.**
It loads `/api/storage/videos` on dashboard entry and after successful upload/delete. Render `Видео на диске`, a percentage bar and `свободно X из Y`; use amber only below 10 GiB free.
- [ ] **Step 5: Ensure success refreshes video data and opens no modal.**
The uploaded video should appear first because the API already sorts manual videos by `published_at` at creation time.
- [ ] **Step 6: Run `npm run build` and commit.**
### Task 5: Integrate and validate in Docker production
**Files:**
- Modify: `.env.example` if present, otherwise none
- Modify: `docker-compose.yml` only if `VIDEO_STORAGE_DIR=/app/data/videos` needs explicit documentation
- [ ] **Step 1: Verify mount isolation.**
Run: `docker inspect dzen-assistant-api --format '{{range .Mounts}}{{println .Source .Destination}}{{end}}'`
Expected: `/var/www/dzen.nstarikov.ru/storage/videos /app/data/videos` alongside the ordinary `./data /app/data` mount.
- [ ] **Step 2: Build and recreate API and worker.**
Run: `docker compose build api worker && docker compose up -d --no-build api worker`
Expected: both containers are `Up` and `https://dzen.nstarikov.ru/health` returns `{"status":"ok"}`.
- [ ] **Step 3: Perform the live acceptance path.**
Upload a small MP4 through the admin: confirm megabyte progress, inspect its `storage/videos/{id}` file, run processing and confirm log sequence starts with the uploaded-file message. Delete it and verify only that directory disappears while another video directory remains.
- [ ] **Step 4: Run full verification and commit/push.**
Run: `python -m unittest discover -s tests -v && (cd admin && npm run build) && git diff --check`
Commit only files from this feature, push `main` to Forgejo, and re-check production health plus `/api/storage/videos` while authenticated.

View file

@ -0,0 +1,50 @@
# Локальная загрузка видео в Дзен-ассистент
## Цель
Добавить в админку второй способ получения ролика: загрузку видеофайла с компьютера. После загрузки файл проходит уже существующий конвейер обработки наравне с видео из VK.
## Пользовательский сценарий
1. В верхней части колонки «Ролики» администратор выбирает файл или перетаскивает его в зону загрузки.
2. Карточка загрузки показывает имя файла, процент и точные байты в формате «384 МБ из 1,2 ГБ».
3. После завершения передачи создаётся обычный ролик со статусом «Новый». Его дата добавления используется для сортировки, поэтому он находится вверху списка.
4. В карточке доступны существующие действия: запустить обработку, посмотреть журнал, открыть черновики, удалить ролик.
5. При обработке локальный файл пропускает этап скачивания: worker использует его сразу, создаёт или переиспользует транскрипцию, выбирает кадры и обращается к Timeweb AI.
6. Для ролика длиннее 20 минут интерфейс запрашивает хронометраж через существующий маршрут глав. Администратор выбирает темы галочками; для каждой выбранной темы создаётся отдельный черновик.
7. Удаление ролика удаляет запись, связанные черновики по существующему правилу и каталог файла на внешнем диске. Удалённый вручную ролик не может повторно попасть из VK-импорта.
## Хранение
Внешний диск смонтирован в `/var/www/dzen.nstarikov.ru/storage`. Для видео используется только каталог:
`/var/www/dzen.nstarikov.ru/storage/videos/{video_id}/video.{extension}`
В Docker API и worker получают его как `/app/data/videos` через отдельный bind mount. База SQLite, транскрипции, изображения и RSS-данные остаются в `./data` на системном диске.
## API и обработка
Новый POST-маршрут принимает multipart-загрузку. Сервер сохраняет поток частями, ограничивает допустимые расширения (`mp4`, `webm`, `mov`, `mkv`) и отказывает при размере больше 10 ГБ. После записи он определяет длительность через ffprobe, создаёт Video с источником `upload`, сохраняет локальный путь и возвращает payload карточки.
Прогресс передачи считается браузером через XMLHttpRequest upload events: загруженные и общие байты видны до ответа сервера. После ответа карточка начинает использовать существующие `progressPercent`, `progressStage` и WebSocket-логи обработки.
Логи upload добавляются в Video.progress_log: начало, записанный размер, путь без служебных деталей и завершение. Worker дописывает в тот же журнал все этапы: подготовка, транскрибация, главы, кадры, Timeweb AI и количество созданных черновиков. Для локального файла лог явно сообщает «Использую загруженный файл».
## Индикатор диска
Новый GET-маршрут возвращает размер, занятое и свободное место файловой системы, на которой находится `settings.video_path`. На главной странице компактный progress-bar показывает «Видео: 2,4 ГБ из 98 ГБ» и свободное место. Если свободно меньше 10 ГБ, состояние меняется на предупреждающее; загрузка блокируется только при фактической нехватке места на сервере.
## Целостность и ошибки
- Неподдерживаемый формат, отсутствие места, прерванная передача или ошибка ffprobe возвращают понятную ошибку; частично загруженный файл удаляется.
- Ролик не запускается автоматически: пользователь сначала видит завершённую загрузку и выбирает обычную обработку или темы.
- Файл сохраняется под ID ролика, а не под исходным именем, чтобы исключить коллизии и небезопасные пути.
- Удаление видео выполняется только после удаления записи из очереди; каталог удаляется строго внутри `settings.video_path / str(video.id)`.
## Проверка
1. Загрузить небольшой MP4 и сверить отображаемые мегабайты и запись на внешнем диске.
2. Запустить обработку и убедиться, что WebSocket-журнал продолжается с этапа «загруженный файл» без yt-dlp.
3. Загрузить ролик дольше 20 минут, получить главы, выбрать несколько тем и проверить создание нескольких черновиков.
4. Удалить ролик и подтвердить отсутствие его каталога на внешнем диске.
5. Проверить API-индикатор диска и мобильную вёрстку зоны загрузки.

View file

@ -0,0 +1,92 @@
import asyncio
import io
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
from unittest.mock import patch
from fastapi import HTTPException, UploadFile
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from app.config import Settings
from app.database import Base
from app.models import Video
from app.routes import delete_video_storage_dir, upload_video, video_storage_payload
class VideoUploadRouteTest(unittest.TestCase):
def setUp(self):
self.temp_dir = TemporaryDirectory()
root = Path(self.temp_dir.name)
self.settings = Settings(storage_dir=str(root / "data"))
self.engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(self.engine)
def tearDown(self):
self.temp_dir.cleanup()
def test_upload_streams_supported_video_to_dedicated_video_path(self):
file = UploadFile(filename="briefing.mp4", file=io.BytesIO(b"video-bytes"))
with Session(self.engine) as session, patch("app.routes.uploaded_video_duration", return_value=123):
payload = asyncio.run(upload_video(file, session, self.settings))
video = session.get(Video, payload["id"])
target = self.settings.videos_path / str(payload["id"]) / "video.mp4"
self.assertEqual(target.read_bytes(), b"video-bytes")
self.assertEqual(video.local_video_path, str(target))
self.assertEqual(video.duration_seconds, 123)
self.assertTrue(video.external_id.startswith("upload:"))
self.assertIn("Длительность определена", video.progress_log)
def test_upload_rejects_unsupported_extension(self):
file = UploadFile(filename="notes.txt", file=io.BytesIO(b"text"))
with Session(self.engine) as session:
with self.assertRaises(HTTPException) as error:
asyncio.run(upload_video(file, session, self.settings))
self.assertEqual(error.exception.status_code, 422)
def test_upload_cleans_video_row_and_partial_file_when_probe_fails(self):
file = UploadFile(filename="broken.mp4", file=io.BytesIO(b"not-a-video"))
with Session(self.engine) as session, patch(
"app.routes.uploaded_video_duration",
side_effect=HTTPException(status_code=422, detail="Видео не распознано."),
):
with self.assertRaises(HTTPException):
asyncio.run(upload_video(file, session, self.settings))
self.assertEqual(session.query(Video).count(), 0)
self.assertEqual(list(self.settings.videos_path.glob("*")), [])
def test_storage_payload_reports_capacity_bytes(self):
payload = video_storage_payload(self.settings)
self.assertEqual(set(payload), {"totalBytes", "usedBytes", "freeBytes", "usedPercent", "freePercent"})
self.assertGreater(payload["totalBytes"], 0)
self.assertGreaterEqual(payload["usedPercent"], 0)
def test_delete_storage_dir_removes_only_target_video_directory(self):
with Session(self.engine) as session:
video = Video(external_id="upload:delete", source_url="upload://delete", title="Delete")
session.add(video)
session.commit()
session.refresh(video)
target = self.settings.videos_path / str(video.id)
neighbour = self.settings.videos_path / str(video.id + 1)
target.mkdir(parents=True)
neighbour.mkdir(parents=True)
(target / "video.mp4").write_bytes(b"video")
(neighbour / "video.mp4").write_bytes(b"other")
video.local_video_path = str(target / "video.mp4")
delete_video_storage_dir(video, self.settings)
self.assertFalse(target.exists())
self.assertTrue((neighbour / "video.mp4").exists())
self.assertIsNone(video.local_video_path)
if __name__ == "__main__":
unittest.main()

View file

@ -0,0 +1,28 @@
import unittest
from app.worker import normalize_chapter_plan, render_chapter_plan
class ChapterPlanTest(unittest.TestCase):
def test_normalize_chapter_plan_makes_first_topic_start_at_zero(self):
chapters = normalize_chapter_plan(
{
"chapters": [
{"title": "Вступление", "startSeconds": 12},
{"title": "Основная тема", "startSeconds": 340},
]
},
900,
)
self.assertEqual(chapters[0]["startSeconds"], 0)
self.assertEqual(chapters[1]["startSeconds"], 340)
self.assertIn("00:00 Вступление", render_chapter_plan(chapters))
def test_normalize_chapter_plan_rejects_single_topic(self):
with self.assertRaisesRegex(RuntimeError, "слишком мало"):
normalize_chapter_plan({"chapters": [{"title": "Тема", "startSeconds": 0}]}, 900)
if __name__ == "__main__":
unittest.main()