更换发型成功

This commit is contained in:
xsl
2026-01-18 22:10:48 +08:00
parent bf2d7d2bba
commit 11dd30eddf
8 changed files with 306 additions and 282 deletions
+105 -34
View File
@@ -2,6 +2,7 @@ from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import json
import os
import time
import requests
import base64
from io import BytesIO
@@ -15,29 +16,40 @@ CORS(app) # 启用CORS,允许跨域请求
# 加载发型数据
def load_hairstyles_from_file():
"""
从hair_res.txt文件加载发型数据
从hairId2url.txt文件加载发型数据
解析文件中的发型ID和URL对应关系
"""
hairstyles = []
try:
# 读取hair_res.txt文件
with open('../hair_res.txt', 'r', encoding='utf-8') as f:
# 读取hairId2url.txt文件
with open('../hairId2url.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
# 解析文件内容,提取图片URL
for i, line in enumerate(lines):
# 解析文件内容,提取发型ID和URL
for line in lines:
line = line.strip()
# 查找以https开头的行,这些是图片URL
if line.startswith('https://'):
# 生成发型ID和名称
hairstyle_id = f'hair_{i:03d}'
hairstyle_name = f'发型{i}'
# 添加到发型列表
hairstyles.append({
'id': hairstyle_id,
'name': hairstyle_name,
'image_url': line
})
# 查找包含 -> 分隔符的行,这些是发型ID和URL的映射
if '->' in line and '.jpg' in line:
# 分割行获取文件名和URL
parts = line.split('->')
if len(parts) == 2:
filename = parts[0].strip()
url = parts[1].strip()
# 提取发型ID(去掉.jpg后缀)
if filename.endswith('.jpg'):
hair_id = filename[:-4]
# 生成发型名称
hairstyle_name = f'发型{hair_id[-4:]}'
# 添加到发型列表
hairstyles.append({
'id': hair_id,
'name': hairstyle_name,
'image_url': url
})
except Exception as e:
print(f'加载发型数据失败: {str(e)}')
@@ -129,30 +141,89 @@ def allowed_file(filename):
def call_remote_api(image_data, hairstyle_id):
"""
调用远程API处理图片
注意:这里是模拟实现,实际项目中需要根据远程API的要求进行调整
根据test_hair.py的实现方式
"""
try:
# 构建请求数据
# 注意:这里需要根据远程API的实际要求调整请求格式
files = {'image': ('upload.jpg', BytesIO(image_data), 'image/jpeg')}
data = {'hairstyle_id': hairstyle_id}
# 将图片数据转换为base64格式
encoded_string = base64.b64encode(image_data).decode('utf-8')
img64_str = f"data:image/jpeg;base64,{encoded_string}"
# 构建请求数据(参考test_hair.py的格式)
data = {
"hair_id": hairstyle_id,
"task_id": f"task_{int(time.time())}", # 生成唯一的任务ID
"user_img_path": img64_str,
"is_hr": "false",
"output_format": "base64"
}
# 打印传入的参数(只打印部分信息,避免日志过长)
print("=== 调用远程API参数 ===")
print(f"hair_id: {hairstyle_id}")
print(f"task_id: {data['task_id']}")
print(f"is_hr: {data['is_hr']}")
print(f"output_format: {data['output_format']}")
print(f"user_img_path 长度: {len(img64_str)}")
print(f"user_img_path 前缀: {img64_str[:50]}...") # 只打印前缀
print("====================")
# 设置请求头(参考test_hair.py
headers = {'Content-Type': 'application/json'}
# 发送请求到远程API
# 注意:实际项目中需要替换为真实的远程API地址
# response = requests.post(
# app.config['REMOTE_API_URL'],
# files=files,
# data=data,
# timeout=app.config['API_TIMEOUT']
# )
print(f"发送请求到: {app.config['REMOTE_API_URL']}")
response = requests.post(
app.config['REMOTE_API_URL'],
headers=headers,
json=data,
timeout=app.config['API_TIMEOUT']
)
# 模拟远程API返回结果
# 这里简单返回原始图片数据作为模拟结果
# 实际项目中应该使用远程API的返回结果
return image_data
# 打印响应状态
print(f"响应状态码: {response.status_code}")
print(f"响应内容长度: {len(response.text)}")
# 只打印响应内容的前100个字符,避免base64数据过长
response_text = response.text
if len(response_text) > 100:
print(f"响应内容: {response_text[:100]}...")
else:
print(f"响应内容: {response_text}")
# 解析响应数据
response_data = response.json()
# 检查响应状态
if response.status_code != 200:
raise Exception(f"远程API返回错误: {response_data.get('msg', '未知错误')}")
# 参考test_hair.py的处理方式,直接检查是否有'data'字段
# 不再依赖'state'字段,因为远程API可能使用不同的成功标识
result_base64 = response_data.get('data', '')
# 检查是否有数据返回,即使有msg字段也不视为错误
# 因为远程API可能在成功时同时返回msg: "success"和data字段
if not result_base64:
# 如果没有'data'字段,检查是否有其他错误信息
error_msg = response_data.get('msg', '未知错误')
raise Exception(f"远程API返回错误: {error_msg}")
# 如果有数据返回,即使msg字段有值也视为成功
# 打印成功信息
success_msg = response_data.get('msg', '成功')
print(f"远程API调用成功: {success_msg}")
# 移除可能的前缀
if result_base64.startswith("data:image"):
result_base64 = result_base64.split(",", 1)[1]
# 解码base64数据为图片
result_image = base64.b64decode(result_base64)
print("远程API调用成功,返回处理后的图片")
return result_image
except Exception as e:
print(f'调用远程API失败: {str(e)}')
# 如果远程API调用失败,返回原始图片
# 实际项目中应该根据需要进行错误处理
return image_data
@app.route('/')