replace-charactor-ani.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import asyncio
  2. import aiohttp
  3. import base64
  4. import os
  5. import json
  6. import sys
  7. import io
  8. from aiohttp import ClientError, ServerDisconnectedError
  9. # 设置标准输出编码为 UTF-8,确保中文正确显示
  10. if sys.platform == 'win32':
  11. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
  12. sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
  13. print("图生图脚本启动...", flush=True)
  14. IMAGE_DIR = "LocalImage" # 固定参考图所在目录
  15. REFERENCE_FILES = ["image1.png", "image2.png"]
  16. PROMPT_TEXT = """Anelyze imaga 1, it contelins a sequence of anmgticn frames eanged in a gnid Return the resuit in .JSON formgt
  17. Creale a high-cuslily animale sore shaat based on the image?, nolce the weapan ae in al fames, nohce the charcer's sze shcuid be same inal iramesCRITICAL INSTRUCTIONSi The lbsyout, glid strucfure, and poses MUST EXACTLY malch the frst image (the lemplale surile shoel) need pure while background2 DO NOT STRETCH the sprites. Manitain the onginal interral aspect ratio of tha charecters.
  18. 3. if the ouiput aspect raho ($ftargetAspectRatoy, difers irom the templale, add pedding fempty space) raher than streiching the content4. Apply the charecter's appearance (colors, dothing, features) lo the poses in the template.S'prompt ? 'Addtional instructions: $iprompt’ ")"""
  19. async def main():
  20. # 检查 image1.png、image2.png 是否存在
  21. missing_files = []
  22. image_paths = []
  23. for file_name in REFERENCE_FILES:
  24. file_path = os.path.join(IMAGE_DIR, file_name)
  25. if os.path.isfile(file_path):
  26. image_paths.append(file_path)
  27. else:
  28. missing_files.append(file_name)
  29. if missing_files:
  30. missing = ", ".join(missing_files)
  31. expected = ", ".join(REFERENCE_FILES)
  32. print(f"错误: 找不到参考图 {missing}")
  33. print(f"请将 {expected} 放在 {IMAGE_DIR} 目录下")
  34. return
  35. # 读取并编码图片
  36. print(f"共找到 {len(image_paths)} 张参考图", flush=True)
  37. content = []
  38. for idx, image_path in enumerate(image_paths, start=1):
  39. print(f"[{idx}] 正在读取并编码: {image_path}", flush=True)
  40. with open(image_path, "rb") as img_file:
  41. image_data = base64.b64encode(img_file.read()).decode('utf-8')
  42. image_type = "png" # 固定为 PNG 格式
  43. content.append(
  44. {
  45. "type": "image_url",
  46. "image_url": {
  47. "url": f"data:image/{image_type};base64,{image_data}"
  48. }
  49. }
  50. )
  51. print("全部图片编码完成", flush=True)
  52. # 添加提示词
  53. content.append(
  54. {
  55. "type": "text",
  56. "text": PROMPT_TEXT
  57. }
  58. )
  59. try:
  60. # 设置超时和连接器配置
  61. timeout = aiohttp.ClientTimeout(total=300) # 总超时5分钟
  62. connector = aiohttp.TCPConnector(limit=10, limit_per_host=5)
  63. async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session:
  64. print("正在发送图生图请求...", flush=True)
  65. print("请求已发送,等待服务器响应...", flush=True)
  66. async with session.post(
  67. "https://api.chatanywhere.tech/v1/chat/completions",
  68. headers={
  69. "Authorization": "Bearer sk-j32LgDixK6pfESYGfJtgc2Tzlmszx5NZhSH0sOzpLQkYuKek",
  70. "Content-Type": "application/json",
  71. },
  72. json={
  73. "model": "gemini-3-pro-image-preview",
  74. "messages": [{"role": "user", "content": content}],
  75. },
  76. ) as resp:
  77. # 获取响应内容(无论成功或失败都保存)
  78. result = await resp.text()
  79. # 直接保存到 ImageToImage.txt
  80. with open("ImageToImage.txt", "w", encoding="utf-8") as f:
  81. f.write(result)
  82. # 检查响应状态
  83. if resp.status != 200:
  84. print(f"错误: 服务器返回状态码 {resp.status},错误信息已保存到 ImageToImage.txt", flush=True)
  85. return
  86. print("收到服务器响应,结果已保存到 ImageToImage.txt", flush=True)
  87. except asyncio.TimeoutError:
  88. print("错误: 请求超时", flush=True)
  89. except ServerDisconnectedError:
  90. print("错误: 服务器断开连接", flush=True)
  91. except ClientError as e:
  92. print(f"错误: 网络连接错误 - {str(e)}", flush=True)
  93. except Exception as e:
  94. print(f"错误: 发生未知错误 - {str(e)}", flush=True)
  95. print(f"错误类型: {type(e).__name__}", flush=True)
  96. asyncio.run(main())