build_lambdas.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env python3
  2. """打包 Lambda 函数为 zip,跨平台 (Windows/Linux/Mac)。"""
  3. import os
  4. import sys
  5. import shutil
  6. import zipfile
  7. import subprocess
  8. SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
  9. LAMBDAS_DIR = os.path.join(SCRIPT_DIR, '..', 'lambdas')
  10. LAMBDAS_DIR = os.path.normpath(LAMBDAS_DIR)
  11. FUNCTIONS = ['submit', 'download', 'transcribe_start', 'transcribe_check', 'summarize', 'notify']
  12. def build_layer():
  13. """打包 Lambda Layer (requests + pycryptodome)"""
  14. print("Building Lambda layer...")
  15. layer_dir = os.path.join(LAMBDAS_DIR, 'layer_build', 'python')
  16. layer_zip = os.path.join(LAMBDAS_DIR, 'layer.zip')
  17. if os.path.exists(os.path.join(LAMBDAS_DIR, 'layer_build')):
  18. shutil.rmtree(os.path.join(LAMBDAS_DIR, 'layer_build'))
  19. os.makedirs(layer_dir)
  20. # 全部指定 Linux 平台安装,确保 native 包兼容 Lambda
  21. subprocess.check_call([
  22. sys.executable, '-m', 'pip', 'install',
  23. 'requests', 'pycryptodome', 'openai', 'tiktoken',
  24. '--platform', 'manylinux2014_x86_64',
  25. '--implementation', 'cp',
  26. '--python-version', '3.12',
  27. '--only-binary=:all:',
  28. '-t', layer_dir, '-q',
  29. ])
  30. with zipfile.ZipFile(layer_zip, 'w', zipfile.ZIP_DEFLATED) as zf:
  31. for root, dirs, files in os.walk(os.path.join(LAMBDAS_DIR, 'layer_build')):
  32. for f in files:
  33. full = os.path.join(root, f)
  34. arcname = os.path.relpath(full, os.path.join(LAMBDAS_DIR, 'layer_build'))
  35. zf.write(full, arcname)
  36. shutil.rmtree(os.path.join(LAMBDAS_DIR, 'layer_build'))
  37. size = os.path.getsize(layer_zip) / 1024 / 1024
  38. print(f" layer.zip ({size:.1f} MB)")
  39. def build_function(name):
  40. """打包单个 Lambda 函数"""
  41. zip_path = os.path.join(LAMBDAS_DIR, f'{name}.zip')
  42. with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
  43. zf.write(os.path.join(LAMBDAS_DIR, f'{name}.py'), f'{name}.py')
  44. zf.write(os.path.join(LAMBDAS_DIR, 'shared.py'), 'shared.py')
  45. size = os.path.getsize(zip_path) / 1024
  46. print(f" {name}.zip ({size:.1f} KB)")
  47. def main():
  48. print(f"Lambda 目录: {LAMBDAS_DIR}\n")
  49. build_layer()
  50. print()
  51. for fn in FUNCTIONS:
  52. build_function(fn)
  53. print("\n完成!")
  54. if __name__ == '__main__':
  55. main()