test_generate.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import os
  2. import sys
  3. import base64
  4. import re
  5. import requests
  6. from pathlib import Path
  7. from dotenv import load_dotenv
  8. load_dotenv()
  9. # 添加父目录到路径
  10. sys.path.insert(0, str(Path(__file__).parent.parent))
  11. from openai import OpenAI
  12. api_key = os.getenv("APIYI_KEY")
  13. if not api_key:
  14. raise ValueError("APIYI_KEY environment variable is required")
  15. client = OpenAI(
  16. api_key=api_key,
  17. base_url="https://api.apiyi.com/v1"
  18. )
  19. def extract_url_from_markdown(text):
  20. """从 markdown 格式中提取 URL"""
  21. # 匹配 ![image](url) 格式
  22. match = re.search(r'!\[.*?\]\((https?://[^\)]+)\)', text)
  23. if match:
  24. return match.group(1)
  25. # 如果不是 markdown 格式,直接返回
  26. return text.strip()
  27. def test_generate_image():
  28. print("Testing GPT Image 2 generation with gpt-image-2-all model...")
  29. # 使用 chat/completions 接口
  30. response = client.chat.completions.create(
  31. model="gpt-image-2-all",
  32. messages=[
  33. {"role": "user", "content": "1024x1024 square image, a cute cat sitting on a sunny windowsill"}
  34. ],
  35. extra_body={"response_format": {"type": "url"}}
  36. )
  37. assert response.choices and len(response.choices) > 0, "No response returned"
  38. content = response.choices[0].message.content
  39. assert content, "Empty content"
  40. # 提取真实的 URL
  41. image_url = extract_url_from_markdown(content)
  42. print(f"[SUCCESS] Image generated successfully!")
  43. print(f" Raw content: {content}")
  44. print(f" Image URL: {image_url}")
  45. # 下载图像保存到本地
  46. output_dir = Path(__file__).parent / "output"
  47. output_dir.mkdir(exist_ok=True)
  48. img_response = requests.get(image_url, timeout=30)
  49. output_path = output_dir / "test_cat.png"
  50. output_path.write_bytes(img_response.content)
  51. print(f" Saved to: {output_path}")
  52. print(f" File size: {len(img_response.content)} bytes")
  53. return True
  54. if __name__ == "__main__":
  55. test_generate_image()