环境搭建与快速开始
1. 环境要求
1.1 硬件要求
最低配置(CPU模式)
- CPU: 4核心以上
- 内存: 8GB以上
- 存储: 50GB以上可用空间
- 网络: 稳定的互联网连接
推荐配置(GPU模式)
- CPU: 8核心以上
- 内存: 16GB以上
- GPU: NVIDIA GPU,24GB显存以上
- 存储: 100GB以上可用空间
- 网络: 稳定的互联网连接
1.2 软件要求
基础环境
- 操作系统: Ubuntu 20.04+ / CentOS 8+ / macOS 10.15+ / Windows 10+
- Python: 3.10+
- Git: 2.30+
可选环境
- Docker: 20.10+(用于容器化部署)
- Docker Compose: 2.0+(用于多服务编排)
- NVIDIA Driver: 470+(用于GPU加速)
- CUDA: 11.8+(用于GPU计算)
2. 环境安装
2.1 Python环境安装
使用Conda(推荐)
# 下载并安装Miniconda
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
# 创建虚拟环境
conda create -n ai-ui python=3.10 -y
conda activate ai-ui
使用pyenv
# 安装pyenv
curl https://pyenv.run | bash
# 安装Python 3.10
pyenv install 3.10.11
pyenv global 3.10.11
# 创建虚拟环境
python -m venv ai-ui-env
source ai-ui-env/bin/activate
2.2 依赖安装
安装基础依赖
# 更新包管理器
sudo apt update # Ubuntu/Debian
# 或
sudo yum update # CentOS/RHEL
# 安装系统依赖
sudo apt install -y build-essential curl git wget
# 或
sudo yum groupinstall -y "Development Tools"
sudo yum install -y curl git wget
安装Python依赖
# 克隆项目
git clone <repository-url>
cd ai-ui-system
# 安装Python依赖
pip install -r requirements.txt
2.3 GPU环境安装(可选)
安装NVIDIA驱动
# 检查GPU信息
lspci | grep -i nvidia
# 安装NVIDIA驱动
sudo apt install nvidia-driver-470
# 或使用官方安装脚本
wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-ubuntu2004.pin
sudo mv cuda-ubuntu2004.pin /etc/apt/preferences.d/cuda-repository-pin-600
wget https://developer.download.nvidia.com/compute/cuda/11.8.0/local_installers/cuda-repo-ubuntu2004-11-8-local_11.8.0-520.61.05-1_amd64.deb
sudo dpkg -i cuda-repo-ubuntu2004-11-8-local_11.8.0-520.61.05-1_amd64.deb
sudo cp /var/cuda-repo-ubuntu2004-11-8-local/cuda-*-keyring.gpg /usr/share/keyrings/
sudo apt-get update
sudo apt-get -y install cuda
安装CUDA
# 设置环境变量
echo 'export PATH=/usr/local/cuda/bin:$PATH' >> ~/.bashrc
echo 'export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH' >> ~/.bashrc
source ~/.bashrc
# 验证安装
nvcc --version
nvidia-smi
安装PyTorch GPU版本
# 安装PyTorch GPU版本
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
2.4 Docker环境安装(可选)
安装Docker
# 安装Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
# 启动Docker服务
sudo systemctl start docker
sudo systemctl enable docker
# 添加用户到docker组
sudo usermod -aG docker $USER
安装Docker Compose
# 安装Docker Compose
sudo curl -L "https://github.com/docker/compose/releases/download/v2.20.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
# 验证安装
docker --version
docker-compose --version
3. 项目配置
3.1 目录结构
# 创建项目目录结构
mkdir -p ai-ui-system/{data,train,inference,render,api,config,docker,scripts,docs,tests,output/{images,vue,dsl},logs,models}
3.2 配置文件
模型配置文件
创建 config/model_config.yaml:
# AI UI生成系统配置文件
# 模型配置
model:
base_model: "google/flan-t5-base" # 基础模型
max_length: 512 # 最大序列长度
temperature: 0.7 # 生成温度
top_p: 0.9 # 核采样参数
top_k: 50 # Top-K采样
# LoRA配置
lora:
r: 16 # LoRA秩
lora_alpha: 32 # LoRA缩放参数
lora_dropout: 0.1 # LoRA dropout
target_modules: ["q", "v"] # 目标模块
# 训练配置
training:
learning_rate: 2e-4 # 学习率
batch_size: 4 # 批次大小
gradient_accumulation_steps: 4 # 梯度累积步数
num_epochs: 3 # 训练轮数
warmup_steps: 100 # 预热步数
max_grad_norm: 1.0 # 梯度裁剪
fp16: true # 半精度训练
dataloader_num_workers: 4 # 数据加载器工作进程数
# 数据配置
data:
train_split: 0.8 # 训练集比例
val_split: 0.1 # 验证集比例
test_split: 0.1 # 测试集比例
max_samples: 10000 # 最大样本数
# UI配置
ui:
themes:
- "obsidian-gold" # 黑金主题
- "silver-white" # 白银主题
- "minimal" # 简约主题
page_types:
- "home" # 首页
- "detail" # 详情页
- "search" # 搜索页
- "profile" # 个人页
- "publish" # 发布页
# 渲染配置
render:
image:
width: 375 # 图片宽度
height: 812 # 图片高度
dpi: 72 # 图片DPI
vue:
framework: "uniapp" # Vue框架
components_path: "components" # 组件路径
# API配置
api:
host: "0.0.0.0" # API主机
port: 8000 # API端口
workers: 1 # 工作进程数
timeout: 300 # 请求超时时间
# 日志配置
logging:
level: "INFO" # 日志级别
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
file: "logs/ai-ui-system.log" # 日志文件路径
UI令牌配置文件
创建 config/ui_tokens.json:
{
"themes": {
"obsidian-gold": {
"name": "黑金主题",
"colors": {
"primary": "#FFD700",
"secondary": "#B8860B",
"background": "#0E0E0E",
"surface": "#1A1A1A",
"text": "#FFFFFF",
"text_secondary": "#CCCCCC",
"border": "#333333",
"accent": "#FF6B35",
"success": "#4CAF50",
"warning": "#FF9800",
"error": "#F44336"
}
},
"silver-white": {
"name": "白银主题",
"colors": {
"primary": "#6B7280",
"secondary": "#9CA3AF",
"background": "#FFFFFF",
"surface": "#F9FAFB",
"text": "#111827",
"text_secondary": "#6B7280",
"border": "#E5E7EB",
"accent": "#3B82F6",
"success": "#10B981",
"warning": "#F59E0B",
"error": "#EF4444"
}
},
"minimal": {
"name": "简约主题",
"colors": {
"primary": "#000000",
"secondary": "#666666",
"background": "#FFFFFF",
"surface": "#FFFFFF",
"text": "#000000",
"text_secondary": "#666666",
"border": "#E0E0E0",
"accent": "#007AFF",
"success": "#34C759",
"warning": "#FF9500",
"error": "#FF3B30"
}
}
}
}
3.3 环境变量
创建 .env 文件:
# API配置
API_HOST=0.0.0.0
API_PORT=8000
API_WORKERS=1
# 模型配置
MODEL_PATH=google/flan-t5-base
LORA_PATH=models/ui-dsl-lora
# 渲染配置
IMAGE_WIDTH=375
IMAGE_HEIGHT=812
IMAGE_DPI=72
# 日志配置
LOG_LEVEL=INFO
LOG_FILE=logs/ai-ui-system.log
# Redis配置(可选)
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_DB=0
4. 快速开始
4.1 环境检查
# 检查Python版本
python --version
# 检查PyTorch安装
python -c "import torch; print(torch.__version__)"
# 检查GPU可用性
python -c "import torch; print(torch.cuda.is_available())"
# 检查其他依赖
python -c "import transformers, peft, fastapi, PIL; print('All dependencies installed')"
4.2 生成示例数据
# 生成示例数据集
python data/generate_synthetic_data.py \
--output_dir data/synthetic \
--num_samples 100
# 查看生成的数据
ls -la data/synthetic/
head -5 data/synthetic/train.jsonl
4.3 快速测试
使用规则生成(无需模型)
# 生成UI设计
python inference/generate_ui.py \
--prompt "黑金风格的电商首页,顶部搜索,中间两列商品卡,底部导航" \
--output output/test_home.json \
--use_rules
# 查看生成的DSL
cat output/test_home.json
渲染为图片
# 渲染为PNG图片
python render/render_to_image.py \
--dsl output/test_home.json \
--output output/images/test_home.png
# 查看生成的图片
ls -la output/images/
渲染为Vue页面
# 渲染为Vue页面
python render/render_to_vue.py \
--dsl output/test_home.json \
--output output/vue/test_home.vue
# 查看生成的Vue代码
head -20 output/vue/test_home.vue
4.4 启动API服务
# 启动FastAPI服务
python api/main.py
# 在另一个终端测试API
curl -X POST "http://localhost:8000/generate-ui" \
-H "Content-Type: application/json" \
-d '{"prompt": "黑金风格的电商首页", "output_format": "json"}'
5. 验证安装
5.1 功能验证
数据生成验证
# 运行数据生成测试
python -c "
from data.generate_synthetic_data import UIDataGenerator
generator = UIDataGenerator()
dataset = generator.generate_dataset(10)
print(f'Generated {len(dataset)} samples')
print('Sample:', dataset[0])
"
模型推理验证
# 运行推理测试
python -c "
from inference.generate_ui import UIGenerator
generator = UIGenerator()
result = generator.generate('黑金风格的电商首页', use_model=False)
print('Success:', result['success'])
print('Method:', result['method'])
"
渲染验证
# 运行渲染测试
python -c "
from render.render_to_image import UIRenderer
from render.render_to_vue import VueRenderer
import json
# 测试数据
dsl = {
'page': {
'name': 'test_page',
'theme': 'obsidian-gold',
'sections': [
{'type': 'topbar', 'props': {'title': '测试页面'}}
]
}
}
# 测试图片渲染
image_renderer = UIRenderer()
image = image_renderer.render(dsl)
print('Image rendered:', image.size)
# 测试Vue渲染
vue_renderer = VueRenderer()
vue_content = vue_renderer.render(dsl)
print('Vue rendered:', len(vue_content))
"
5.2 性能验证
GPU性能测试
# GPU性能测试
python -c "
import torch
import time
if torch.cuda.is_available():
device = torch.device('cuda')
x = torch.randn(1000, 1000).to(device)
y = torch.randn(1000, 1000).to(device)
start_time = time.time()
for _ in range(100):
z = torch.matmul(x, y)
torch.cuda.synchronize()
end_time = time.time()
print(f'GPU computation time: {end_time - start_time:.4f}s')
print(f'GPU memory: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.1f}GB')
else:
print('GPU not available')
"
API性能测试
# API性能测试
python -c "
import requests
import time
url = 'http://localhost:8000/health'
times = []
for _ in range(10):
start_time = time.time()
response = requests.get(url)
end_time = time.time()
times.append(end_time - start_time)
avg_time = sum(times) / len(times)
print(f'Average response time: {avg_time:.4f}s')
print(f'Min response time: {min(times):.4f}s')
print(f'Max response time: {max(times):.4f}s')
"
6. 常见问题
6.1 安装问题
Python版本问题
conda install python=3.10
# 或
pyenv install 3.10.11
pyenv global 3.10.11
依赖冲突问题
conda create -n ai-ui-new python=3.10 -y
conda activate ai-ui-new
pip install -r requirements.txt
GPU驱动问题
pip uninstall torch torchvision torchaudio
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
6.2 运行问题
内存不足问题
# 编辑 config/model_config.yaml
training:
batch_size: 2 # 减小批次大小
gradient_accumulation_steps: 8 # 增加梯度累积
端口占用问题
# 方法1: 更改端口
export API_PORT=8001
python api/main.py
# 方法2: 停止占用进程
lsof -ti:8000 | xargs kill -9
权限问题
chmod +x data/generate_synthetic_data.py
chmod +x train/finetune_lora.py
chmod +x inference/generate_ui.py
6.3 性能问题
推理速度慢
# 编辑 config/model_config.yaml
model:
max_length: 256 # 减小最大长度
temperature: 0.3 # 降低温度
内存使用过高
# 编辑 config/model_config.yaml
training:
fp16: true # 启用半精度训练
7. 下一步
环境搭建完成后,您可以:
8. 总结
通过本章的学习,您已经完成了:
- 环境安装: Python、PyTorch、依赖包等
- 项目配置: 配置文件、环境变量等
- 快速测试: 数据生成、模型推理、渲染等
- 功能验证: 各模块功能验证
- 问题解决: 常见问题的解决方案
现在您已经具备了运行AI UI生成系统的基础环境,可以开始深入学习系统的各个模块了。