Разработка AI-системы генерации коротких видео для соцсетей
Автоматическая генерация short-form видео для TikTok, Instagram Reels, YouTube Shorts из текстового контента (статьи, новости, подкасты, продуктовые описания). Производительность: 10–50 готовых клипов в час.
Пайплайн short-video генерации
from dataclasses import dataclass
from openai import AsyncOpenAI
import asyncio
client = AsyncOpenAI()
@dataclass
class ShortVideoScript:
hook: str # первые 3 секунды — захват внимания
main_points: list[str]
cta: str
hashtags: list[str]
voiceover_text: str
visual_prompts: list[str] # промпты для AI-изображений
async def generate_short_video_script(
topic: str,
platform: str = "tiktok",
duration: int = 30,
tone: str = "engaging"
) -> ShortVideoScript:
response = await client.chat.completions.create(
model="gpt-4o",
messages=[{
"role": "system",
"content": f"""Создай сценарий для {duration}-секундного видео для {platform}.
Структура:
- Hook (3 сек): цепляющий старт с вопросом или удивительным фактом
- Main points (3-5 пунктов по 4-6 сек каждый)
- CTA (3 сек): призыв к действию
Тон: {tone}.
Для каждого блока — промпт для AI-визуала.
Верни JSON."""
}, {
"role": "user",
"content": f"Тема: {topic}"
}],
response_format={"type": "json_object"}
)
data = json.loads(response.choices[0].message.content)
return ShortVideoScript(**data)
Генерация визуального ряда
class ShortVideoVisualGenerator:
async def generate_visual_sequence(
self,
script: ShortVideoScript,
visual_style: str = "modern flat illustration"
) -> list[bytes]:
"""Генерируем изображение для каждого блока сценария"""
tasks = []
for prompt in script.visual_prompts:
full_prompt = f"{prompt}, {visual_style}, vertical 9:16 format, no text"
tasks.append(generate_image_dalle(full_prompt, size="1024x1792"))
return await asyncio.gather(*tasks)
Синтез воронки
import subprocess
from pydub import AudioSegment
import edge_tts
import tempfile
import os
class ShortVideoAssembler:
async def assemble(
self,
script: ShortVideoScript,
images: list[bytes],
background_music: bytes = None,
add_captions: bool = True
) -> bytes:
with tempfile.TemporaryDirectory() as tmpdir:
# 1. TTS озвучка
audio_path = os.path.join(tmpdir, "voiceover.mp3")
tts = edge_tts.Communicate(script.voiceover_text, voice="ru-RU-DmitryNeural", rate="+15%")
await tts.save(audio_path)
audio = AudioSegment.from_mp3(audio_path)
total_duration = len(audio) / 1000
# 2. Создаём слайдшоу из изображений
img_duration = total_duration / len(images)
image_paths = []
for i, img_bytes in enumerate(images):
img_path = os.path.join(tmpdir, f"img_{i:03d}.jpg")
with open(img_path, "wb") as f:
f.write(img_bytes)
image_paths.append(img_path)
# 3. Сборка через ffmpeg
# Создаём список изображений для ffmpeg
concat_file = os.path.join(tmpdir, "concat.txt")
with open(concat_file, "w") as f:
for img_path in image_paths:
f.write(f"file '{img_path}'\n")
f.write(f"duration {img_duration:.2f}\n")
slideshow_path = os.path.join(tmpdir, "slideshow.mp4")
subprocess.run([
"ffmpeg", "-f", "concat", "-safe", "0",
"-i", concat_file,
"-vf", "scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2",
"-r", "30", slideshow_path
], check=True)
# 4. Добавляем аудио
output_path = os.path.join(tmpdir, "output.mp4")
if background_music:
music_path = os.path.join(tmpdir, "music.mp3")
with open(music_path, "wb") as f:
f.write(background_music)
subprocess.run([
"ffmpeg", "-i", slideshow_path,
"-i", audio_path, "-i", music_path,
"-filter_complex",
f"[1:a]volume=1.0[vo];[2:a]volume=0.2,afade=out:st={total_duration-1}:d=1[bg];[vo][bg]amix=inputs=2[aout]",
"-map", "0:v", "-map", "[aout]",
"-shortest", "-y", output_path
], check=True)
else:
subprocess.run([
"ffmpeg", "-i", slideshow_path, "-i", audio_path,
"-map", "0:v", "-map", "1:a", "-shortest", "-y", output_path
], check=True)
with open(output_path, "rb") as f:
return f.read()
Автопостинг в соцсети
class SocialMediaPoster:
async def post_to_tiktok(self, video: bytes, caption: str, hashtags: list[str]): ...
async def post_to_instagram_reels(self, video: bytes, caption: str): ...
async def post_to_youtube_shorts(self, video: bytes, title: str, description: str): ...
async def post_to_vk_clips(self, video: bytes, description: str): ...
Сроки: генератор shorts из статьи (сценарий + TTS + слайдшоу) — 2–3 недели. Полная платформа с публикацией, аналитикой и A/B тестированием форматов — 2–3 месяца.







