test_local_openpose.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. import os
  2. import sys
  3. import time
  4. import base64
  5. import requests
  6. sys.path.append(os.path.join(os.path.dirname(__file__), '../tools/local/liblibai_controlnet'))
  7. from liblibai_client import LibLibAIClient
  8. TEMPLATE_UUID = "e10adc3949ba59abbe56e057f20f883e"
  9. DEFAULT_CHECKPOINT_ID = "0ea388c7eb854be3ba3c6f65aac6bfd3"
  10. # 这里填入您实际能用的 OpenPose SDXL 模型的 UUID
  11. OPENPOSE_MODEL_ID = "b6806516962f4e1599a93ac4483c3d23" # 注意:这里默认放的是Canny,请记得更换成 OpenPose UUID
  12. def get_base64_image(image_path):
  13. with open(image_path, "rb") as f:
  14. return "data:image/png;base64," + base64.b64encode(f.read()).decode("utf-8")
  15. def main():
  16. print("=" * 50)
  17. print("测试: 读取本地图片并自动上传 -> 使用 OpenPose 生成图片")
  18. print("=" * 50)
  19. client = LibLibAIClient()
  20. # 1. 读取本地图片并转换为 Base64
  21. local_image_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "features/pose_skeleton/img_1_openpose.png"))
  22. print(f"Reading local image: {local_image_path}")
  23. if not os.path.exists(local_image_path):
  24. print(f"Error: 找不到图片 {local_image_path}")
  25. sys.exit(1)
  26. base64_image = get_base64_image(local_image_path)
  27. # 2. 借助已经写好的 `upload_base64_image` 上传到 OSS
  28. print("Uploading Base64 to Liblib OSS...")
  29. image_url = client.upload_base64_image(base64_image)
  30. print(f"Uploaded successfully! Public URL: {image_url}")
  31. # 3. 发送任务
  32. payload = {
  33. "templateUuid": TEMPLATE_UUID,
  34. "generateParams": {
  35. "checkPointId": DEFAULT_CHECKPOINT_ID,
  36. "prompt": "1girl, highly detailed, masterpieces, beautiful face, standing pose",
  37. "negativePrompt": "lowres, bad anatomy",
  38. "sampler": 15,
  39. "steps": 20,
  40. "cfgScale": 7.0,
  41. "width": 512,
  42. "height": 512,
  43. "imgCount": 1,
  44. "controlNet": [{
  45. "unitOrder": 1,
  46. "sourceImage": image_url,
  47. "width": 512,
  48. "height": 512,
  49. "preprocessor": 14, # 14 = OpenPose Full
  50. "model": OPENPOSE_MODEL_ID, # !!需更换为OpenPose模型UUID
  51. "controlWeight": 1.0,
  52. "startingControlStep": 0.0,
  53. "endingControlStep": 1.0,
  54. "pixelPerfect": 1,
  55. "controlMode": 0,
  56. "annotationParameters": {
  57. "openposeFull": {
  58. "preprocessorResolution": 512
  59. }
  60. }
  61. }]
  62. }
  63. }
  64. auth_url = client.generate_auth_url("/api/generate/webui/text2img")
  65. print(f"Submitting OpenPose payload...")
  66. resp = requests.post(auth_url, json=payload, timeout=10)
  67. data = resp.json()
  68. if data.get("code") != 0:
  69. print(f"Submit task failed: {data.get('msg')} (code: {data.get('code')})")
  70. sys.exit(1)
  71. task_id = data["data"]["generateUuid"]
  72. print(f"Task submitted! Task ID: {task_id}")
  73. timeout = 300
  74. start_time = time.time()
  75. while time.time() - start_time < timeout:
  76. task_data = client.query_task_status(task_id)
  77. status = task_data.get("generateStatus")
  78. if status == 5:
  79. images = [img["imageUrl"] for img in task_data.get("images", [])]
  80. print(f"\n[SUCCESSS] Generated images: {images}")
  81. # --- 新增: 自动下载图片到 output 文件夹 ---
  82. output_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "output"))
  83. os.makedirs(output_dir, exist_ok=True)
  84. for i, img_url in enumerate(images):
  85. try:
  86. img_resp = requests.get(img_url)
  87. img_resp.raise_for_status()
  88. # 以时间戳作为文件名前缀防止覆盖
  89. timestamp = int(time.time())
  90. filename = f"openpose_result_{timestamp}_{i}.png"
  91. filepath = os.path.join(output_dir, filename)
  92. with open(filepath, "wb") as f:
  93. f.write(img_resp.content)
  94. print(f"[{i}] 已自动下载到本地: {filepath}")
  95. except Exception as e:
  96. print(f"[{i}] 图片自动下载失败: {e}")
  97. return
  98. elif status in [6, 7]:
  99. print("\n[FAILED] Task failed.")
  100. return
  101. print(".", end="", flush=True)
  102. time.sleep(5)
  103. print("\n[TIMEOUT]")
  104. if __name__ == "__main__":
  105. main()