From 3b98061b16864025cfeb3489af8c72f1de7fdae3 Mon Sep 17 00:00:00 2001 From: nstarikov Date: Tue, 11 Aug 2026 17:53:54 +0300 Subject: [PATCH] feat: generate article images with Polza --- dzen-assistant/admin/src/App.tsx | 370 +++++++++++++++++- dzen-assistant/admin/src/index.css | 9 + dzen-assistant/app/database.py | 2 +- dzen-assistant/app/image_generation.py | 256 ++++++++++++ dzen-assistant/app/models.py | 40 ++ dzen-assistant/app/routes.py | 151 ++++++- dzen-assistant/app/worker.py | 93 +++++ dzen-assistant/tests/test_image_generation.py | 50 +++ 8 files changed, 959 insertions(+), 12 deletions(-) create mode 100644 dzen-assistant/app/image_generation.py create mode 100644 dzen-assistant/tests/test_image_generation.py diff --git a/dzen-assistant/admin/src/App.tsx b/dzen-assistant/admin/src/App.tsx index bfe4b65..b8638ef 100644 --- a/dzen-assistant/admin/src/App.tsx +++ b/dzen-assistant/admin/src/App.tsx @@ -34,6 +34,30 @@ import { Input } from "@/components/ui/input" type AppSettings = { signatureHtml: string llmInstructions: string + imageApiUrl: string + imageModel: string + imageApiTokenConfigured: boolean +} + +type ImageGenerationTarget = "cover" | "middle" | "final" + +type ImageGenerationJob = { + id: string + target: ImageGenerationTarget + status: string + progress: number + stage: string + localUrl?: string + errorCode?: string + errorMessage?: string + targetBlockId?: string + snapshotId?: string +} + +type ImageGenerationBatch = { + batchId: string + status: string + jobs: ImageGenerationJob[] } type VideoArticle = { @@ -118,6 +142,10 @@ type RandomFrameTuneConfig = { onReplace?: (block: BlockAPI) => void | Promise } +type ImageGenerationTuneConfig = { + onRegenerate?: (block: BlockAPI) => void | Promise +} + const ARTICLES_PAGE_SIZE = 10 const CHAPTER_SELECTION_STORAGE_PREFIX = "dzen:selected-chapters:" @@ -190,6 +218,30 @@ class RandomFrameTune { } } +class ImageGenerationTune { + private readonly block: BlockAPI + private readonly config: ImageGenerationTuneConfig + + static get isTune() { + return true + } + + constructor({ block, config }: { block: BlockAPI; config?: ImageGenerationTuneConfig }) { + this.block = block + this.config = config ?? {} + } + + render() { + return { + icon: '', + label: "Перегенерировать по тексту", + onActivate: () => { + void this.config.onRegenerate?.(this.block) + }, + } + } +} + const editorI18n = { messages: { ui: { @@ -654,8 +706,44 @@ function editorDataToPlainText(data: OutputData, title?: string): string { return parts.join("\n\n").trim() } +function imageBlockData(url: string, caption: string) { + return { + file: { url }, + caption, + withBorder: false, + withBackground: false, + stretched: false, + } +} + +function nearestHeadingIndex(blocks: EditorBlock[], preferredIndex: number) { + const headingIndexes = blocks + .map((block, index) => block.type === "header" ? index : -1) + .filter((index) => index >= 0) + if (!headingIndexes.length) return preferredIndex + return headingIndexes.reduce((closest, index) => + Math.abs(index - preferredIndex) < Math.abs(closest - preferredIndex) ? index : closest + ) +} + +function generatedImagePlacementIndex(data: OutputData, target: Exclude) { + const blocks = data.blocks || [] + const imageIndexes = blocks.map((block, index) => block.type === "image" ? index : -1).filter((index) => index >= 0) + if (target === "middle" && imageIndexes.length) return imageIndexes[0] + if (target === "final" && imageIndexes.length > 1) return imageIndexes[imageIndexes.length - 1] + const preferredIndex = Math.floor(blocks.length * (target === "middle" ? 1 / 3 : 2 / 3)) + return nearestHeadingIndex(blocks, preferredIndex) +} + function SettingsPanel({ onBack, onSaved }: { onBack: () => void; onSaved: (settings: AppSettings) => void }) { - const [settings, setSettings] = useState({ signatureHtml: "", llmInstructions: "" }) + const [settings, setSettings] = useState({ + signatureHtml: "", + llmInstructions: "", + imageApiUrl: "https://polza.ai/api", + imageModel: "google/gemini-3.1-flash-image", + imageApiTokenConfigured: false, + }) + const [imageApiToken, setImageApiToken] = useState("") const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) const [dirty, setDirty] = useState(false) @@ -717,9 +805,15 @@ function SettingsPanel({ onBack, onSaved }: { onBack: () => void; onSaved: (sett const next: AppSettings = { signatureHtml: htmlToPlainText(serializedSignature).trim() ? serializedSignature : "", llmInstructions: settings.llmInstructions.trim(), + imageApiUrl: settings.imageApiUrl.trim(), + imageModel: settings.imageModel.trim(), + imageApiTokenConfigured: settings.imageApiTokenConfigured, } - const saved = await api("/api/settings", { method: "PUT", body: JSON.stringify(next) }) + const payload: Record = { ...next } + if (imageApiToken.trim()) payload.imageApiToken = imageApiToken.trim() + const saved = await api("/api/settings", { method: "PUT", body: JSON.stringify(payload) }) setSettings(saved) + setImageApiToken("") setDirty(false) setMessage("Настройки сохранены") onSaved(saved) @@ -730,6 +824,32 @@ function SettingsPanel({ onBack, onSaved }: { onBack: () => void; onSaved: (sett } } + async function clearImageApiToken() { + if (!window.confirm("Удалить токен Polza? Генерация изображений станет недоступна до ввода нового токена.")) return + setSaving(true) + try { + const saved = await api("/api/settings", { + method: "PUT", + body: JSON.stringify({ + signatureHtml: settings.signatureHtml, + llmInstructions: settings.llmInstructions, + imageApiUrl: settings.imageApiUrl.trim(), + imageModel: settings.imageModel.trim(), + deleteImageApiToken: true, + }), + }) + setSettings(saved) + setImageApiToken("") + setDirty(false) + setMessage("Токен удалён") + onSaved(saved) + } catch (error) { + setMessage(`Не удалось удалить токен: ${error instanceof Error ? error.message : String(error)}`) + } finally { + setSaving(false) + } + } + async function registerPasskey() { setPasskeyBusy(true) try { @@ -790,6 +910,53 @@ function SettingsPanel({ onBack, onSaved }: { onBack: () => void; onSaved: (sett )} + {!loading ? ( + + + Генерация изображений + Polza вызывается только с сервера. Токен не возвращается в браузер и не попадает в черновики. + + + + +
+
+ + + {settings.imageApiTokenConfigured ? "Токен задан" : "Токен не задан"} + +
+
+ { setImageApiToken(event.target.value); setDirty(true) }} + /> + {settings.imageApiTokenConfigured ? : null} +
+

Пустое поле не меняет уже сохранённый токен.

+
+
+
+ ) : null}
-

Редактируйте блоки как в Medium. Для картинки выберите image-блок и нажмите кнопку случайного кадра.

+

Редактируйте блоки как в Medium. У изображения доступны случайный кадр и перегенерация по смыслу текста.

+ @@ -2171,6 +2494,15 @@ export default function App() { Выбрать +
+ {imageGenerationBatch ? ( +
+
+
+

Генерация изображений

+

Статус: {imageGenerationBatch.status}

+
+ {["completed", "completed_with_errors", "failed"].includes(imageGenerationBatch.status) ? Завершено : Выполняется} +
+
+ {imageGenerationBatch.jobs.map((job) => { + const label = job.target === "cover" ? "Обложка" : job.target === "middle" ? "Вторая часть" : "Финальная часть" + const canApply = job.status === "ready" && Boolean(job.localUrl) && !appliedImageGenerationJobsRef.current.has(job.id) + return ( +
+
+ {label} + {job.progress || 0}% +
+
+

{job.errorMessage || job.stage || job.status}

+ {canApply ? : null} +
+ ) + })} +
+
+ ) : null}