feat: generate article images with Polza
This commit is contained in:
parent
c2ea4fd580
commit
3b98061b16
8 changed files with 959 additions and 12 deletions
|
|
@ -34,6 +34,30 @@ import { Input } from "@/components/ui/input"
|
||||||
type AppSettings = {
|
type AppSettings = {
|
||||||
signatureHtml: string
|
signatureHtml: string
|
||||||
llmInstructions: 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 = {
|
type VideoArticle = {
|
||||||
|
|
@ -118,6 +142,10 @@ type RandomFrameTuneConfig = {
|
||||||
onReplace?: (block: BlockAPI) => void | Promise<void>
|
onReplace?: (block: BlockAPI) => void | Promise<void>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ImageGenerationTuneConfig = {
|
||||||
|
onRegenerate?: (block: BlockAPI) => void | Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
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:"
|
||||||
|
|
||||||
|
|
@ -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: '<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-2.64-6.36"/><path d="M21 3v6h-6"/></svg>',
|
||||||
|
label: "Перегенерировать по тексту",
|
||||||
|
onActivate: () => {
|
||||||
|
void this.config.onRegenerate?.(this.block)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const editorI18n = {
|
const editorI18n = {
|
||||||
messages: {
|
messages: {
|
||||||
ui: {
|
ui: {
|
||||||
|
|
@ -654,8 +706,44 @@ function editorDataToPlainText(data: OutputData, title?: string): string {
|
||||||
return parts.join("\n\n").trim()
|
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<ImageGenerationTarget, "cover">) {
|
||||||
|
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 }) {
|
function SettingsPanel({ onBack, onSaved }: { onBack: () => void; onSaved: (settings: AppSettings) => void }) {
|
||||||
const [settings, setSettings] = useState<AppSettings>({ signatureHtml: "", llmInstructions: "" })
|
const [settings, setSettings] = useState<AppSettings>({
|
||||||
|
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 [loading, setLoading] = useState(true)
|
||||||
const [saving, setSaving] = useState(false)
|
const [saving, setSaving] = useState(false)
|
||||||
const [dirty, setDirty] = useState(false)
|
const [dirty, setDirty] = useState(false)
|
||||||
|
|
@ -717,9 +805,15 @@ function SettingsPanel({ onBack, onSaved }: { onBack: () => void; onSaved: (sett
|
||||||
const next: AppSettings = {
|
const next: AppSettings = {
|
||||||
signatureHtml: htmlToPlainText(serializedSignature).trim() ? serializedSignature : "",
|
signatureHtml: htmlToPlainText(serializedSignature).trim() ? serializedSignature : "",
|
||||||
llmInstructions: settings.llmInstructions.trim(),
|
llmInstructions: settings.llmInstructions.trim(),
|
||||||
|
imageApiUrl: settings.imageApiUrl.trim(),
|
||||||
|
imageModel: settings.imageModel.trim(),
|
||||||
|
imageApiTokenConfigured: settings.imageApiTokenConfigured,
|
||||||
}
|
}
|
||||||
const saved = await api<AppSettings>("/api/settings", { method: "PUT", body: JSON.stringify(next) })
|
const payload: Record<string, unknown> = { ...next }
|
||||||
|
if (imageApiToken.trim()) payload.imageApiToken = imageApiToken.trim()
|
||||||
|
const saved = await api<AppSettings>("/api/settings", { method: "PUT", body: JSON.stringify(payload) })
|
||||||
setSettings(saved)
|
setSettings(saved)
|
||||||
|
setImageApiToken("")
|
||||||
setDirty(false)
|
setDirty(false)
|
||||||
setMessage("Настройки сохранены")
|
setMessage("Настройки сохранены")
|
||||||
onSaved(saved)
|
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<AppSettings>("/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() {
|
async function registerPasskey() {
|
||||||
setPasskeyBusy(true)
|
setPasskeyBusy(true)
|
||||||
try {
|
try {
|
||||||
|
|
@ -790,6 +910,53 @@ function SettingsPanel({ onBack, onSaved }: { onBack: () => void; onSaved: (sett
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{!loading ? (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Генерация изображений</CardTitle>
|
||||||
|
<CardDescription>Polza вызывается только с сервера. Токен не возвращается в браузер и не попадает в черновики.</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<label className="grid gap-1.5 text-sm font-medium sm:col-span-1">
|
||||||
|
API URL
|
||||||
|
<Input
|
||||||
|
value={settings.imageApiUrl}
|
||||||
|
placeholder="https://polza.ai/api"
|
||||||
|
onChange={(event) => { setSettings((current) => ({ ...current, imageApiUrl: event.target.value })); setDirty(true) }}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="grid gap-1.5 text-sm font-medium sm:col-span-1">
|
||||||
|
Модель
|
||||||
|
<Input
|
||||||
|
value={settings.imageModel}
|
||||||
|
placeholder="google/gemini-3.1-flash-image"
|
||||||
|
onChange={(event) => { setSettings((current) => ({ ...current, imageModel: event.target.value })); setDirty(true) }}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<div className="grid gap-1.5 sm:col-span-2">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<label className="text-sm font-medium" htmlFor="image-api-token">API-токен</label>
|
||||||
|
<span className={`text-xs ${settings.imageApiTokenConfigured ? "text-emerald-700" : "text-muted-foreground"}`}>
|
||||||
|
{settings.imageApiTokenConfigured ? "Токен задан" : "Токен не задан"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Input
|
||||||
|
id="image-api-token"
|
||||||
|
className="min-w-[14rem] flex-1"
|
||||||
|
type="password"
|
||||||
|
autoComplete="new-password"
|
||||||
|
value={imageApiToken}
|
||||||
|
placeholder={settings.imageApiTokenConfigured ? "Введите новый токен для замены" : "Введите токен Polza"}
|
||||||
|
onChange={(event) => { setImageApiToken(event.target.value); setDirty(true) }}
|
||||||
|
/>
|
||||||
|
{settings.imageApiTokenConfigured ? <Button type="button" variant="outline" disabled={saving} onClick={clearImageApiToken}>Удалить токен</Button> : null}
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">Пустое поле не меняет уже сохранённый токен.</p>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
) : null}
|
||||||
<div className="flex justify-end gap-2">
|
<div className="flex justify-end gap-2">
|
||||||
<Button disabled={passkeyBusy || loading} onClick={registerPasskey} variant="outline">
|
<Button disabled={passkeyBusy || loading} onClick={registerPasskey} variant="outline">
|
||||||
{passkeyBusy ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <Fingerprint data-icon="inline-start" />}
|
{passkeyBusy ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <Fingerprint data-icon="inline-start" />}
|
||||||
|
|
@ -949,7 +1116,13 @@ export default function App() {
|
||||||
const [authState, setAuthState] = useState<"loading" | "unauthenticated" | "authenticated">("loading")
|
const [authState, setAuthState] = useState<"loading" | "unauthenticated" | "authenticated">("loading")
|
||||||
const [hasPasskeys, setHasPasskeys] = useState(false)
|
const [hasPasskeys, setHasPasskeys] = useState(false)
|
||||||
const [activeView, setActiveView] = useState<"dashboard" | "settings">("dashboard")
|
const [activeView, setActiveView] = useState<"dashboard" | "settings">("dashboard")
|
||||||
const [appSettings, setAppSettings] = useState<AppSettings>({ signatureHtml: "", llmInstructions: "" })
|
const [appSettings, setAppSettings] = useState<AppSettings>({
|
||||||
|
signatureHtml: "",
|
||||||
|
llmInstructions: "",
|
||||||
|
imageApiUrl: "https://polza.ai/api",
|
||||||
|
imageModel: "google/gemini-3.1-flash-image",
|
||||||
|
imageApiTokenConfigured: false,
|
||||||
|
})
|
||||||
const [videos, setVideos] = useState<Video[]>([])
|
const [videos, setVideos] = useState<Video[]>([])
|
||||||
const [articles, setArticles] = useState<Article[]>([])
|
const [articles, setArticles] = useState<Article[]>([])
|
||||||
const [articlesHasMore, setArticlesHasMore] = useState(false)
|
const [articlesHasMore, setArticlesHasMore] = useState(false)
|
||||||
|
|
@ -965,6 +1138,8 @@ export default function App() {
|
||||||
const [featureImageBusy, setFeatureImageBusy] = useState(false)
|
const [featureImageBusy, setFeatureImageBusy] = useState(false)
|
||||||
const [featureImageDragActive, setFeatureImageDragActive] = useState(false)
|
const [featureImageDragActive, setFeatureImageDragActive] = useState(false)
|
||||||
const [featureImageHoverActive, setFeatureImageHoverActive] = useState(false)
|
const [featureImageHoverActive, setFeatureImageHoverActive] = useState(false)
|
||||||
|
const [imageGenerationBatch, setImageGenerationBatch] = useState<ImageGenerationBatch | null>(null)
|
||||||
|
const [imageGenerationStarting, setImageGenerationStarting] = useState(false)
|
||||||
const [copyToast, setCopyToast] = useState("")
|
const [copyToast, setCopyToast] = useState("")
|
||||||
const [statusMessage, setStatusMessage] = useState("")
|
const [statusMessage, setStatusMessage] = useState("")
|
||||||
const [busy, setBusy] = useState(false)
|
const [busy, setBusy] = useState(false)
|
||||||
|
|
@ -985,6 +1160,8 @@ export default function App() {
|
||||||
const articlesOffsetRef = useRef(0)
|
const articlesOffsetRef = useRef(0)
|
||||||
const articlesLoadingRef = useRef(false)
|
const articlesLoadingRef = useRef(false)
|
||||||
const articlesHasMoreRef = useRef(false)
|
const articlesHasMoreRef = useRef(false)
|
||||||
|
const appliedImageGenerationJobsRef = useRef<Set<string>>(new Set())
|
||||||
|
const imageGenerationPollRef = useRef<number | null>(null)
|
||||||
|
|
||||||
const handleAuthenticated = useCallback(() => {
|
const handleAuthenticated = useCallback(() => {
|
||||||
setAuthState("authenticated")
|
setAuthState("authenticated")
|
||||||
|
|
@ -1270,6 +1447,17 @@ export default function App() {
|
||||||
setEditorTitle(result.title)
|
setEditorTitle(result.title)
|
||||||
setPublishAt(toDateTimeLocalValue(result.publishedAt) || currentDateTimeLocalValue())
|
setPublishAt(toDateTimeLocalValue(result.publishedAt) || currentDateTimeLocalValue())
|
||||||
setEditorDirty(false)
|
setEditorDirty(false)
|
||||||
|
appliedImageGenerationJobsRef.current = new Set()
|
||||||
|
try {
|
||||||
|
const active = await fetch(`/api/articles/${id}/image-generations/active`)
|
||||||
|
if (active.status === 204) {
|
||||||
|
setImageGenerationBatch(null)
|
||||||
|
} else if (active.ok) {
|
||||||
|
setImageGenerationBatch(await active.json() as ImageGenerationBatch)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// The editor itself remains usable if a status recovery request fails.
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function publishArticle(id: number, scheduledAt?: string) {
|
async function publishArticle(id: number, scheduledAt?: string) {
|
||||||
|
|
@ -1370,7 +1558,7 @@ export default function App() {
|
||||||
},
|
},
|
||||||
image: {
|
image: {
|
||||||
class: ImageTool as unknown as ToolConstructable,
|
class: ImageTool as unknown as ToolConstructable,
|
||||||
tunes: ["randomFrame"],
|
tunes: ["randomFrame", "imageGeneration"],
|
||||||
config: {
|
config: {
|
||||||
captionPlaceholder: "Подпись к изображению",
|
captionPlaceholder: "Подпись к изображению",
|
||||||
uploader: {
|
uploader: {
|
||||||
|
|
@ -1400,6 +1588,12 @@ export default function App() {
|
||||||
onReplace: replaceWithRandomFrame,
|
onReplace: replaceWithRandomFrame,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
imageGeneration: {
|
||||||
|
class: ImageGenerationTune as unknown as ToolConstructable,
|
||||||
|
config: {
|
||||||
|
onRegenerate: (block: BlockAPI) => startImageGeneration(inlineImageGenerationTarget(block), block),
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
onChange: () => {
|
onChange: () => {
|
||||||
setEditorDirty(true)
|
setEditorDirty(true)
|
||||||
|
|
@ -1582,6 +1776,127 @@ export default function App() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function applyGeneratedImage(job: ImageGenerationJob) {
|
||||||
|
const article = selectedArticleRef.current
|
||||||
|
const editor = editorInstanceRef.current
|
||||||
|
if (!article || !job.localUrl || appliedImageGenerationJobsRef.current.has(job.id)) return false
|
||||||
|
if (job.target === "cover") {
|
||||||
|
setSelectedArticle((current) => current ? { ...current, featureImageUrl: job.localUrl } : current)
|
||||||
|
setEditorDirty(true)
|
||||||
|
appliedImageGenerationJobsRef.current.add(job.id)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if (!editor) return false
|
||||||
|
await editor.isReady
|
||||||
|
const count = editor.blocks.getBlocksCount()
|
||||||
|
let targetBlock: BlockAPI | null = null
|
||||||
|
if (job.targetBlockId) {
|
||||||
|
for (let index = 0; index < count; index += 1) {
|
||||||
|
const candidate = editor.blocks.getBlockByIndex(index)
|
||||||
|
if (candidate?.id === job.targetBlockId && candidate.name === "image") {
|
||||||
|
targetBlock = candidate
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!targetBlock) return false
|
||||||
|
} else {
|
||||||
|
const data = await editor.save()
|
||||||
|
const placement = generatedImagePlacementIndex(data, job.target)
|
||||||
|
const candidate = editor.blocks.getBlockByIndex(placement)
|
||||||
|
if (candidate?.name === "image") targetBlock = candidate
|
||||||
|
else {
|
||||||
|
editor.blocks.insert("image", imageBlockData(job.localUrl, imageCaptionFromPostTitle()), undefined, Math.min(placement, count), true)
|
||||||
|
setEditorDirty(true)
|
||||||
|
appliedImageGenerationJobsRef.current.add(job.id)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const previousData = await (targetBlock as unknown as { save: () => Promise<Record<string, any>> }).save()
|
||||||
|
await editor.blocks.update(targetBlock.id, {
|
||||||
|
...previousData,
|
||||||
|
file: { ...(previousData.file || {}), url: job.localUrl },
|
||||||
|
caption: previousData.caption || imageCaptionFromPostTitle(),
|
||||||
|
})
|
||||||
|
setEditorDirty(true)
|
||||||
|
appliedImageGenerationJobsRef.current.add(job.id)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function applyReadyImageGenerationJobs(batch: ImageGenerationBatch) {
|
||||||
|
for (const job of batch.jobs) {
|
||||||
|
if (job.status !== "ready" || !job.localUrl || appliedImageGenerationJobsRef.current.has(job.id)) continue
|
||||||
|
const applied = await applyGeneratedImage(job)
|
||||||
|
if (!applied && job.targetBlockId) {
|
||||||
|
setStatusMessage("Исходное изображение было изменено. Готовый результат сохранён — выберите «Применить» в списке генерации.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pollImageGeneration(batchId: string, articleId: number) {
|
||||||
|
const batch = await api<ImageGenerationBatch>(`/api/articles/${articleId}/image-generations/${batchId}`)
|
||||||
|
setImageGenerationBatch(batch)
|
||||||
|
await applyReadyImageGenerationJobs(batch)
|
||||||
|
}
|
||||||
|
|
||||||
|
function inlineImageGenerationTarget(block: BlockAPI): Exclude<ImageGenerationTarget, "cover"> {
|
||||||
|
const editor = editorInstanceRef.current
|
||||||
|
if (!editor) return "middle"
|
||||||
|
const imageBlocks: BlockAPI[] = []
|
||||||
|
for (let index = 0; index < editor.blocks.getBlocksCount(); index += 1) {
|
||||||
|
const candidate = editor.blocks.getBlockByIndex(index)
|
||||||
|
if (candidate?.name === "image") imageBlocks.push(candidate)
|
||||||
|
}
|
||||||
|
return imageBlocks.length > 1 && imageBlocks[imageBlocks.length - 1]?.id === block.id ? "final" : "middle"
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startImageGeneration(mode: "all" | ImageGenerationTarget, block?: BlockAPI) {
|
||||||
|
const article = selectedArticleRef.current
|
||||||
|
const editor = editorInstanceRef.current
|
||||||
|
if (!article || !editor || imageGenerationStarting) return
|
||||||
|
if (!appSettings.imageApiTokenConfigured) {
|
||||||
|
setStatusMessage("Для генерации изображений сначала укажите токен Polza в настройках.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setImageGenerationStarting(true)
|
||||||
|
try {
|
||||||
|
const editorData = await editor.save()
|
||||||
|
const snapshotId = crypto.randomUUID()
|
||||||
|
const payload: Record<string, unknown> = {
|
||||||
|
mode,
|
||||||
|
title: editorTitleRef.current.trim() || article.title,
|
||||||
|
featureImageUrl: article.featureImageUrl || "",
|
||||||
|
editorData,
|
||||||
|
snapshotId,
|
||||||
|
}
|
||||||
|
if (block?.name === "image") payload.targetBlockId = block.id
|
||||||
|
const batch = await api<ImageGenerationBatch>(`/api/articles/${article.id}/image-generations`, {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
})
|
||||||
|
setImageGenerationBatch(batch)
|
||||||
|
await applyReadyImageGenerationJobs(batch)
|
||||||
|
} catch (error) {
|
||||||
|
setStatusMessage(`Не удалось запустить генерацию: ${error instanceof Error ? error.message : String(error)}`)
|
||||||
|
} finally {
|
||||||
|
setImageGenerationStarting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!selectedArticle || !imageGenerationBatch || ["completed", "completed_with_errors", "failed"].includes(imageGenerationBatch.status)) return
|
||||||
|
const poll = () => {
|
||||||
|
void pollImageGeneration(imageGenerationBatch.batchId, selectedArticle.id).catch((error) => {
|
||||||
|
setStatusMessage(`Не удалось обновить генерацию: ${error instanceof Error ? error.message : String(error)}`)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
poll()
|
||||||
|
imageGenerationPollRef.current = window.setInterval(poll, 2200)
|
||||||
|
return () => {
|
||||||
|
if (imageGenerationPollRef.current !== null) window.clearInterval(imageGenerationPollRef.current)
|
||||||
|
imageGenerationPollRef.current = null
|
||||||
|
}
|
||||||
|
}, [selectedArticle?.id, imageGenerationBatch?.batchId, imageGenerationBatch?.status])
|
||||||
|
|
||||||
async function saveArticle(showMessage = true) {
|
async function saveArticle(showMessage = true) {
|
||||||
if (!selectedArticle) return selectedArticle
|
if (!selectedArticle) return selectedArticle
|
||||||
setEditorBusy(true)
|
setEditorBusy(true)
|
||||||
|
|
@ -2099,7 +2414,7 @@ export default function App() {
|
||||||
<h2 className="min-w-0 flex-1 truncate text-lg font-semibold tracking-normal">Редактирование статьи</h2>
|
<h2 className="min-w-0 flex-1 truncate text-lg font-semibold tracking-normal">Редактирование статьи</h2>
|
||||||
{editorDirty ? <Badge variant="secondary">есть правки</Badge> : null}
|
{editorDirty ? <Badge variant="secondary">есть правки</Badge> : null}
|
||||||
</div>
|
</div>
|
||||||
<p className="mt-1 text-sm text-muted-foreground">Редактируйте блоки как в Medium. Для картинки выберите image-блок и нажмите кнопку случайного кадра.</p>
|
<p className="mt-1 text-sm text-muted-foreground">Редактируйте блоки как в Medium. У изображения доступны случайный кадр и перегенерация по смыслу текста.</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="article-modal-actions flex shrink-0 flex-wrap justify-end gap-2">
|
<div className="article-modal-actions flex shrink-0 flex-wrap justify-end gap-2">
|
||||||
<input
|
<input
|
||||||
|
|
@ -2123,6 +2438,14 @@ export default function App() {
|
||||||
>
|
>
|
||||||
<Copy className="size-4" />
|
<Copy className="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
disabled={editorBusy || imageGenerationStarting || Boolean(imageGenerationBatch && !["completed", "completed_with_errors", "failed"].includes(imageGenerationBatch.status))}
|
||||||
|
onClick={() => startImageGeneration("all")}
|
||||||
|
>
|
||||||
|
{imageGenerationStarting ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <ImagePlus data-icon="inline-start" />}
|
||||||
|
Сгенерировать изображения
|
||||||
|
</Button>
|
||||||
<Button size="icon" variant="outline" disabled={editorBusy || !editorDirty} title="Сохранить" aria-label="Сохранить" onClick={() => saveArticle()}>
|
<Button size="icon" variant="outline" disabled={editorBusy || !editorDirty} title="Сохранить" aria-label="Сохранить" onClick={() => saveArticle()}>
|
||||||
<Save className="size-4" />
|
<Save className="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
|
@ -2171,6 +2494,15 @@ export default function App() {
|
||||||
<ImagePlus data-icon="inline-start" className={featureImageBusy ? "animate-pulse" : ""} />
|
<ImagePlus data-icon="inline-start" className={featureImageBusy ? "animate-pulse" : ""} />
|
||||||
Выбрать
|
Выбрать
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
disabled={imageGenerationStarting || Boolean(imageGenerationBatch && !["completed", "completed_with_errors", "failed"].includes(imageGenerationBatch.status))}
|
||||||
|
onClick={() => startImageGeneration("cover")}
|
||||||
|
>
|
||||||
|
<RefreshCw data-icon="inline-start" className={imageGenerationStarting ? "animate-spin" : ""} />
|
||||||
|
Перегенерировать обложку
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
className={`relative flex aspect-video w-full cursor-pointer items-center justify-center overflow-hidden rounded-md border border-dashed transition ${
|
className={`relative flex aspect-video w-full cursor-pointer items-center justify-center overflow-hidden rounded-md border border-dashed transition ${
|
||||||
|
|
@ -2231,6 +2563,34 @@ export default function App() {
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{imageGenerationBatch ? (
|
||||||
|
<section className="image-generation-status mb-6 rounded-md border bg-zinc-50 p-3" aria-live="polite">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-zinc-950">Генерация изображений</p>
|
||||||
|
<p className="text-xs text-muted-foreground">Статус: {imageGenerationBatch.status}</p>
|
||||||
|
</div>
|
||||||
|
{["completed", "completed_with_errors", "failed"].includes(imageGenerationBatch.status) ? <Badge variant="outline">Завершено</Badge> : <Badge variant="secondary"><Loader2 className="mr-1 size-3 animate-spin" />Выполняется</Badge>}
|
||||||
|
</div>
|
||||||
|
<div className="mt-3 grid gap-2 sm:grid-cols-3">
|
||||||
|
{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 (
|
||||||
|
<div key={job.id} className="rounded border bg-background p-2.5">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<span className="text-sm font-medium">{label}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">{job.progress || 0}%</span>
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 h-1.5 overflow-hidden rounded bg-muted"><div className="h-full rounded bg-primary transition-all" style={{ width: `${Math.max(0, Math.min(100, job.progress || 0))}%` }} /></div>
|
||||||
|
<p className={`mt-2 min-h-5 text-xs ${job.status === "failed" ? "text-destructive" : "text-muted-foreground"}`}>{job.errorMessage || job.stage || job.status}</p>
|
||||||
|
{canApply ? <Button className="mt-2 w-full" size="sm" variant="outline" onClick={() => void applyGeneratedImage(job)}>Применить</Button> : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
) : null}
|
||||||
<Textarea
|
<Textarea
|
||||||
ref={titleTextareaRef}
|
ref={titleTextareaRef}
|
||||||
rows={1}
|
rows={1}
|
||||||
|
|
|
||||||
|
|
@ -440,6 +440,15 @@
|
||||||
.article-editorjs .image-tool__caption {
|
.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;
|
@apply mx-auto mt-2 max-w-3xl border-0 px-0 text-sm leading-6 text-muted-foreground shadow-none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.image-generation-status {
|
||||||
|
border-color: hsl(214 18% 85%);
|
||||||
|
background: linear-gradient(135deg, hsl(210 30% 98%), hsl(0 0% 100%));
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-generation-status > div:last-child > div {
|
||||||
|
box-shadow: 0 1px 2px hsl(224 13% 12% / 0.035);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 640px) {
|
@media (max-width: 640px) {
|
||||||
|
|
|
||||||
|
|
@ -50,7 +50,7 @@ def migrate_db() -> None:
|
||||||
},
|
},
|
||||||
"articles": {
|
"articles": {
|
||||||
"feature_image_url": "TEXT NOT NULL DEFAULT ''",
|
"feature_image_url": "TEXT NOT NULL DEFAULT ''",
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
with engine.begin() as connection:
|
with engine.begin() as connection:
|
||||||
for table, columns in migrations.items():
|
for table, columns in migrations.items():
|
||||||
|
|
|
||||||
256
dzen-assistant/app/image_generation.py
Normal file
256
dzen-assistant/app/image_generation.py
Normal file
|
|
@ -0,0 +1,256 @@
|
||||||
|
"""Server-only helpers for Polza image generation.
|
||||||
|
|
||||||
|
The module deliberately keeps provider URLs and secrets out of API payloads.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ipaddress
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import tempfile
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from html import unescape
|
||||||
|
from io import BytesIO
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
DEFAULT_API_URL = "https://polza.ai/api"
|
||||||
|
DEFAULT_MODEL = "google/gemini-3.1-flash-image"
|
||||||
|
MAX_IMAGE_BYTES = 20 * 1024 * 1024
|
||||||
|
ALLOWED_IMAGE_TYPES = {"image/jpeg": ".jpg", "image/png": ".png", "image/webp": ".webp"}
|
||||||
|
|
||||||
|
|
||||||
|
class ImageGenerationError(RuntimeError):
|
||||||
|
def __init__(self, code: str, message: str, *, size_error: bool = False) -> None:
|
||||||
|
super().__init__(message)
|
||||||
|
self.code = code
|
||||||
|
self.message = message
|
||||||
|
self.size_error = size_error
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_api_url(value: str) -> str:
|
||||||
|
parsed = urlparse(value.strip().rstrip("/"))
|
||||||
|
if parsed.scheme != "https" or not parsed.netloc or parsed.username or parsed.password or parsed.query or parsed.fragment:
|
||||||
|
raise ValueError("API URL должен быть абсолютным HTTPS URL без параметров.")
|
||||||
|
if parsed.hostname in {"localhost", "localhost.localdomain"}:
|
||||||
|
raise ValueError("API URL не может указывать на локальную сеть.")
|
||||||
|
try:
|
||||||
|
host_ip = ipaddress.ip_address(parsed.hostname or "")
|
||||||
|
if host_ip.is_private or host_ip.is_loopback or host_ip.is_link_local or host_ip.is_reserved:
|
||||||
|
raise ValueError("API URL не может указывать на локальную сеть.")
|
||||||
|
except ValueError as exc:
|
||||||
|
if str(exc).startswith("API URL"):
|
||||||
|
raise
|
||||||
|
try:
|
||||||
|
for address in socket.getaddrinfo(parsed.hostname, None):
|
||||||
|
host_ip = ipaddress.ip_address(address[4][0])
|
||||||
|
if host_ip.is_private or host_ip.is_loopback or host_ip.is_link_local or host_ip.is_reserved:
|
||||||
|
raise ValueError("API URL не может указывать на локальную сеть.")
|
||||||
|
except socket.gaierror as exc:
|
||||||
|
raise ValueError("Не удалось разрешить API URL.") from exc
|
||||||
|
return parsed.geturl().rstrip("/")
|
||||||
|
|
||||||
|
|
||||||
|
def _text(value: Any) -> str:
|
||||||
|
return unescape(__import__("re").sub(r"<[^>]+>", " ", str(value or ""))).replace("\xa0", " ").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def content_blocks(editor_data: dict[str, Any]) -> list[dict[str, Any]]:
|
||||||
|
blocks = editor_data.get("blocks") if isinstance(editor_data, dict) else None
|
||||||
|
if not isinstance(blocks, list):
|
||||||
|
raise ValueError("editorData должен содержать массив blocks.")
|
||||||
|
result = []
|
||||||
|
for block in blocks:
|
||||||
|
if not isinstance(block, dict):
|
||||||
|
continue
|
||||||
|
kind, data = str(block.get("type") or ""), block.get("data") or {}
|
||||||
|
if not isinstance(data, dict) or kind == "image":
|
||||||
|
continue
|
||||||
|
text = _text(data.get("text") or data.get("caption") or data.get("content"))
|
||||||
|
if text:
|
||||||
|
result.append({"id": str(block.get("id") or ""), "type": kind, "text": text})
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def section_context(editor_data: dict[str, Any], target: str, target_block_id: str | None = None) -> str:
|
||||||
|
blocks = content_blocks(editor_data)
|
||||||
|
if not blocks:
|
||||||
|
return "Смысловой контекст отсутствует; создай сдержанную нейтральную аналитическую композицию."
|
||||||
|
headings = [i for i, block in enumerate(blocks) if block["type"] in {"header", "heading"}]
|
||||||
|
if target_block_id:
|
||||||
|
raw_blocks = editor_data.get("blocks") or []
|
||||||
|
image_index = next((i for i, item in enumerate(raw_blocks) if isinstance(item, dict) and str(item.get("id") or "") == target_block_id), -1)
|
||||||
|
if image_index >= 0:
|
||||||
|
nearby: list[str] = []
|
||||||
|
for item in raw_blocks[max(0, image_index - 4): image_index + 5]:
|
||||||
|
if not isinstance(item, dict) or item.get("type") == "image":
|
||||||
|
continue
|
||||||
|
data = item.get("data") or {}
|
||||||
|
if isinstance(data, dict):
|
||||||
|
text = _text(data.get("text") or data.get("caption") or data.get("content"))
|
||||||
|
if text:
|
||||||
|
nearby.append(text)
|
||||||
|
if nearby:
|
||||||
|
return " ".join(nearby)[:5000]
|
||||||
|
return " ".join(block["text"] for block in blocks[-4:])[:5000]
|
||||||
|
if headings:
|
||||||
|
sections: list[list[dict[str, Any]]] = []
|
||||||
|
for index, start in enumerate(headings):
|
||||||
|
end = headings[index + 1] if index + 1 < len(headings) else len(blocks)
|
||||||
|
sections.append(blocks[start:end])
|
||||||
|
if target == "final":
|
||||||
|
selected = sections[-1]
|
||||||
|
else:
|
||||||
|
total_chars = max(1, sum(len(block["text"]) for block in blocks))
|
||||||
|
offset = sum(len(block["text"]) for block in blocks[:headings[0]])
|
||||||
|
positioned_sections: list[tuple[float, list[dict[str, Any]]]] = []
|
||||||
|
for section in sections:
|
||||||
|
section_chars = sum(len(block["text"]) for block in section)
|
||||||
|
positioned_sections.append(((offset + section_chars / 2) / total_chars, section))
|
||||||
|
offset += section_chars
|
||||||
|
selected = min(positioned_sections, key=lambda item: abs(item[0] - .5))[1]
|
||||||
|
return " ".join(block["text"] for block in selected)[:5000]
|
||||||
|
total = sum(len(item["text"]) for item in blocks)
|
||||||
|
threshold = total * (.75 if target == "final" else .34)
|
||||||
|
seen, selected = 0, []
|
||||||
|
for item in blocks:
|
||||||
|
seen += len(item["text"])
|
||||||
|
if seen >= threshold:
|
||||||
|
selected.append(item)
|
||||||
|
return " ".join(item["text"] for item in selected[:6])[:5000]
|
||||||
|
|
||||||
|
|
||||||
|
def build_prompt(target: str, title: str, editor_data: dict[str, Any], target_block_id: str | None = None) -> str:
|
||||||
|
context = section_context(editor_data, target, target_block_id)
|
||||||
|
limits = ("Не показывай реальные карты, координаты, маршруты, военные схемы, оружие, активные БПЛА, ракеты, "
|
||||||
|
"взрывы, пожары, кровь, тела, разрушения, узнаваемых людей, флаги, гербы, эмблемы или логотипы. "
|
||||||
|
"Не выдавай спорные утверждения за доказанный факт.")
|
||||||
|
if target == "cover":
|
||||||
|
return f"""Создай фотореалистичную премиальную обложку серьёзного международного военно-политического аналитического издания, 16:9, кинематографичный свет, высокая детализация, спокойная центральная safe area.
|
||||||
|
ЕДИНСТВЕННЫЙ ТЕКСТ НА ИЗОБРАЖЕНИИ, строго без изменений:
|
||||||
|
<<<{title.strip()}>>>
|
||||||
|
Используй Bebas Neue, сохрани кириллицу, Ё, регистр и пунктуацию; холодно-серебристые металлические 3D-буквы, тёмно-графитовая обводка, тень и блики. Не добавляй иных надписей, логотипов или водяных знаков.
|
||||||
|
Сюжет создай по смыслу статьи: предметная, архитектурная, аналитическая композиция, без людей.
|
||||||
|
КОНТЕКСТ: {context}
|
||||||
|
{limits}"""
|
||||||
|
role = "факты, расследование, предметы, пространство и смысловой конфликт второй части" if target == "middle" else "вывод, последствия, ответственность, неопределённость или развязку заключительной части"
|
||||||
|
return f"""Создай фотореалистичную кинематографичную редакционную иллюстрацию 16:9 для военно-политической аналитической статьи. Визуализируй {role}. Полностью без текста, букв, цифр, читаемых документов, логотипов и водяных знаков. Сдержанная, серьёзная, неоднозначная предметная композиция.
|
||||||
|
КОНТЕКСТ: {context}
|
||||||
|
{limits}"""
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_public_url(url: str) -> None:
|
||||||
|
parsed = urlparse(url)
|
||||||
|
if parsed.scheme != "https" or not parsed.hostname:
|
||||||
|
raise ImageGenerationError("download_failed", "Провайдер вернул недопустимую ссылку на изображение.")
|
||||||
|
try:
|
||||||
|
addresses = socket.getaddrinfo(parsed.hostname, None)
|
||||||
|
for address in addresses:
|
||||||
|
ip = ipaddress.ip_address(address[4][0])
|
||||||
|
if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved:
|
||||||
|
raise ImageGenerationError("download_failed", "Ссылка на изображение недоступна.")
|
||||||
|
except socket.gaierror as exc:
|
||||||
|
raise ImageGenerationError("download_failed", "Не удалось разрешить адрес изображения.") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def error_from_response(response: httpx.Response) -> ImageGenerationError:
|
||||||
|
body = response.text[:1000].lower()
|
||||||
|
if response.status_code in {401, 403}:
|
||||||
|
return ImageGenerationError("token_invalid", "Токен Polza отклонён.")
|
||||||
|
if response.status_code == 429:
|
||||||
|
return ImageGenerationError("rate_limited", "Превышен лимит запросов Polza.")
|
||||||
|
if "balance" in body or "insufficient" in body:
|
||||||
|
return ImageGenerationError("insufficient_balance", "Недостаточно средств в Polza.")
|
||||||
|
if "moderation" in body or "safety" in body:
|
||||||
|
return ImageGenerationError("moderation_rejected", "Запрос отклонён политикой провайдера.")
|
||||||
|
if "model" in body and ("not found" in body or "unavailable" in body):
|
||||||
|
return ImageGenerationError("model_unavailable", "Выбранная модель недоступна.")
|
||||||
|
size_error = any(value in body for value in ("resolution", "size", "quality", "4k", "image_resolution"))
|
||||||
|
return ImageGenerationError("provider_error", "Polza не смогла создать изображение.", size_error=size_error)
|
||||||
|
|
||||||
|
|
||||||
|
class PolzaClient:
|
||||||
|
def __init__(self, api_url: str, token: str) -> None:
|
||||||
|
self.api_url, self.token = normalize_api_url(api_url), token
|
||||||
|
|
||||||
|
@property
|
||||||
|
def media_url(self) -> str:
|
||||||
|
return self.api_url + "/v1/media"
|
||||||
|
|
||||||
|
async def create(self, model: str, prompt: str, resolution: str = "4K") -> str:
|
||||||
|
input_payload: dict[str, Any] = {
|
||||||
|
"prompt": prompt,
|
||||||
|
"output_format": "png",
|
||||||
|
"max_images": 1,
|
||||||
|
}
|
||||||
|
if resolution == "4K":
|
||||||
|
input_payload.update({"aspect_ratio": "16:9", "image_resolution": "4K", "quality": "high"})
|
||||||
|
else:
|
||||||
|
input_payload["aspect_ratio"] = "1792x1024"
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=60) as client:
|
||||||
|
response = await client.post(self.media_url, headers={"Authorization": f"Bearer {self.token}"}, json={"model": model, "input": input_payload, "async": True})
|
||||||
|
except httpx.TimeoutException as exc:
|
||||||
|
raise ImageGenerationError("provider_timeout", "Истёк тайм-аут Polza.") from exc
|
||||||
|
if response.is_error:
|
||||||
|
raise error_from_response(response)
|
||||||
|
data = response.json()
|
||||||
|
generation_id = data.get("id") or data.get("generation_id") or (data.get("data") or {}).get("id")
|
||||||
|
if not generation_id:
|
||||||
|
raise ImageGenerationError("provider_error", "Polza вернула неполный ответ.")
|
||||||
|
return str(generation_id)
|
||||||
|
|
||||||
|
async def status(self, generation_id: str) -> dict[str, Any]:
|
||||||
|
async with httpx.AsyncClient(timeout=30) as client:
|
||||||
|
response = await client.get(f"{self.media_url}/{generation_id}", headers={"Authorization": f"Bearer {self.token}"})
|
||||||
|
if response.is_error:
|
||||||
|
raise error_from_response(response)
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
|
def extract_result_url(data: dict[str, Any]) -> str | None:
|
||||||
|
candidates: list[Any] = [data.get("url"), data.get("output"), data.get("result"), data.get("data")]
|
||||||
|
while candidates:
|
||||||
|
value = candidates.pop(0)
|
||||||
|
if isinstance(value, str) and value.startswith("http"):
|
||||||
|
return value
|
||||||
|
if isinstance(value, dict):
|
||||||
|
candidates.extend(value.get(k) for k in ("url", "output", "result", "data", "images") if k in value)
|
||||||
|
if isinstance(value, list):
|
||||||
|
candidates.extend(value)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def save_remote_image(url: str, target_dir: Path, public_base_url: str, article_id: int, target: str) -> str:
|
||||||
|
_safe_public_url(url)
|
||||||
|
response = httpx.get(url, timeout=45, follow_redirects=False)
|
||||||
|
if response.is_error or response.headers.get("content-type", "").split(";", 1)[0].lower() not in ALLOWED_IMAGE_TYPES:
|
||||||
|
raise ImageGenerationError("invalid_image", "Polza вернула недопустимый файл изображения.")
|
||||||
|
content = response.content
|
||||||
|
if not content or len(content) > MAX_IMAGE_BYTES:
|
||||||
|
raise ImageGenerationError("invalid_image", "Размер изображения недопустим.")
|
||||||
|
try:
|
||||||
|
Image.open(BytesIO(content)).verify()
|
||||||
|
except Exception as exc:
|
||||||
|
raise ImageGenerationError("invalid_image", "Файл изображения повреждён.") from exc
|
||||||
|
date_key = datetime.now(timezone.utc).strftime("%Y%m%d")
|
||||||
|
date_dir = target_dir / "generated" / date_key / str(article_id)
|
||||||
|
date_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
suffix = ALLOWED_IMAGE_TYPES[response.headers["content-type"].split(";", 1)[0].lower()]
|
||||||
|
name = f"{target}-{uuid4().hex}{suffix}"
|
||||||
|
fd, temporary = tempfile.mkstemp(prefix=".upload-", dir=date_dir)
|
||||||
|
try:
|
||||||
|
with os.fdopen(fd, "wb") as output:
|
||||||
|
output.write(content)
|
||||||
|
os.replace(temporary, date_dir / name)
|
||||||
|
os.chmod(date_dir / name, 0o644)
|
||||||
|
finally:
|
||||||
|
if os.path.exists(temporary):
|
||||||
|
os.unlink(temporary)
|
||||||
|
return f"{public_base_url.rstrip('/')}/media/generated/{date_key}/{article_id}/{name}"
|
||||||
|
|
@ -121,3 +121,43 @@ class Article(Base):
|
||||||
published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||||
|
|
||||||
video: Mapped[Video | None] = relationship(back_populates="articles")
|
video: Mapped[Video | None] = relationship(back_populates="articles")
|
||||||
|
image_generation_batches: Mapped[list["ImageGenerationBatch"]] = relationship(back_populates="article", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class ImageGenerationBatch(Base):
|
||||||
|
__tablename__ = "image_generation_batches"
|
||||||
|
|
||||||
|
id: Mapped[str] = mapped_column(String(36), primary_key=True)
|
||||||
|
article_id: Mapped[int] = mapped_column(ForeignKey("articles.id", ondelete="CASCADE"), index=True)
|
||||||
|
status: Mapped[str] = mapped_column(String(32), default="queued", index=True)
|
||||||
|
snapshot_id: Mapped[str] = mapped_column(String(128), default="")
|
||||||
|
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())
|
||||||
|
|
||||||
|
article: Mapped[Article] = relationship(back_populates="image_generation_batches")
|
||||||
|
jobs: Mapped[list["ImageGenerationJob"]] = relationship(back_populates="batch", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class ImageGenerationJob(Base):
|
||||||
|
__tablename__ = "image_generation_jobs"
|
||||||
|
|
||||||
|
id: Mapped[str] = mapped_column(String(36), primary_key=True)
|
||||||
|
batch_id: Mapped[str] = mapped_column(ForeignKey("image_generation_batches.id", ondelete="CASCADE"), index=True)
|
||||||
|
article_id: Mapped[int] = mapped_column(ForeignKey("articles.id", ondelete="CASCADE"), index=True)
|
||||||
|
target: Mapped[str] = mapped_column(String(16), index=True)
|
||||||
|
target_block_id: Mapped[str | None] = mapped_column(String(128))
|
||||||
|
snapshot_id: Mapped[str] = mapped_column(String(128), default="")
|
||||||
|
prompt: Mapped[str] = mapped_column(Text)
|
||||||
|
api_url: Mapped[str] = mapped_column(Text)
|
||||||
|
model: Mapped[str] = mapped_column(String(256))
|
||||||
|
celery_task_id: Mapped[str | None] = mapped_column(String(64))
|
||||||
|
status: Mapped[str] = mapped_column(String(32), default="queued", index=True)
|
||||||
|
progress: Mapped[int] = mapped_column(Integer, default=0)
|
||||||
|
stage: Mapped[str] = mapped_column(String(160), default="В очереди")
|
||||||
|
local_url: Mapped[str | None] = mapped_column(Text)
|
||||||
|
error_code: Mapped[str | None] = mapped_column(String(64))
|
||||||
|
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())
|
||||||
|
|
||||||
|
batch: Mapped[ImageGenerationBatch] = relationship(back_populates="jobs")
|
||||||
|
|
|
||||||
|
|
@ -34,10 +34,11 @@ from app.auth import (
|
||||||
from app.captions import strip_leading_duplicate_title
|
from app.captions import strip_leading_duplicate_title
|
||||||
from app.chapters import chapter_to_payload, parse_video_chapters
|
from app.chapters import chapter_to_payload, parse_video_chapters
|
||||||
from app.database import SessionLocal, get_session
|
from app.database import SessionLocal, get_session
|
||||||
from app.models import AppSetting, Article, Frame, PasskeyCredential, Source, Video
|
from app.models import AppSetting, Article, Frame, ImageGenerationBatch, ImageGenerationJob, PasskeyCredential, Source, Video
|
||||||
|
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 article_url, build_feed_xml, render_article_html
|
from app.rss import article_url, build_feed_xml, render_article_html
|
||||||
from app.worker import best_thumbnail_url, parse_upload_date, process_video, scan_sources, ytdlp_base_args
|
from app.worker import best_thumbnail_url, generate_article_image, parse_upload_date, process_video, scan_sources, ytdlp_base_args
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
@ -74,6 +75,10 @@ class VkAuthIn(BaseModel):
|
||||||
class AppSettingsIn(BaseModel):
|
class AppSettingsIn(BaseModel):
|
||||||
signatureHtml: str = ""
|
signatureHtml: str = ""
|
||||||
llmInstructions: str = ""
|
llmInstructions: str = ""
|
||||||
|
imageApiUrl: str | None = None
|
||||||
|
imageModel: str | None = None
|
||||||
|
imageApiToken: str | None = None
|
||||||
|
deleteImageApiToken: bool = False
|
||||||
|
|
||||||
|
|
||||||
class ChatIn(BaseModel):
|
class ChatIn(BaseModel):
|
||||||
|
|
@ -90,6 +95,15 @@ class ArticlePublishIn(BaseModel):
|
||||||
publishedAt: datetime | None = None
|
publishedAt: datetime | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ImageGenerationIn(BaseModel):
|
||||||
|
mode: str
|
||||||
|
title: str
|
||||||
|
featureImageUrl: str | None = None
|
||||||
|
editorData: dict[str, Any]
|
||||||
|
snapshotId: str
|
||||||
|
targetBlockId: str | None = None
|
||||||
|
|
||||||
|
|
||||||
class VideoChapterIn(BaseModel):
|
class VideoChapterIn(BaseModel):
|
||||||
id: str | None = None
|
id: str | None = None
|
||||||
title: str
|
title: str
|
||||||
|
|
@ -109,23 +123,30 @@ def health() -> dict[str, str]:
|
||||||
|
|
||||||
SETTING_SIGNATURE = "article_signature_html"
|
SETTING_SIGNATURE = "article_signature_html"
|
||||||
SETTING_LLM_INSTRUCTIONS = "llm_instructions"
|
SETTING_LLM_INSTRUCTIONS = "llm_instructions"
|
||||||
|
SETTING_IMAGE_API_URL = "image_api_url"
|
||||||
|
SETTING_IMAGE_MODEL = "image_model"
|
||||||
|
SETTING_IMAGE_API_TOKEN = "image_api_token"
|
||||||
|
|
||||||
|
|
||||||
def app_settings_payload(session: Session) -> dict[str, str]:
|
def app_settings_payload(session: Session) -> dict[str, Any]:
|
||||||
values = {
|
values = {
|
||||||
setting.key: setting.value
|
setting.key: setting.value
|
||||||
for setting in session.scalars(
|
for setting in session.scalars(
|
||||||
select(AppSetting).where(AppSetting.key.in_([SETTING_SIGNATURE, SETTING_LLM_INSTRUCTIONS]))
|
select(AppSetting).where(AppSetting.key.in_([SETTING_SIGNATURE, SETTING_LLM_INSTRUCTIONS, SETTING_IMAGE_API_URL, SETTING_IMAGE_MODEL, SETTING_IMAGE_API_TOKEN]))
|
||||||
).all()
|
).all()
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
"signatureHtml": values.get(SETTING_SIGNATURE, ""),
|
"signatureHtml": values.get(SETTING_SIGNATURE, ""),
|
||||||
"llmInstructions": values.get(SETTING_LLM_INSTRUCTIONS, ""),
|
"llmInstructions": values.get(SETTING_LLM_INSTRUCTIONS, ""),
|
||||||
|
"imageApiUrl": values.get(SETTING_IMAGE_API_URL, DEFAULT_API_URL),
|
||||||
|
"imageModel": values.get(SETTING_IMAGE_MODEL, DEFAULT_MODEL),
|
||||||
|
"imageApiTokenConfigured": bool(values.get(SETTING_IMAGE_API_TOKEN, "")),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/api/settings")
|
@router.get("/api/settings")
|
||||||
def get_app_settings(session: Session = Depends(get_session)) -> dict[str, str]:
|
def get_app_settings(request: Request, session: Session = Depends(get_session)) -> dict[str, Any]:
|
||||||
|
require_session(request)
|
||||||
return app_settings_payload(session)
|
return app_settings_payload(session)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -181,11 +202,30 @@ def passkey_logout(request: Request, response: Response) -> dict[str, bool]:
|
||||||
|
|
||||||
|
|
||||||
@router.put("/api/settings")
|
@router.put("/api/settings")
|
||||||
def update_app_settings(payload: AppSettingsIn, session: Session = Depends(get_session)) -> dict[str, str]:
|
def update_app_settings(payload: AppSettingsIn, request: Request, session: Session = Depends(get_session)) -> dict[str, Any]:
|
||||||
|
require_session(request)
|
||||||
|
token = (payload.imageApiToken or "").strip()
|
||||||
|
if payload.deleteImageApiToken and token:
|
||||||
|
raise HTTPException(status_code=422, detail="Нельзя одновременно заменить и удалить токен.")
|
||||||
|
try:
|
||||||
|
image_url = normalize_api_url(payload.imageApiUrl) if payload.imageApiUrl is not None else None
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||||
|
image_model = payload.imageModel.strip() if payload.imageModel is not None else None
|
||||||
|
if image_model is not None and not image_model:
|
||||||
|
raise HTTPException(status_code=422, detail="Модель не может быть пустой.")
|
||||||
values = {
|
values = {
|
||||||
SETTING_SIGNATURE: payload.signatureHtml.strip(),
|
SETTING_SIGNATURE: payload.signatureHtml.strip(),
|
||||||
SETTING_LLM_INSTRUCTIONS: payload.llmInstructions.strip(),
|
SETTING_LLM_INSTRUCTIONS: payload.llmInstructions.strip(),
|
||||||
}
|
}
|
||||||
|
if image_url is not None:
|
||||||
|
values[SETTING_IMAGE_API_URL] = image_url
|
||||||
|
if image_model is not None:
|
||||||
|
values[SETTING_IMAGE_MODEL] = image_model
|
||||||
|
if payload.deleteImageApiToken:
|
||||||
|
values[SETTING_IMAGE_API_TOKEN] = ""
|
||||||
|
elif token:
|
||||||
|
values[SETTING_IMAGE_API_TOKEN] = token
|
||||||
existing = {
|
existing = {
|
||||||
setting.key: setting
|
setting.key: setting
|
||||||
for setting in session.scalars(select(AppSetting).where(AppSetting.key.in_(values))).all()
|
for setting in session.scalars(select(AppSetting).where(AppSetting.key.in_(values))).all()
|
||||||
|
|
@ -769,6 +809,105 @@ def get_article(article_id: int, session: Session = Depends(get_session), settin
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def image_job_payload(job: ImageGenerationJob) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"id": job.id,
|
||||||
|
"target": job.target,
|
||||||
|
"status": job.status,
|
||||||
|
"progress": job.progress,
|
||||||
|
"stage": job.stage,
|
||||||
|
"localUrl": job.local_url if job.status == "ready" else None,
|
||||||
|
"errorCode": job.error_code,
|
||||||
|
"errorMessage": job.error_message,
|
||||||
|
"targetBlockId": job.target_block_id,
|
||||||
|
"snapshotId": job.snapshot_id,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def image_batch_payload(batch: ImageGenerationBatch) -> dict[str, Any]:
|
||||||
|
return {"batchId": batch.id, "status": batch.status, "snapshotId": batch.snapshot_id, "jobs": [image_job_payload(job) for job in batch.jobs]}
|
||||||
|
|
||||||
|
|
||||||
|
def active_image_batch(session: Session, article_id: int) -> ImageGenerationBatch | None:
|
||||||
|
return session.scalar(
|
||||||
|
select(ImageGenerationBatch)
|
||||||
|
.where(ImageGenerationBatch.article_id == article_id, ImageGenerationBatch.status.in_(["queued", "running"]))
|
||||||
|
.order_by(ImageGenerationBatch.created_at.desc())
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/articles/{article_id}/image-generations/active")
|
||||||
|
def active_article_image_generation(article_id: int, request: Request, session: Session = Depends(get_session)) -> Any:
|
||||||
|
require_session(request)
|
||||||
|
if not session.get(Article, article_id):
|
||||||
|
raise HTTPException(status_code=404, detail="Article not found")
|
||||||
|
batch = active_image_batch(session, article_id)
|
||||||
|
return Response(status_code=204) if not batch else image_batch_payload(batch)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/articles/{article_id}/image-generations/{batch_id}")
|
||||||
|
def article_image_generation(article_id: int, batch_id: str, request: Request, session: Session = Depends(get_session)) -> dict[str, Any]:
|
||||||
|
require_session(request)
|
||||||
|
batch = session.get(ImageGenerationBatch, batch_id)
|
||||||
|
if not batch or batch.article_id != article_id:
|
||||||
|
raise HTTPException(status_code=404, detail="Image generation not found")
|
||||||
|
return image_batch_payload(batch)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/articles/{article_id}/image-generations", status_code=202)
|
||||||
|
def create_article_image_generation(article_id: int, payload: ImageGenerationIn, request: Request, session: Session = Depends(get_session)) -> dict[str, Any]:
|
||||||
|
require_session(request)
|
||||||
|
article = session.get(Article, article_id)
|
||||||
|
if not article:
|
||||||
|
raise HTTPException(status_code=404, detail="Article not found")
|
||||||
|
if payload.mode not in {"all", "cover", "middle", "final"}:
|
||||||
|
raise HTTPException(status_code=422, detail="Неизвестный режим генерации.")
|
||||||
|
if not payload.title.strip() or not payload.snapshotId.strip():
|
||||||
|
raise HTTPException(status_code=422, detail="Нужны заголовок и идентификатор снимка.")
|
||||||
|
if payload.mode in {"middle", "final"} and payload.mode != "all" and not payload.targetBlockId:
|
||||||
|
raise HTTPException(status_code=422, detail="Для перегенерации изображения нужен targetBlockId.")
|
||||||
|
try:
|
||||||
|
# Validate the untrusted snapshot before persisting a job.
|
||||||
|
build_prompt("cover", payload.title, payload.editorData)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||||
|
active = active_image_batch(session, article_id)
|
||||||
|
if active and payload.mode == "all":
|
||||||
|
return image_batch_payload(active)
|
||||||
|
targets = ["cover", "middle", "final"] if payload.mode == "all" else [payload.mode]
|
||||||
|
if active and payload.mode != "all":
|
||||||
|
active_targets = {job.target for job in active.jobs if job.status in {"queued", "requesting", "generating", "downloading"}}
|
||||||
|
if payload.mode in active_targets:
|
||||||
|
return image_batch_payload(active)
|
||||||
|
values = {item.key: item.value for item in session.scalars(select(AppSetting).where(AppSetting.key.in_([SETTING_IMAGE_API_URL, SETTING_IMAGE_MODEL]))).all()}
|
||||||
|
api_url, model = values.get(SETTING_IMAGE_API_URL, DEFAULT_API_URL), values.get(SETTING_IMAGE_MODEL, DEFAULT_MODEL)
|
||||||
|
try:
|
||||||
|
api_url = normalize_api_url(api_url)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=422, detail="Некорректный API URL в настройках.") from exc
|
||||||
|
if not model.strip():
|
||||||
|
raise HTTPException(status_code=422, detail="Не задана модель генерации.")
|
||||||
|
batch = ImageGenerationBatch(id=str(uuid4()), article_id=article_id, snapshot_id=payload.snapshotId.strip(), status="queued")
|
||||||
|
session.add(batch)
|
||||||
|
jobs: list[ImageGenerationJob] = []
|
||||||
|
for target in targets:
|
||||||
|
job = ImageGenerationJob(
|
||||||
|
id=str(uuid4()), batch_id=batch.id, article_id=article_id, target=target,
|
||||||
|
target_block_id=payload.targetBlockId if target in {"middle", "final"} else None,
|
||||||
|
snapshot_id=batch.snapshot_id, prompt=build_prompt(target, payload.title, payload.editorData, payload.targetBlockId),
|
||||||
|
api_url=api_url, model=model.strip(), status="queued", progress=0, stage="В очереди",
|
||||||
|
)
|
||||||
|
session.add(job)
|
||||||
|
jobs.append(job)
|
||||||
|
session.commit()
|
||||||
|
for job in jobs:
|
||||||
|
task = generate_article_image.delay(job.id)
|
||||||
|
job.celery_task_id = task.id
|
||||||
|
session.commit()
|
||||||
|
session.refresh(batch)
|
||||||
|
return image_batch_payload(batch)
|
||||||
|
|
||||||
|
|
||||||
@router.patch("/api/articles/{article_id}")
|
@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:
|
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)
|
article = session.get(Article, article_id)
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
import asyncio
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import shlex
|
import shlex
|
||||||
|
|
@ -16,6 +17,8 @@ from app.chapters import seconds_to_timecode
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
from app.database import SessionLocal, init_db
|
from app.database import SessionLocal, init_db
|
||||||
from app.models import AppSetting, Article, Frame, Source, Video
|
from app.models import AppSetting, Article, Frame, Source, Video
|
||||||
|
from app.models import ImageGenerationBatch, ImageGenerationJob
|
||||||
|
from app.image_generation import ImageGenerationError, PolzaClient, extract_result_url, save_remote_image
|
||||||
from app.quality import validate_article_content, validate_transcript_text
|
from app.quality import validate_article_content, validate_transcript_text
|
||||||
|
|
||||||
settings = get_settings()
|
settings = get_settings()
|
||||||
|
|
@ -33,6 +36,96 @@ celery_app.conf.beat_schedule = {
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
IMAGE_TOKEN_SETTING = "image_api_token"
|
||||||
|
|
||||||
|
|
||||||
|
def refresh_image_batch_status(session, batch: ImageGenerationBatch) -> None:
|
||||||
|
states = [job.status for job in batch.jobs]
|
||||||
|
if any(state in {"queued", "requesting", "generating", "downloading"} for state in states):
|
||||||
|
batch.status = "running" if any(state != "queued" for state in states) else "queued"
|
||||||
|
elif states and all(state == "ready" for state in states):
|
||||||
|
batch.status = "completed"
|
||||||
|
elif any(state == "ready" for state in states):
|
||||||
|
batch.status = "completed_with_errors"
|
||||||
|
else:
|
||||||
|
batch.status = "failed"
|
||||||
|
|
||||||
|
|
||||||
|
@celery_app.task(name="app.worker.generate_article_image")
|
||||||
|
def generate_article_image(job_id: str) -> None:
|
||||||
|
"""Generate one image. Never log prompt, token, or raw provider payload."""
|
||||||
|
init_db()
|
||||||
|
with SessionLocal() as session:
|
||||||
|
job = session.get(ImageGenerationJob, job_id)
|
||||||
|
if not job or job.status not in {"queued", "requesting"}:
|
||||||
|
return
|
||||||
|
token = session.scalar(select(AppSetting.value).where(AppSetting.key == IMAGE_TOKEN_SETTING)) or ""
|
||||||
|
if not token.strip():
|
||||||
|
job.status, job.stage, job.error_code, job.error_message = "failed", "Ошибка", "token_missing", "Не задан токен Polza."
|
||||||
|
refresh_image_batch_status(session, job.batch)
|
||||||
|
session.commit()
|
||||||
|
return
|
||||||
|
job.status, job.progress, job.stage = "requesting", 5, "Отправляем запрос"
|
||||||
|
refresh_image_batch_status(session, job.batch)
|
||||||
|
session.commit()
|
||||||
|
api_url, model, prompt, article_id, target = job.api_url, job.model, job.prompt, job.article_id, job.target
|
||||||
|
try:
|
||||||
|
client = PolzaClient(api_url, token)
|
||||||
|
try:
|
||||||
|
generation_id = asyncio.run(client.create(model, prompt, "4K"))
|
||||||
|
except ImageGenerationError as exc:
|
||||||
|
if not exc.size_error:
|
||||||
|
raise
|
||||||
|
generation_id = asyncio.run(client.create(model, prompt, "1792x1024"))
|
||||||
|
image_url: str | None = None
|
||||||
|
for _ in range(120):
|
||||||
|
with SessionLocal() as session:
|
||||||
|
job = session.get(ImageGenerationJob, job_id)
|
||||||
|
if not job:
|
||||||
|
return
|
||||||
|
job.status, job.progress, job.stage = "generating", max(job.progress, 20), "Генерируем изображение"
|
||||||
|
refresh_image_batch_status(session, job.batch)
|
||||||
|
session.commit()
|
||||||
|
result = asyncio.run(client.status(generation_id))
|
||||||
|
provider_status = str(result.get("status") or (result.get("data") or {}).get("status") or "").lower()
|
||||||
|
image_url = extract_result_url(result)
|
||||||
|
if image_url:
|
||||||
|
break
|
||||||
|
if provider_status in {"failed", "error", "cancelled", "canceled"}:
|
||||||
|
raise ImageGenerationError("provider_error", "Polza не смогла создать изображение.")
|
||||||
|
time.sleep(3)
|
||||||
|
if not image_url:
|
||||||
|
raise ImageGenerationError("provider_timeout", "Polza не успела создать изображение.")
|
||||||
|
with SessionLocal() as session:
|
||||||
|
job = session.get(ImageGenerationJob, job_id)
|
||||||
|
if not job:
|
||||||
|
return
|
||||||
|
job.status, job.progress, job.stage = "downloading", 85, "Сохраняем изображение"
|
||||||
|
refresh_image_batch_status(session, job.batch)
|
||||||
|
session.commit()
|
||||||
|
local_url = save_remote_image(image_url, settings.media_path, settings.public_base_url, article_id, target)
|
||||||
|
with SessionLocal() as session:
|
||||||
|
job = session.get(ImageGenerationJob, job_id)
|
||||||
|
if not job:
|
||||||
|
return
|
||||||
|
job.status, job.progress, job.stage, job.local_url = "ready", 100, "Готово", local_url
|
||||||
|
refresh_image_batch_status(session, job.batch)
|
||||||
|
session.commit()
|
||||||
|
except ImageGenerationError as exc:
|
||||||
|
with SessionLocal() as session:
|
||||||
|
job = session.get(ImageGenerationJob, job_id)
|
||||||
|
if job:
|
||||||
|
job.status, job.stage, job.error_code, job.error_message = "failed", "Ошибка", exc.code, exc.message
|
||||||
|
refresh_image_batch_status(session, job.batch)
|
||||||
|
session.commit()
|
||||||
|
except Exception:
|
||||||
|
with SessionLocal() as session:
|
||||||
|
job = session.get(ImageGenerationJob, job_id)
|
||||||
|
if job:
|
||||||
|
job.status, job.stage, job.error_code, job.error_message = "failed", "Ошибка", "provider_error", "Не удалось создать изображение."
|
||||||
|
refresh_image_batch_status(session, job.batch)
|
||||||
|
session.commit()
|
||||||
|
|
||||||
|
|
||||||
def slugify(text: str) -> str:
|
def slugify(text: str) -> str:
|
||||||
translit = {
|
translit = {
|
||||||
|
|
|
||||||
50
dzen-assistant/tests/test_image_generation.py
Normal file
50
dzen-assistant/tests/test_image_generation.py
Normal file
|
|
@ -0,0 +1,50 @@
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from app.image_generation import build_prompt, content_blocks, section_context
|
||||||
|
|
||||||
|
|
||||||
|
EDITOR_DATA = {
|
||||||
|
"blocks": [
|
||||||
|
{"id": "intro", "type": "paragraph", "data": {"text": "Вводный абзац."}},
|
||||||
|
{"id": "middle-heading", "type": "header", "data": {"text": "Вторая часть"}},
|
||||||
|
{"id": "middle", "type": "paragraph", "data": {"text": "Факты второй части."}},
|
||||||
|
{"id": "image", "type": "image", "data": {"file": {"url": "https://example.test/old.jpg"}}},
|
||||||
|
{"id": "final-heading", "type": "header", "data": {"text": "Вывод"}},
|
||||||
|
{"id": "final", "type": "paragraph", "data": {"text": "Заключительный вывод статьи."}},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ImageGenerationPromptTest(unittest.TestCase):
|
||||||
|
def test_cover_keeps_exact_title_and_forbids_extra_text(self):
|
||||||
|
title = "КТО НАВЁЛ УДАР?"
|
||||||
|
prompt = build_prompt("cover", title, EDITOR_DATA)
|
||||||
|
|
||||||
|
self.assertIn(title, prompt)
|
||||||
|
self.assertIn("ЕДИНСТВЕННЫЙ ТЕКСТ", prompt)
|
||||||
|
self.assertIn("Bebas Neue", prompt)
|
||||||
|
|
||||||
|
def test_body_prompts_are_distinct_and_forbid_text(self):
|
||||||
|
middle = build_prompt("middle", "Заголовок", EDITOR_DATA)
|
||||||
|
final = build_prompt("final", "Заголовок", EDITOR_DATA)
|
||||||
|
|
||||||
|
self.assertNotEqual(middle, final)
|
||||||
|
self.assertIn("без текста", middle.lower())
|
||||||
|
self.assertIn("без текста", final.lower())
|
||||||
|
|
||||||
|
def test_image_blocks_are_excluded_from_context(self):
|
||||||
|
blocks = content_blocks(EDITOR_DATA)
|
||||||
|
|
||||||
|
self.assertNotIn("image", {block["id"] for block in blocks})
|
||||||
|
self.assertIn("Факты второй части.", section_context(EDITOR_DATA, "middle"))
|
||||||
|
self.assertIn("Заключительный вывод статьи.", section_context(EDITOR_DATA, "final"))
|
||||||
|
|
||||||
|
def test_inline_regeneration_uses_nearby_text(self):
|
||||||
|
context = section_context(EDITOR_DATA, "middle", "image")
|
||||||
|
|
||||||
|
self.assertIn("Факты второй части.", context)
|
||||||
|
self.assertIn("Заключительный вывод статьи.", context)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Loading…
Reference in a new issue