跳到主要内容

技术栈详细说明

技术选型概览

┌─────────────────────────────────────────────────────────┐
│ 前端层 │
├─────────────────────────────────────────────────────────┤
│ React 18 + Next.js 14 + TailwindCSS + TypeScript │
│ 状态管理: Zustand │ 数据获取: SWR │ UI: Shadcn/ui │
└─────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────┐
│ 后端API层 │
├─────────────────────────────────────────────────────────┤
│ Django 4.2 + Django REST Framework + Python 3.11 │
│ 身份认证: JWT │ API文档: drf-spectacular │
└─────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────┐
│ 异步任务层 │
├─────────────────────────────────────────────────────────┤
│ Celery + RabbitMQ + Redis │
│ 任务调度 │ 失败重试 │ 结果存储 │
└─────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────┐
│ 视频处理层 │
├─────────────────────────────────────────────────────────┤
│ FFmpeg + MoviePy + OpenCV + Pillow │
│ GPU加速: NVIDIA CUDA │ 并发处理: ProcessPoolExecutor │
└─────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────┐
│ AI服务层 │
├─────────────────────────────────────────────────────────┤
│ OpenAI GPT-4 │ Azure TTS │ Optional: 数字人平台 │
└─────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────┐
│ 数据存储层 │
├─────────────────────────────────────────────────────────┤
│ PostgreSQL 14 │ Redis 7 │ 阿里云OSS/AWS S3 │
│ Elasticsearch (可选) │ InfluxDB (可选) │
└─────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────┐
│ 基础设施层 │
├─────────────────────────────────────────────────────────┤
│ Docker + Kubernetes │ Nginx │ CloudFlare CDN │
│ Prometheus + Grafana │ Sentry │ ELK Stack │
└─────────────────────────────────────────────────────────┘

一、前端技术栈

1. 核心框架

React 18

{
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}

选择理由:

  • 组件化开发,代码复用性强
  • 虚拟DOM,性能优秀
  • 生态丰富,社区活跃
  • 招聘容易,学习资源多

核心特性:

  • 并发渲染(Concurrent Rendering)
  • 自动批处理(Automatic Batching)
  • Suspense支持

Next.js 14

{
"dependencies": {
"next": "^14.0.0"
}
}

选择理由:

  • 服务端渲染(SSR),SEO友好
  • 文件系统路由,开发效率高
  • API Routes,前后端分离方便
  • 图像优化,性能更好
  • 内置TypeScript支持

项目结构:

app/
├── (auth)/
│ ├── login/
│ └── register/
├── dashboard/
│ ├── projects/
│ ├── templates/
│ └── videos/
├── api/
│ ├── auth/
│ └── videos/
├── layout.tsx
└── page.tsx

2. UI与样式

TailwindCSS

{
"devDependencies": {
"tailwindcss": "^3.3.0",
"autoprefixer": "^10.4.16",
"postcss": "^8.4.31"
}
}

优势:

  • 实用优先(Utility-first)
  • 快速开发
  • 响应式设计简单
  • 文件体积小(按需打包)

配置示例:

// tailwind.config.js
module.exports = {
content: [
'./app/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
],
theme: {
extend: {
colors: {
brand: {
50: '#f0f9ff',
500: '#3b82f6',
900: '#1e3a8a',
}
}
},
},
plugins: [],
}

Shadcn/ui

npx shadcn-ui@latest init

优势:

  • 基于Radix UI,可访问性好
  • 复制即用,无包依赖
  • 完全可定制
  • TypeScript原生支持

组件示例:

import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Input } from "@/components/ui/input"

export default function VideoForm() {
return (
<Card\>
\<Input placeholder="视频标题" /\>
<Button\>创建视频</Button\>
</Card\>
)
}

3. 状态管理

Zustand

npm install zustand

选择理由:

  • 轻量级(<1KB)
  • API简洁
  • 无需Provider包裹
  • TypeScript支持好

使用示例:

// store/videoStore.ts
import { create } from 'zustand'

interface VideoState {
videos: Video[]
isLoading: boolean
fetchVideos: () =\> Promise<void\>
createVideo: (data: VideoData) =\> Promise<void\>
}

export const useVideoStore = create<VideoState\>((set) =\> ({
videos: [],
isLoading: false,

fetchVideos: async () =\> {
set({ isLoading: true })
const videos = await api.getVideos()
set({ videos, isLoading: false })
},

createVideo: async (data) =\> {
const video = await api.createVideo(data)
set((state) =\> ({
videos: [...state.videos, video]
}))
}
}))

// 组件中使用
function VideoList() {
const { videos, fetchVideos } = useVideoStore()

useEffect(() =\> {
fetchVideos()
}, [])

return <div\>{videos.map(v =\> <VideoCard key={v.id} {...v} /\>)}</div\>
}

4. 数据获取

SWR

npm install swr

优势:

  • 自动缓存
  • 自动重新验证
  • 错误重试
  • 分页支持

使用示例:

import useSWR from 'swr'

const fetcher = (url: string) =\> fetch(url).then(r =\> r.json())

function Projects() {
const { data, error, isLoading } = useSWR('/api/projects', fetcher)

if (isLoading) return <Skeleton /\>
if (error) return <Error /\>

return <ProjectList projects={data} /\>
}

5. 表单处理

React Hook Form

npm install react-hook-form zod @hookform/resolvers

优势:

  • 性能优秀(无受控组件)
  • TypeScript支持
  • 验证集成(Zod)
  • 文件体积小

使用示例:

import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import * as z from 'zod'

const schema = z.object({
title: z.string().min(1, '标题不能为空'),
description: z.string().optional(),
})

type FormData = z.infer<typeof schema\>

function CreateVideoForm() {
const { register, handleSubmit, formState: { errors } } = useForm<FormData\>({
resolver: zodResolver(schema)
})

const onSubmit = (data: FormData) =\> {
console.log(data)
}

return (
<form onSubmit={handleSubmit(onSubmit)}\>
<input {...register('title')} /\>
{errors.title && <span\>{errors.title.message}</span\>}
\<button type="submit"\>提交</button\>
</form\>
)
}

二、后端技术栈

1. Django + DRF

Django 4.2

pip install django==4.2

项目结构:

backend/
├── config/
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── apps/
│ ├── users/
│ ├── projects/
│ ├── templates/
│ ├── videos/
│ └── tasks/
├── core/
│ ├── models.py
│ ├── mixins.py
│ └── utils.py
├── media/
├── static/
└── manage.py

Django REST Framework

pip install djangorestframework==3.14.0

API示例:

# serializers.py
from rest_framework import serializers
from .models import Video

class VideoSerializer(serializers.ModelSerializer):
class Meta:
model = Video
fields = ['id', 'title', 'status', 'file_url', 'created_at']
read_only_fields = ['id', 'created_at']

# views.py
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response

class VideoViewSet(viewsets.ModelViewSet):
queryset = Video.objects.all()
serializer_class = VideoSerializer

@action(detail=False, methods=['post'])
def batch_create(self, request):
"""批量创建视频"""
data_list = request.data.get('videos', [])
task = batch_render_task.delay(data_list)
return Response({'task_id': task.id})

@action(detail=True, methods=['get'])
def download(self, request, pk=None):
"""下载视频"""
video = self.get_object()
return redirect(video.file_url)

2. 数据库与ORM

PostgreSQL

# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'videomatic',
'USER': 'postgres',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432',
}
}

模型示例:

from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
plan = models.CharField(max_length=50, default='free')
quota_used = models.IntegerField(default=0)
quota_limit = models.IntegerField(default=10)

class Template(models.Model):
name = models.CharField(max_length=255)
category = models.CharField(max_length=100)
config = models.JSONField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)

class Video(models.Model):
STATUS_CHOICES = [
('queued', '排队中'),
('rendering', '渲染中'),
('completed', '已完成'),
('failed', '失败'),
]

user = models.ForeignKey(User, on_delete=models.CASCADE)
template = models.ForeignKey(Template, on_delete=models.SET_NULL, null=True)
status = models.CharField(max_length=50, choices=STATUS_CHOICES)
file_url = models.URLField(blank=True)
progress = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)

3. 异步任务

Celery

# celery.py
from celery import Celery
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')

app = Celery('videomatic')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

# settings.py
CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Shanghai'

# tasks.py
from celery import shared_task
from .services import VideoRenderer

@shared_task(bind=True, max_retries=3)
def render_video_task(self, template_id, data):
try:
renderer = VideoRenderer()
video_path = renderer.render(template_id, data)
return {'status': 'success', 'path': video_path}
except Exception as exc:
raise self.retry(exc=exc, countdown=60)

三、视频处理技术栈

1. FFmpeg

# 安装
apt-get install ffmpeg
# 或
brew install ffmpeg

Python封装:

pip install ffmpeg-python

使用示例:

import ffmpeg

def process_video(input_file, output_file):
"""处理视频"""
stream = (
ffmpeg
.input(input_file)
.filter('scale', 1080, 1920)
.filter('fps', fps=30)
.output(output_file, vcodec='libx264', crf=23)
)

ffmpeg.run(stream, overwrite_output=True)

2. MoviePy

pip install moviepy

使用示例:

from moviepy.editor import *

def create_video_with_text(background, text_content):
"""创建带文字的视频"""
# 背景视频
video = VideoFileClip(background)

# 文字
txt = TextClip(
text_content,
fontsize=70,
color='white',
font='Arial-Bold'
)
txt = txt.set_position('center').set_duration(video.duration)

# 合成
final = CompositeVideoClip([video, txt])
final.write_videofile("output.mp4", fps=30)

四、AI服务集成

1. OpenAI

pip install openai
from openai import OpenAI

client = OpenAI(api_key="sk-...")

def generate_script(product_name):
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "你是视频文案专家"},
{"role": "user", "content": f"为{product_name}写15秒短视频文案"}
]
)
return response.choices[0].message.content

2. Azure TTS

pip install azure-cognitiveservices-speech
import azure.cognitiveservices.speech as speechsdk

def text_to_speech(text, output_file):
speech_config = speechsdk.SpeechConfig(
subscription="your-key",
region="eastasia"
)

audio_config = speechsdk.audio.AudioOutputConfig(filename=output_file)
synthesizer = speechsdk.SpeechSynthesizer(
speech_config=speech_config,
audio_config=audio_config
)

synthesizer.speak_text(text)

五、DevOps与部署

1. Docker

# Dockerfile
FROM python:3.11-slim

WORKDIR /app

# 安装FFmpeg
RUN apt-get update && apt-get install -y ffmpeg

# 安装Python依赖
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["gunicorn", "config.wsgi:application", "--bind", "0.0.0.0:8000"]

2. docker-compose

version: '3.8'

services:
db:
image: postgres:14
environment:
POSTGRES_DB: videomatic
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data

redis:
image: redis:7-alpine

rabbitmq:
image: rabbitmq:3-management
ports:
- "5672:5672"
- "15672:15672"

web:
build: .
command: gunicorn config.wsgi:application --bind 0.0.0.0:8000
volumes:
- .:/app
ports:
- "8000:8000"
depends_on:
- db
- redis
- rabbitmq

celery:
build: .
command: celery -A config worker -l info
volumes:
- .:/app
depends_on:
- db
- redis
- rabbitmq

volumes:
postgres_data:

六、完整依赖清单

Python (requirements.txt)

# Django
Django==4.2.7
djangorestframework==3.14.0
django-cors-headers==4.3.0
drf-spectacular==0.27.0

# Database
psycopg2-binary==2.9.9
redis==5.0.1

# Celery
celery==5.3.4
celery[redis]==5.3.4

# Video Processing
ffmpeg-python==0.2.0
moviepy==1.0.3
Pillow==10.1.0
opencv-python==4.8.1.78

# AI Services
openai==1.3.7
azure-cognitiveservices-speech==1.33.0

# Storage
boto3==1.29.7 # AWS S3
oss2==2.18.2 # Aliyun OSS

# Utilities
python-dotenv==1.0.0
requests==2.31.0
pandas==2.1.3

# Production
gunicorn==21.2.0
sentry-sdk==1.38.0

JavaScript (package.json)

{
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"next": "^14.0.4",
"typescript": "^5.3.3",

"zustand": "^4.4.7",
"swr": "^2.2.4",
"react-hook-form": "^7.49.2",
"zod": "^3.22.4",
"@hookform/resolvers": "^3.3.3",

"tailwindcss": "^3.3.6",
"@radix-ui/react-dialog": "^1.0.5",
"@radix-ui/react-dropdown-menu": "^2.0.6",

"axios": "^1.6.2",
"date-fns": "^2.30.0",
"lucide-react": "^0.294.0"
},
"devDependencies": {
"@types/react": "^18.2.45",
"@types/node": "^20.10.5",
"autoprefixer": "^10.4.16",
"postcss": "^8.4.32",
"eslint": "^8.56.0",
"prettier": "^3.1.1"
}
}

更新记录

  • 2025-01-08: 初始版本,完成技术栈说明