154 lines
5.9 KiB
Python
154 lines
5.9 KiB
Python
import requests
|
||
import json
|
||
import logging
|
||
import time
|
||
import os
|
||
import base64
|
||
|
||
# 配置日志
|
||
logging.basicConfig(
|
||
level=logging.INFO,
|
||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||
)
|
||
logger = logging.getLogger("TestQWenImageEdit")
|
||
|
||
# API基础URL
|
||
base_url = "http://localhost:8200/api/qwenImage"
|
||
|
||
|
||
def test_get_config():
|
||
"""测试获取配置接口"""
|
||
try:
|
||
url = f"{base_url}/config"
|
||
logger.info(f"调用获取配置接口: {url}")
|
||
response = requests.get(url)
|
||
|
||
if response.status_code == 200:
|
||
result = response.json()
|
||
logger.info(f"获取配置成功: {json.dumps(result, ensure_ascii=False, indent=2)}")
|
||
return True, result
|
||
else:
|
||
logger.error(f"获取配置失败: HTTP状态码={response.status_code}, 响应内容={response.text}")
|
||
return False, None
|
||
except Exception as e:
|
||
logger.exception(f"获取配置时发生异常: {str(e)}")
|
||
return False, None
|
||
|
||
|
||
def get_test_image_base64(image_path=None):
|
||
"""获取测试图片的base64编码"""
|
||
try:
|
||
# 默认使用测试目录下的示例图片
|
||
if not image_path:
|
||
test_dir = os.path.dirname(os.path.abspath(__file__))
|
||
image_path = os.path.join(test_dir, "test_image.jpg")
|
||
|
||
# 如果默认图片不存在,创建一个简单的base64字符串
|
||
if not os.path.exists(image_path):
|
||
logger.warning(f"测试图片不存在,使用默认base64字符串: {image_path}")
|
||
return "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
|
||
|
||
# 读取图片文件并转换为base64
|
||
with open(image_path, "rb") as image_file:
|
||
return base64.b64encode(image_file.read()).decode('utf-8')
|
||
except Exception as e:
|
||
logger.exception(f"获取图片base64编码时发生异常: {str(e)}")
|
||
return "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
|
||
|
||
|
||
def test_edit_image(prompt, image_base64=None, size='1328*1328', save_local=True):
|
||
"""测试编辑图片接口(仅支持base64流式上传)"""
|
||
try:
|
||
url = f"{base_url}/edit"
|
||
headers = {"Content-Type": "application/json"}
|
||
|
||
# 如果未提供base64,使用默认测试图片
|
||
if not image_base64:
|
||
image_base64 = get_test_image_base64()
|
||
logger.info("使用默认测试图片base64数据")
|
||
|
||
data = {
|
||
"prompt": prompt,
|
||
"image_base64": image_base64,
|
||
"size": size,
|
||
"save_local": save_local
|
||
}
|
||
|
||
logger.info(f"调用编辑图片接口: {url}")
|
||
logger.info(f"请求参数: prompt={prompt[:50]}..., size={size}, save_local={save_local}")
|
||
|
||
# 记录开始时间
|
||
start_time = time.time()
|
||
|
||
# 发送请求
|
||
response = requests.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False))
|
||
|
||
# 计算耗时
|
||
elapsed_time = time.time() - start_time
|
||
logger.info(f"请求耗时: {elapsed_time:.2f}秒")
|
||
|
||
if response.status_code == 200:
|
||
result = response.json()
|
||
logger.info(f"编辑图片成功: {json.dumps(result, ensure_ascii=False, indent=2)}")
|
||
|
||
# 检查返回的数据
|
||
if result.get("code") == 200 and "data" in result:
|
||
images = result["data"].get("images", [])
|
||
logger.info(f"成功编辑{len(images)}张图片")
|
||
|
||
# 如果保存了本地文件,检查文件是否存在
|
||
if save_local and "local_file_paths" in result["data"]:
|
||
for file_path in result["data"]["local_file_paths"]:
|
||
full_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), file_path.lstrip('.'))
|
||
if os.path.exists(full_path):
|
||
logger.info(f"本地文件已保存: {full_path}")
|
||
else:
|
||
logger.warning(f"本地文件不存在: {full_path}")
|
||
|
||
return True, result
|
||
else:
|
||
logger.error(f"编辑图片失败: HTTP状态码={response.status_code}, 响应内容={response.text}")
|
||
return False, None
|
||
except Exception as e:
|
||
logger.exception(f"编辑图片时发生异常: {str(e)}")
|
||
return False, None
|
||
|
||
|
||
def main():
|
||
"""主函数,运行单元测试"""
|
||
logger.info("===== 开始测试QWenImage编辑接口 ====")
|
||
|
||
# 1. 测试获取配置接口
|
||
logger.info("\n1. 测试获取配置接口")
|
||
config_success, config_data = test_get_config()
|
||
|
||
# 2. 测试编辑图片接口 - 基本测试
|
||
logger.info("\n2. 测试编辑图片接口 - 基本测试")
|
||
basic_prompt = "将图片转换为水彩画风格,增加明亮度"
|
||
edit_success, edit_data = test_edit_image(
|
||
prompt=basic_prompt,
|
||
size="1328*1328",
|
||
save_local=True
|
||
)
|
||
|
||
# 3. 测试编辑图片接口 - 不同参数
|
||
if config_success:
|
||
supported_sizes = config_data["data"].get("supported_sizes", ["1328*1328"])
|
||
|
||
logger.info(f"\n3. 测试编辑图片接口 - 不同参数(size={supported_sizes[0]})")
|
||
different_prompt = "添加下雪效果,转为冷色调"
|
||
test_edit_image(
|
||
prompt=different_prompt,
|
||
size=supported_sizes[0],
|
||
save_local=True
|
||
)
|
||
|
||
logger.info("\n===== QWenImage编辑接口测试完成 =====")
|
||
|
||
# 输出测试结果摘要
|
||
success_count = sum([config_success, edit_success])
|
||
logger.info(f"测试结果: {success_count} 接口测试成功")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main() |