'commit'
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
import json
|
||||
|
||||
from Config.Config import OBS_BUCKET, OBS_SERVER
|
||||
from LibLibGenerator import LibLibGenerator
|
||||
from Liblib.Kit.LibLibGenerator import LibLibGenerator
|
||||
|
||||
|
||||
class PuLIDGenerator:
|
||||
def __init__(self):
|
||||
|
BIN
dsLightRag/Liblib/Kit/__pycache__/PuLIDGenerator.cpython-310.pyc
Normal file
BIN
dsLightRag/Liblib/Kit/__pycache__/PuLIDGenerator.cpython-310.pyc
Normal file
Binary file not shown.
176
dsLightRag/Routes/CopyFaceRoute.py
Normal file
176
dsLightRag/Routes/CopyFaceRoute.py
Normal file
@@ -0,0 +1,176 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from typing import Optional, List
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from Liblib.Kit.PuLIDGenerator import PuLIDGenerator
|
||||
|
||||
# 创建路由路由器
|
||||
router = APIRouter(prefix="/api/copyface", tags=["人像换脸"])
|
||||
|
||||
# 配置日志
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# JSON配置文件路径
|
||||
COPY_FACE_CONFIG_PATH = os.path.join(os.path.dirname(__file__), "..", "Liblib", "Data", "copy_face_image_data.json")
|
||||
|
||||
class CopyFaceRequest(BaseModel):
|
||||
image_url: str
|
||||
|
||||
class ModelSample(BaseModel):
|
||||
name: str
|
||||
template_uuid: str
|
||||
steps: int
|
||||
width: int
|
||||
height: int
|
||||
cfgScale: float
|
||||
sampler: str
|
||||
seed: int
|
||||
prompt: str
|
||||
negative_prompt: Optional[str] = None
|
||||
reference_image_url: str
|
||||
control_weight: float
|
||||
|
||||
@router.get("/samples", response_model=List[ModelSample])
|
||||
async def get_available_samples():
|
||||
"""
|
||||
获取所有可用的生成样例配置
|
||||
|
||||
Returns:
|
||||
包含所有可用模型样例的列表
|
||||
"""
|
||||
try:
|
||||
# 读取配置文件
|
||||
with open(COPY_FACE_CONFIG_PATH, 'r', encoding='utf-8') as f:
|
||||
config_data = json.load(f)
|
||||
|
||||
# 返回所有模型配置
|
||||
return config_data["models"]
|
||||
|
||||
except FileNotFoundError:
|
||||
logger.error(f"配置文件未找到: {COPY_FACE_CONFIG_PATH}")
|
||||
raise HTTPException(status_code=404, detail="配置文件未找到")
|
||||
except json.JSONDecodeError:
|
||||
logger.error(f"配置文件格式错误: {COPY_FACE_CONFIG_PATH}")
|
||||
raise HTTPException(status_code=500, detail="配置文件格式错误")
|
||||
except Exception as e:
|
||||
logger.error(f"获取样例配置失败: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=f"获取样例配置失败: {str(e)}")
|
||||
|
||||
@router.post("/generate", response_model=dict)
|
||||
async def generate_copy_face(request: CopyFaceRequest):
|
||||
"""
|
||||
根据提供的图片URL生成模拟人脸图片(使用默认配置)
|
||||
|
||||
Args:
|
||||
request: 包含图片URL的请求体
|
||||
|
||||
Returns:
|
||||
包含生成图片OBS地址的字典
|
||||
"""
|
||||
try:
|
||||
# 读取默认配置(第一个模型)
|
||||
with open(COPY_FACE_CONFIG_PATH, 'r', encoding='utf-8') as f:
|
||||
config_data = json.load(f)
|
||||
|
||||
default_config = config_data["models"][0]
|
||||
|
||||
# 使用默认配置
|
||||
generator = PuLIDGenerator()
|
||||
|
||||
# 设置默认参数
|
||||
generator.set_default_params(
|
||||
template_uuid=default_config["template_uuid"],
|
||||
steps=default_config["steps"],
|
||||
width=default_config["width"],
|
||||
height=default_config["height"]
|
||||
)
|
||||
|
||||
# 生成图像
|
||||
obs_url = generator.generate_image(
|
||||
prompt=default_config["prompt"],
|
||||
reference_image_url=request.image_url,
|
||||
control_weight=default_config["control_weight"]
|
||||
)
|
||||
|
||||
if obs_url:
|
||||
logger.info(f"人像换脸生成成功,OBS地址: {obs_url}")
|
||||
return {
|
||||
"status": "success",
|
||||
"obs_url": obs_url,
|
||||
"message": "人像换脸生成成功",
|
||||
"model_used": default_config["name"]
|
||||
}
|
||||
else:
|
||||
logger.error("人像换脸生成失败")
|
||||
raise HTTPException(status_code=500, detail="人像换脸生成失败")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"人像换脸请求处理失败: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=f"人像换脸请求处理失败: {str(e)}")
|
||||
|
||||
@router.post("/generate/{model_name}", response_model=dict)
|
||||
async def generate_copy_face_with_model(model_name: str, request: CopyFaceRequest):
|
||||
"""
|
||||
根据指定的模型名称和图片URL生成模拟人脸图片
|
||||
|
||||
Args:
|
||||
model_name: 模型名称(如:炫酷机甲美女_majicflus)
|
||||
request: 包含图片URL的请求体
|
||||
|
||||
Returns:
|
||||
包含生成图片OBS地址的字典
|
||||
"""
|
||||
try:
|
||||
# 读取配置文件
|
||||
with open(COPY_FACE_CONFIG_PATH, 'r', encoding='utf-8') as f:
|
||||
config_data = json.load(f)
|
||||
|
||||
# 查找指定的模型配置
|
||||
model_config = None
|
||||
for model in config_data["models"]:
|
||||
if model["name"] == model_name:
|
||||
model_config = model
|
||||
break
|
||||
|
||||
if not model_config:
|
||||
raise HTTPException(status_code=404, detail=f"未找到模型: {model_name}")
|
||||
|
||||
# 使用指定配置
|
||||
generator = PuLIDGenerator()
|
||||
|
||||
# 设置参数
|
||||
generator.set_default_params(
|
||||
template_uuid=model_config["template_uuid"],
|
||||
steps=model_config["steps"],
|
||||
width=model_config["width"],
|
||||
height=model_config["height"]
|
||||
)
|
||||
|
||||
# 生成图像
|
||||
obs_url = generator.generate_image(
|
||||
prompt=model_config["prompt"],
|
||||
reference_image_url=request.image_url,
|
||||
control_weight=model_config["control_weight"]
|
||||
)
|
||||
|
||||
if obs_url:
|
||||
logger.info(f"人像换脸生成成功,模型: {model_name}, OBS地址: {obs_url}")
|
||||
return {
|
||||
"status": "success",
|
||||
"obs_url": obs_url,
|
||||
"message": "人像换脸生成成功",
|
||||
"model_used": model_name
|
||||
}
|
||||
else:
|
||||
logger.error(f"人像换脸生成失败,模型: {model_name}")
|
||||
raise HTTPException(status_code=500, detail="人像换脸生成失败")
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"人像换脸请求处理失败: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=f"人像换脸请求处理失败: {str(e)}")
|
BIN
dsLightRag/Routes/__pycache__/CopyFaceRoute.cpython-310.pyc
Normal file
BIN
dsLightRag/Routes/__pycache__/CopyFaceRoute.cpython-310.pyc
Normal file
Binary file not shown.
@@ -29,6 +29,7 @@ from Routes.ZuoWen import router as zuowen_router
|
||||
from Routes.RecognizeEduQuestion import router as ocr_router
|
||||
from Routes.VideoRetalkRoute import router as videoRetalk_router
|
||||
from Routes.ttsRoute import router as tts_router
|
||||
from Routes.CopyFaceRoute import router as copyFace_router
|
||||
# 控制日志输出
|
||||
logger = logging.getLogger('lightrag')
|
||||
logger.setLevel(logging.INFO)
|
||||
@@ -84,6 +85,7 @@ app.include_router(ocr_router) # 教育场景识别
|
||||
app.include_router(videoRetalk_router) # 视频复读
|
||||
app.include_router(tts_router) # 文本转语音
|
||||
|
||||
app.include_router(copyFace_router) # 抄脸
|
||||
|
||||
# Teaching Model 相关路由
|
||||
# 登录相关(不用登录)
|
||||
|
301
dsLightRag/static/LibLib/copyface.html
Normal file
301
dsLightRag/static/LibLib/copyface.html
Normal file
@@ -0,0 +1,301 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>人像换脸生成器</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
.container {
|
||||
background: white;
|
||||
padding: 30px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
}
|
||||
h1 {
|
||||
color: #333;
|
||||
text-align: center;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
.form-group {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 5px;
|
||||
font-weight: bold;
|
||||
color: #555;
|
||||
}
|
||||
input[type="url"], select {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 5px;
|
||||
font-size: 14px;
|
||||
}
|
||||
button {
|
||||
background-color: #007bff;
|
||||
color: white;
|
||||
padding: 12px 24px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
margin-right: 10px;
|
||||
}
|
||||
button:hover {
|
||||
background-color: #0056b3;
|
||||
}
|
||||
button:disabled {
|
||||
background-color: #6c757d;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.image-preview {
|
||||
margin-top: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
.image-preview img {
|
||||
max-width: 300px;
|
||||
max-height: 300px;
|
||||
border: 2px solid #ddd;
|
||||
border-radius: 5px;
|
||||
}
|
||||
.result {
|
||||
margin-top: 30px;
|
||||
padding: 20px;
|
||||
background-color: #f8f9fa;
|
||||
border-radius: 5px;
|
||||
border-left: 4px solid #007bff;
|
||||
}
|
||||
.result img {
|
||||
max-width: 100%;
|
||||
max-height: 400px;
|
||||
border: 2px solid #28a745;
|
||||
border-radius: 5px;
|
||||
}
|
||||
.loading {
|
||||
display: none;
|
||||
text-align: center;
|
||||
margin: 20px 0;
|
||||
}
|
||||
.spinner {
|
||||
border: 4px solid #f3f3f3;
|
||||
border-top: 4px solid #007bff;
|
||||
border-radius: 50%;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
animation: spin 1s linear infinite;
|
||||
margin: 0 auto;
|
||||
}
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
.error {
|
||||
color: #dc3545;
|
||||
background-color: #f8d7da;
|
||||
border: 1px solid #f5c6cb;
|
||||
padding: 10px;
|
||||
border-radius: 5px;
|
||||
margin: 10px 0;
|
||||
}
|
||||
.success {
|
||||
color: #155724;
|
||||
background-color: #d4edda;
|
||||
border: 1px solid #c3e6cb;
|
||||
padding: 10px;
|
||||
border-radius: 5px;
|
||||
margin: 10px 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1>🎭 人像换脸生成器</h1>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="imageUrl">图片URL地址:</label>
|
||||
<input type="url" id="imageUrl" placeholder="请输入图片URL地址"
|
||||
value="https://dsideal.obs.cn-north-1.myhuaweicloud.com/HuangHai/Backup/HuangWanQiao.jpg">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="modelSelect">选择生成模型:</label>
|
||||
<select id="modelSelect">
|
||||
<option value="">加载中...</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="image-preview" id="previewContainer">
|
||||
<h3>参考图片预览:</h3>
|
||||
<img id="previewImage" src="https://dsideal.obs.cn-north-1.myhuaweicloud.com/HuangHai/Backup/HuangWanQiao.jpg"
|
||||
alt="参考图片预览" onerror="this.style.display='none'">
|
||||
</div>
|
||||
|
||||
<button onclick="generateImage()" id="generateBtn">生成换脸图片</button>
|
||||
<button onclick="loadSamples()" id="refreshBtn">刷新模型列表</button>
|
||||
|
||||
<div class="loading" id="loading">
|
||||
<div class="spinner"></div>
|
||||
<p>正在生成中,请稍候...</p>
|
||||
</div>
|
||||
|
||||
<div class="result" id="resultContainer" style="display: none;">
|
||||
<h3>生成结果:</h3>
|
||||
<div id="resultMessage"></div>
|
||||
<div id="resultImage"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const API_BASE = '/api/copyface';
|
||||
|
||||
// 页面加载时获取可用模型
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
loadSamples();
|
||||
|
||||
// 监听URL输入变化,实时预览
|
||||
document.getElementById('imageUrl').addEventListener('input', function() {
|
||||
const url = this.value.trim();
|
||||
const previewImg = document.getElementById('previewImage');
|
||||
if (url) {
|
||||
previewImg.src = url;
|
||||
previewImg.style.display = 'block';
|
||||
} else {
|
||||
previewImg.style.display = 'none';
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 加载可用模型样例
|
||||
async function loadSamples() {
|
||||
const select = document.getElementById('modelSelect');
|
||||
const refreshBtn = document.getElementById('refreshBtn');
|
||||
|
||||
refreshBtn.disabled = true;
|
||||
refreshBtn.textContent = '加载中...';
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/samples`);
|
||||
if (!response.ok) {
|
||||
throw new Error('获取模型列表失败');
|
||||
}
|
||||
|
||||
const samples = await response.json();
|
||||
|
||||
// 清空并填充选项
|
||||
select.innerHTML = '';
|
||||
samples.forEach(sample => {
|
||||
const option = document.createElement('option');
|
||||
option.value = sample.name;
|
||||
option.textContent = sample.name;
|
||||
select.appendChild(option);
|
||||
});
|
||||
|
||||
if (samples.length > 0) {
|
||||
select.value = samples[0].name;
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('加载模型失败:', error);
|
||||
select.innerHTML = '<option value="">加载失败,点击刷新</option>';
|
||||
} finally {
|
||||
refreshBtn.disabled = false;
|
||||
refreshBtn.textContent = '刷新模型列表';
|
||||
}
|
||||
}
|
||||
|
||||
// 生成换脸图片
|
||||
async function generateImage() {
|
||||
const imageUrl = document.getElementById('imageUrl').value.trim();
|
||||
const modelName = document.getElementById('modelSelect').value;
|
||||
const generateBtn = document.getElementById('generateBtn');
|
||||
const loading = document.getElementById('loading');
|
||||
const resultContainer = document.getElementById('resultContainer');
|
||||
const resultMessage = document.getElementById('resultMessage');
|
||||
const resultImage = document.getElementById('resultImage');
|
||||
|
||||
// 验证输入
|
||||
if (!imageUrl) {
|
||||
alert('请输入图片URL地址');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!modelName) {
|
||||
alert('请选择生成模型');
|
||||
return;
|
||||
}
|
||||
|
||||
// 显示加载状态
|
||||
generateBtn.disabled = true;
|
||||
loading.style.display = 'block';
|
||||
resultContainer.style.display = 'none';
|
||||
|
||||
try {
|
||||
let apiUrl = `${API_BASE}/generate`;
|
||||
if (modelName) {
|
||||
apiUrl = `${API_BASE}/generate/${encodeURIComponent(modelName)}`;
|
||||
}
|
||||
|
||||
const response = await fetch(apiUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
image_url: imageUrl
|
||||
})
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (response.ok && result.status === 'success') {
|
||||
// 显示成功结果
|
||||
resultMessage.innerHTML = `
|
||||
<div class="success">
|
||||
✅ ${result.message}<br>
|
||||
📦 使用模型: ${result.model_used}<br>
|
||||
🌐 OBS地址: <a href="${result.obs_url}" target="_blank">${result.obs_url}</a>
|
||||
</div>
|
||||
`;
|
||||
|
||||
resultImage.innerHTML = `
|
||||
<h4>生成结果预览:</h4>
|
||||
<img src="${result.obs_url}" alt="生成结果"
|
||||
onerror="this.style.display='none'; alert('图片加载失败,请检查OBS地址')">
|
||||
`;
|
||||
|
||||
} else {
|
||||
// 显示错误信息
|
||||
resultMessage.innerHTML = `
|
||||
<div class="error">
|
||||
❌ 生成失败: ${result.detail || result.message || '未知错误'}
|
||||
</div>
|
||||
`;
|
||||
resultImage.innerHTML = '';
|
||||
}
|
||||
|
||||
resultContainer.style.display = 'block';
|
||||
|
||||
} catch (error) {
|
||||
console.error('生成请求失败:', error);
|
||||
resultMessage.innerHTML = `
|
||||
<div class="error">
|
||||
❌ 请求失败: ${error.message}
|
||||
</div>
|
||||
`;
|
||||
resultContainer.style.display = 'block';
|
||||
} finally {
|
||||
generateBtn.disabled = false;
|
||||
loading.style.display = 'none';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
Reference in New Issue
Block a user