AI-генерация иллюстраций для статей
AI-генерация иллюстраций заменяет поиск стоковых фото для редакционных материалов: каждая иллюстрация уникальна, соответствует тексту, не требует лицензирования. Применяется в медиа, корпоративных блогах, образовательных платформах.
Автоматическое извлечение промпта из текста
from openai import AsyncOpenAI
client = AsyncOpenAI()
async def extract_illustration_prompt(
article_text: str,
section_text: str,
style: str = "flat illustration",
language_out: str = "en" # промпты для SD лучше на английском
) -> str:
response = await client.chat.completions.create(
model="gpt-4o-mini",
messages=[{
"role": "system",
"content": f"""Создай промпт для иллюстрации к разделу статьи.
Стиль: {style}.
Требования:
- Описание сцены/объекта (не абстракции)
- Без текста и надписей на изображении
- Без людей, если не упоминаются явно
- На языке: {language_out}
- Длина: 30-60 слов
Верни только промпт, без пояснений."""
}, {
"role": "user",
"content": f"Статья о: {article_text[:500]}\nРаздел: {section_text[:300]}"
}]
)
return response.choices[0].message.content.strip()
Стили иллюстраций
ILLUSTRATION_STYLES = {
"flat": "flat design illustration, minimal, clean lines, pastel colors, 2D",
"isometric": "isometric 3D illustration, flat design, colorful, technical",
"hand_drawn": "hand-drawn illustration, sketch style, ink lines, watercolor wash",
"editorial": "editorial illustration, magazine style, expressive, bold colors",
"tech_blog": "tech illustration, geometric shapes, gradient colors, modern digital art",
"corporate": "professional corporate illustration, clean, business-appropriate, blue palette",
"educational": "educational diagram, infographic style, clean labels, instructional",
}
async def generate_article_illustration(
article_section: str,
style: str = "flat",
width: int = 1200,
height: int = 630 # OG image / featured image размер
) -> bytes:
style_prompt = ILLUSTRATION_STYLES.get(style, style)
content_prompt = await extract_illustration_prompt(
article_section, article_section, style_prompt
)
full_prompt = f"{content_prompt}, {style_prompt}, no text, professional quality"
# Генерируем через DALL-E 3 или FLUX
return await generate_image_dalle(full_prompt, size="1792x1024")
Batch-генерация для всей статьи
import re
from dataclasses import dataclass
@dataclass
class ArticleSection:
heading: str
content: str
illustration_prompt: str = ""
illustration_bytes: bytes = b""
async def illustrate_article(
article_markdown: str,
style: str = "flat",
illustrate_every_n_sections: int = 2
) -> list[ArticleSection]:
# Разбиваем на секции по H2/H3
sections = []
current_heading = "Introduction"
current_content = []
for line in article_markdown.split("\n"):
if line.startswith("## ") or line.startswith("### "):
if current_content:
sections.append(ArticleSection(current_heading, "\n".join(current_content)))
current_heading = line.lstrip("#").strip()
current_content = []
else:
current_content.append(line)
if current_content:
sections.append(ArticleSection(current_heading, "\n".join(current_content)))
# Генерируем иллюстрации для каждой N-й секции
for i, section in enumerate(sections):
if i % illustrate_every_n_sections == 0:
section.illustration_prompt = await extract_illustration_prompt(
article_markdown[:500], section.content, ILLUSTRATION_STYLES[style]
)
section.illustration_bytes = await generate_article_illustration(
section.content, style
)
return sections
Интеграция с CMS
class CMSIllustrationIntegration:
async def upload_to_wordpress(self, image_bytes: bytes, title: str) -> str:
"""Загружаем изображение в WordPress Media Library"""
import httpx
async with httpx.AsyncClient() as client:
resp = await client.post(
f"{WP_URL}/wp-json/wp/v2/media",
headers={
"Authorization": f"Basic {WP_AUTH}",
"Content-Disposition": f'attachment; filename="{title}.jpg"',
"Content-Type": "image/jpeg"
},
content=image_bytes
)
return resp.json()["source_url"]
DALL-E 3 генерирует иллюстрации, которые почти не нуждаются в постпроцессинге для редакционного использования. Для корпоративных блогов с постоянным стилем — LoRA на SDXL. Сроки: скрипт иллюстрирования статьи — 1–2 дня. Плагин для WordPress/Ghost с автоиллюстрированием — 1–2 недели.







