Files
hair_change_color/backend/app.py
T
2026-01-18 20:04:25 +08:00

174 lines
5.2 KiB
Python

from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import json
import os
import requests
import base64
from io import BytesIO
from config import Config
app = Flask(__name__)
app.config.from_object(Config)
CORS(app) # 启用CORS,允许跨域请求
# 加载发型数据
def load_hairstyles_from_file():
"""
从hair_res.txt文件加载发型数据
"""
hairstyles = []
try:
# 读取hair_res.txt文件
with open('../hair_res.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
# 解析文件内容,提取图片URL
for i, line in enumerate(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
})
except Exception as e:
print(f'加载发型数据失败: {str(e)}')
return hairstyles
# 加载发型数据
hairstyles_data = load_hairstyles_from_file()
@app.route('/api/hairstyles', methods=['GET'])
def get_hairstyles():
"""
获取发型列表
返回所有发型数据,不再区分男女
"""
try:
return jsonify({
'success': True,
'data': {
'hairstyles': hairstyles_data
}
})
except Exception as e:
return jsonify({
'success': False,
'message': f'获取发型列表失败: {str(e)}'
}), 500
@app.route('/api/change-hair', methods=['POST'])
def change_hair():
"""
更换发型
接收用户上传的图片和发型ID,调用远程API处理
"""
try:
# 检查是否有文件上传
if 'image' not in request.files:
return jsonify({
'success': False,
'message': '请上传图片'
}), 400
# 获取图片文件和发型ID
image_file = request.files['image']
hairstyle_id = request.form.get('hairstyle_id')
if not hairstyle_id:
return jsonify({
'success': False,
'message': '请选择发型'
}), 400
# 验证文件类型
if not allowed_file(image_file.filename):
return jsonify({
'success': False,
'message': '不支持的文件类型,请上传图片文件'
}), 400
# 读取图片数据
image_data = image_file.read()
# 调用远程API处理图片
# 注意:这里是模拟实现,实际项目中需要根据远程API的要求进行调整
result_image = call_remote_api(image_data, hairstyle_id)
# 将处理后的图片转换为base64格式返回
result_base64 = base64.b64encode(result_image).decode('utf-8')
result_data_url = f'data:image/jpeg;base64,{result_base64}'
return jsonify({
'success': True,
'data': {
'result_image': result_data_url
}
})
except Exception as e:
return jsonify({
'success': False,
'message': f'处理图片失败: {str(e)}'
}), 500
def allowed_file(filename):
"""
验证文件类型是否允许
"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
def call_remote_api(image_data, hairstyle_id):
"""
调用远程API处理图片
注意:这里是模拟实现,实际项目中需要根据远程API的要求进行调整
"""
try:
# 构建请求数据
# 注意:这里需要根据远程API的实际要求调整请求格式
files = {'image': ('upload.jpg', BytesIO(image_data), 'image/jpeg')}
data = {'hairstyle_id': hairstyle_id}
# 发送请求到远程API
# 注意:实际项目中需要替换为真实的远程API地址
# response = requests.post(
# app.config['REMOTE_API_URL'],
# files=files,
# data=data,
# timeout=app.config['API_TIMEOUT']
# )
# 模拟远程API返回结果
# 这里简单返回原始图片数据作为模拟结果
# 实际项目中应该使用远程API的返回结果
return image_data
except Exception as e:
# 如果远程API调用失败,返回原始图片
# 实际项目中应该根据需要进行错误处理
return image_data
@app.route('/')
def index():
"""
提供前端静态文件
开发环境下使用,生产环境应该使用Nginx等静态文件服务器
"""
return send_from_directory('../frontend', 'index.html')
@app.route('/<path:path>')
def send_static(path):
"""
提供前端静态文件
"""
return send_from_directory('../frontend', path)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)