upload.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import asyncio
  2. import os
  3. import sys
  4. import httpx
  5. from cyber_sdk.ali_oss import upload_localfile
  6. async def upload_image(local_file_path: str, bucket_name: str = 'aigc-admin', bucket_path: str = 'template') -> str:
  7. """Uploads a local image to OSS and returns the CDN URL."""
  8. print(f"Uploading {local_file_path} to {bucket_name}/{bucket_path}...")
  9. # Use forward slashes so cyber_sdk's .split('/') can correctly extract filename on Windows
  10. safe_path = os.path.abspath(local_file_path).replace("\\", "/")
  11. result = await upload_localfile(
  12. file_path=safe_path,
  13. bucket_path=bucket_path,
  14. bucket_name=bucket_name
  15. )
  16. print("Upload SDK Response:", result)
  17. oss_object_key = result.get('oss_object_key')
  18. if oss_object_key:
  19. cdn_url = f"https://res.cybertogether.net/{oss_object_key}"
  20. return cdn_url
  21. return None
  22. async def download_image(url: str, save_path: str):
  23. """Downloads an image from an HTTP link and saves it locally."""
  24. print(f"Downloading from {url} to {save_path}...")
  25. async with httpx.AsyncClient(timeout=30.0) as client:
  26. resp = await client.get(url)
  27. resp.raise_for_status()
  28. with open(save_path, 'wb') as f:
  29. f.write(resp.content)
  30. print(f"Download completed: {save_path}")
  31. async def main():
  32. if len(sys.argv) < 2:
  33. print("Usage:")
  34. print(" Upload: python upload.py <file_path>")
  35. print(" Download: python upload.py download <url> <save_path>")
  36. # Self-test block if no param is given
  37. print("\n--- Running Self Test ---")
  38. test_file = 'img_1_gen.png'
  39. if not os.path.exists(test_file):
  40. print(f"Creating a dummy 1x1 PNG at {test_file} for testing.")
  41. with open(test_file, 'wb') as f:
  42. f.write(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82')
  43. url = await upload_image(test_file, 'aigc-admin', 'crawler/image')
  44. print(f"\nExtracted URL: {url}")
  45. if url:
  46. # Download it back
  47. download_path = "downloaded_dummy.png"
  48. await download_image(url, download_path)
  49. elif sys.argv[1] == 'download':
  50. if len(sys.argv) >= 4:
  51. await download_image(sys.argv[2], sys.argv[3])
  52. else:
  53. print("Error: Missing parameters for download.")
  54. print("Usage: python upload.py download <url> <save_path>")
  55. else:
  56. # Upload context
  57. file_path = sys.argv[1]
  58. url = await upload_image(file_path, 'aigc-admin', 'crawler/image')
  59. print(f"\nFinal CDN URL: {url}")
  60. if __name__ == '__main__':
  61. asyncio.run(main())