ai_swap_example.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. """
  2. AI换脸换装服务使用示例
  3. 展示如何使用AISwapService进行换脸换装操作
  4. """
  5. import os
  6. import sys
  7. import time
  8. from datetime import datetime
  9. # 添加项目根目录到Python路径
  10. sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
  11. from backend.services.ai_swap_service import AISwapService, process_swap_with_record
  12. from backend.modules.database.operations import DatabaseOperations
  13. from backend.utils.logger_config import setup_logger
  14. logger = setup_logger(__name__)
  15. def create_test_user():
  16. """创建测试用户"""
  17. db_ops = DatabaseOperations()
  18. # 检查用户是否已存在
  19. existing_user = db_ops.get_user_by_username("test_user")
  20. if existing_user:
  21. logger.info(f"测试用户已存在: {existing_user['id']}")
  22. return existing_user["id"]
  23. # 创建新用户
  24. user = db_ops.create_user(
  25. username="test_user",
  26. password_hash="test_password_hash",
  27. is_admin=False
  28. )
  29. logger.info(f"创建测试用户成功: {user['id']}")
  30. return user["id"]
  31. def create_test_images(user_id: int):
  32. """创建测试图片记录"""
  33. db_ops = DatabaseOperations()
  34. # 检查是否已有测试图片
  35. existing_images = db_ops.get_user_images(user_id, page_size=10)
  36. if existing_images["total"] >= 2:
  37. logger.info("测试图片已存在")
  38. face_images = [img for img in existing_images["images"] if img["image_type"] == "face"]
  39. cloth_images = [img for img in existing_images["images"] if img["image_type"] == "cloth"]
  40. if face_images and cloth_images:
  41. return face_images[0]["id"], cloth_images[0]["id"]
  42. # 创建测试图片记录(这里只是创建记录,实际文件需要手动上传)
  43. # 在实际项目中,你需要先上传图片文件,然后创建记录
  44. # 模拟图片路径
  45. test_face_path = "backend/data/face.png"
  46. test_cloth_path = "backend/data/cloth.png"
  47. if not os.path.exists(test_face_path) or not os.path.exists(test_cloth_path):
  48. logger.warning("测试图片文件不存在,请先准备测试图片")
  49. return None, None
  50. # 创建人脸图片记录
  51. face_record = db_ops.create_image_record(
  52. user_id=user_id,
  53. image_type="face",
  54. original_filename="test_face.png",
  55. stored_path=test_face_path,
  56. file_size=os.path.getsize(test_face_path)
  57. )
  58. # 创建服装图片记录
  59. cloth_record = db_ops.create_image_record(
  60. user_id=user_id,
  61. image_type="cloth",
  62. original_filename="test_cloth.png",
  63. stored_path=test_cloth_path,
  64. file_size=os.path.getsize(test_cloth_path)
  65. )
  66. logger.info(f"创建测试图片记录成功: 人脸={face_record['id']}, 服装={cloth_record['id']}")
  67. return face_record["id"], cloth_record["id"]
  68. def test_ai_swap_service():
  69. """测试AI换脸换装服务"""
  70. logger.info("开始测试AI换脸换装服务")
  71. try:
  72. # 1. 创建测试用户
  73. user_id = create_test_user()
  74. # 2. 创建测试图片记录
  75. face_image_id, cloth_image_id = create_test_images(user_id)
  76. if not face_image_id or not cloth_image_id:
  77. logger.error("无法获取测试图片,测试终止")
  78. return
  79. # 3. 创建服务实例
  80. ai_swap_service = AISwapService()
  81. # 4. 执行换脸换装
  82. logger.info("开始执行换脸换装...")
  83. start_time = time.time()
  84. result = ai_swap_service.process_swap_with_record(
  85. user_id=user_id,
  86. face_image_id=face_image_id,
  87. cloth_image_id=cloth_image_id,
  88. prompt="美女站在海边,阳光明媚,穿着时尚的连衣裙"
  89. )
  90. end_time = time.time()
  91. processing_time = end_time - start_time
  92. # 5. 输出结果
  93. if result["success"]:
  94. logger.info("✅ 换脸换装成功!")
  95. logger.info(f"处理时间: {processing_time:.2f}秒")
  96. logger.info(f"处理记录ID: {result['process_record_id']}")
  97. logger.info(f"结果图片ID: {result['result_image_id']}")
  98. logger.info(f"生成的文案: {result['copywriter_text']}")
  99. logger.info(f"历史提示词: {result['history_prompt']}")
  100. # 6. 查询历史记录
  101. logger.info("\n查询处理历史...")
  102. history = ai_swap_service.get_user_process_history(user_id, page=1, page_size=5)
  103. logger.info(f"用户共有 {history['total']} 条处理记录")
  104. # 7. 查询处理详情
  105. if history["records"]:
  106. latest_record = history["records"][0]
  107. detail = ai_swap_service.get_process_detail(latest_record["id"])
  108. if detail:
  109. logger.info(f"最新处理详情: 记录ID={detail['process_record']['id']}")
  110. logger.info(f"人脸图片: {detail['face_image']['original_filename']}")
  111. logger.info(f"服装图片: {detail['cloth_image']['original_filename']}")
  112. logger.info(f"结果图片: {detail['result_image']['original_filename']}")
  113. else:
  114. logger.error("❌ 换脸换装失败!")
  115. logger.error(f"错误信息: {result['error']}")
  116. logger.error(f"错误类型: {result['error_type']}")
  117. except Exception as e:
  118. logger.error(f"测试过程中发生异常: {str(e)}", exc_info=True)
  119. def test_convenience_function():
  120. """测试便捷函数"""
  121. logger.info("开始测试便捷函数")
  122. try:
  123. # 使用便捷函数
  124. result = process_swap_with_record(
  125. user_id=1,
  126. face_image_id=1,
  127. cloth_image_id=2,
  128. prompt="美女在花园里拍照"
  129. )
  130. if result["success"]:
  131. logger.info("✅ 便捷函数测试成功!")
  132. logger.info(f"结果: {result}")
  133. else:
  134. logger.error("❌ 便捷函数测试失败!")
  135. logger.error(f"错误: {result['error']}")
  136. except Exception as e:
  137. logger.error(f"便捷函数测试异常: {str(e)}", exc_info=True)
  138. def test_error_handling():
  139. """测试错误处理"""
  140. logger.info("开始测试错误处理")
  141. ai_swap_service = AISwapService()
  142. # 测试无效用户ID
  143. try:
  144. result = ai_swap_service.process_swap_with_record(
  145. user_id=99999, # 不存在的用户ID
  146. face_image_id=1,
  147. cloth_image_id=2,
  148. prompt="测试"
  149. )
  150. logger.info(f"无效用户ID测试结果: {result}")
  151. except Exception as e:
  152. logger.info(f"无效用户ID测试异常: {str(e)}")
  153. # 测试无效图片ID
  154. try:
  155. result = ai_swap_service.process_swap_with_record(
  156. user_id=1,
  157. face_image_id=99999, # 不存在的图片ID
  158. cloth_image_id=2,
  159. prompt="测试"
  160. )
  161. logger.info(f"无效图片ID测试结果: {result}")
  162. except Exception as e:
  163. logger.info(f"无效图片ID测试异常: {str(e)}")
  164. # 测试空提示词
  165. try:
  166. result = ai_swap_service.process_swap_with_record(
  167. user_id=1,
  168. face_image_id=1,
  169. cloth_image_id=2,
  170. prompt="" # 空提示词
  171. )
  172. logger.info(f"空提示词测试结果: {result}")
  173. except Exception as e:
  174. logger.info(f"空提示词测试异常: {str(e)}")
  175. def main():
  176. """主函数"""
  177. logger.info("=" * 50)
  178. logger.info("AI换脸换装服务测试开始")
  179. logger.info("=" * 50)
  180. # 1. 测试错误处理
  181. test_error_handling()
  182. # 2. 测试便捷函数
  183. test_convenience_function()
  184. # 3. 测试完整服务
  185. test_ai_swap_service()
  186. logger.info("=" * 50)
  187. logger.info("AI换脸换装服务测试完成")
  188. logger.info("=" * 50)
  189. if __name__ == "__main__":
  190. main()