test_jimeng.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. """Jimeng AI Tool Test Script"""
  2. import asyncio
  3. import sys
  4. import os
  5. # Add parent directory to path
  6. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  7. from jimeng_client import JimengClient
  8. async def test_text2image():
  9. """Test text-to-image functionality"""
  10. print("\n=== Testing Text-to-Image ===")
  11. client = JimengClient(
  12. api_key=os.getenv("JIMENG_API_KEY"),
  13. cookie=os.getenv("JIMENG_COOKIE"),
  14. base_url=os.getenv("JIMENG_BASE_URL", "https://api.jimeng.ai")
  15. )
  16. try:
  17. # Submit text-to-image task
  18. result = await client.text2image(
  19. prompt="A cute cat playing in the garden",
  20. negative_prompt="blurry, low quality",
  21. aspect_ratio="1:1",
  22. image_count=1,
  23. cfg_scale=7.0,
  24. steps=20,
  25. seed=-1
  26. )
  27. print(f"Task ID: {result['task_id']}")
  28. print(f"Status: {result['status']}")
  29. print(f"Estimated time: {result.get('estimated_time', 'N/A')} seconds")
  30. if result['status'] == 'failed':
  31. print(f"Error: {result.get('error')}")
  32. return False
  33. # Simulate query task status
  34. print("\nQuerying task status...")
  35. status = await client.query_status(result['task_id'])
  36. print(f"Current status: {status['status']}")
  37. print(f"Progress: {status.get('progress', 0)}%")
  38. return True
  39. except Exception as e:
  40. print(f"Test failed: {str(e)}")
  41. import traceback
  42. traceback.print_exc()
  43. return False
  44. finally:
  45. await client.close()
  46. async def test_image2video():
  47. """Test image-to-video functionality"""
  48. print("\n=== Testing Image-to-Video ===")
  49. client = JimengClient(
  50. api_key=os.getenv("JIMENG_API_KEY"),
  51. cookie=os.getenv("JIMENG_COOKIE"),
  52. base_url=os.getenv("JIMENG_BASE_URL", "https://api.jimeng.ai")
  53. )
  54. try:
  55. # Use test image URL
  56. test_image_url = "https://example.com/test.jpg"
  57. result = await client.image2video(
  58. image_url=test_image_url,
  59. prompt="Make the image move",
  60. video_duration=5,
  61. motion_strength=0.5,
  62. seed=-1
  63. )
  64. print(f"Task ID: {result['task_id']}")
  65. print(f"Status: {result['status']}")
  66. print(f"Estimated time: {result.get('estimated_time', 'N/A')} seconds")
  67. if result['status'] == 'failed':
  68. print(f"Error: {result.get('error')}")
  69. # This is expected since we're using a test URL
  70. return True
  71. return True
  72. except Exception as e:
  73. print(f"Test failed: {str(e)}")
  74. import traceback
  75. traceback.print_exc()
  76. return False
  77. finally:
  78. await client.close()
  79. async def test_cache():
  80. """Test cache functionality"""
  81. print("\n=== Testing Cache ===")
  82. client = JimengClient()
  83. try:
  84. # Test cache set and get
  85. test_data = {
  86. "task_id": "test_123",
  87. "status": "completed",
  88. "result": {"images": ["test.jpg"]}
  89. }
  90. client.cache.set("test_123", test_data)
  91. cached = client.cache.get("test_123")
  92. if cached and cached["task_id"] == "test_123":
  93. print("OK: Cache set and get working")
  94. else:
  95. print("FAIL: Cache not working")
  96. return False
  97. # Test cache cleanup
  98. client.cleanup_cache()
  99. print("OK: Cache cleanup working")
  100. return True
  101. except Exception as e:
  102. print(f"Test failed: {str(e)}")
  103. import traceback
  104. traceback.print_exc()
  105. return False
  106. finally:
  107. await client.close()
  108. async def main():
  109. """Run all tests"""
  110. print("=" * 50)
  111. print("Jimeng AI Tool Tests")
  112. print("=" * 50)
  113. results = []
  114. # Test cache (doesn't need API key)
  115. results.append(("Cache", await test_cache()))
  116. # Check if API key is configured
  117. if not os.getenv("JIMENG_API_KEY") and not os.getenv("JIMENG_COOKIE"):
  118. print("\nWARNING: JIMENG_API_KEY or JIMENG_COOKIE not configured")
  119. print("Skipping API tests. Configure credentials in .env for full testing")
  120. else:
  121. # Test text-to-image
  122. results.append(("Text2Image", await test_text2image()))
  123. # Test image-to-video
  124. results.append(("Image2Video", await test_image2video()))
  125. # Output test results
  126. print("\n" + "=" * 50)
  127. print("Test Results Summary")
  128. print("=" * 50)
  129. for name, success in results:
  130. status = "PASS" if success else "FAIL"
  131. print(f"{name}: {status}")
  132. all_passed = all(success for _, success in results)
  133. print("\nOverall:", "ALL TESTS PASSED" if all_passed else "SOME TESTS FAILED")
  134. return all_passed
  135. if __name__ == "__main__":
  136. success = asyncio.run(main())
  137. sys.exit(0 if success else 1)