25-6-2-云计算lambda代码
本文最后由方少年更新于2025 年 11 月 10 日,已超过20天没有更新。如果文章内容或图片资源失效,请留言反馈,将会及时处理,谢谢!
```
import boto3
import os
import base64
import pymysql
import requests
import traceback
from PIL import Image
import mimetypes
s3 = boto3.client('s3')
# 环境变量
GEMINI_API_KEY = os.environ['GEMINI_API_KEY']
DB_HOST = os.environ['DB_HOST']
DB_USER = os.environ['DB_USER']
DB_PASSWORD = os.environ['DB_PASSWORD']
DB_NAME = os.environ['DB_NAME']
def lambda_handler(event, context):
try:
bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
filename = os.path.basename(key)
if key.startswith('thumbnails/'):
print("🟡 Skipping thumbnail:", key)
return {'statusCode': 200, 'body': 'Skip thumbnail'}
tmp_file = f"/tmp/{filename}"
thumb_file = f"/tmp/thumb-{filename}"
thumb_key = f"thumbnails/{filename}"
# 下载原始图片
print("🟡 Downloading original image...")
s3.download_file(bucket, key, tmp_file)
print(f"✅ Downloaded to {tmp_file}")
# 生成缩略图
try:
with Image.open(tmp_file) as img:
img.thumbnail((128, 128))
img.save(thumb_file)
print("✅ Thumbnail created")
s3.upload_file(thumb_file, bucket, thumb_key)
print(f"✅ Thumbnail uploaded to s3://{bucket}/{thumb_key}")
except Exception as e:
print("❌ Thumbnail creation failed:", str(e))
# 获取 MIME 类型
mime_type, _ = mimetypes.guess_type(tmp_file)
if not mime_type:
mime_type = 'image/jpeg'
# 编码为 base64
with open(tmp_file, "rb") as img_file:
img_b64 = base64.b64encode(img_file.read()).decode('utf-8')
# 调用 Gemini
print("🟡 Calling Gemini API...")
gemini_url = (
f"https://generativelanguage.googleapis.com/v1/models/"
f"gemini-1.5-flash:generateContent?key={GEMINI_API_KEY}"
)
response = requests.post(
gemini_url,
headers={"Content-Type": "application/json"},
json={
"contents": [{
"parts": [
{"text": "Describe this image in one sentence."},
{"inline_data": {
"mime_type": mime_type,
"data": img_b64
}}
]
}]
},
timeout=10 # 避免卡死
)
result = response.json()
print("✅ Gemini response:", result)
if 'candidates' in result:
annotation = result['candidates'][0]['content']['parts'][0]['text']
else:
annotation = "Annotation failed"
print("❌ Gemini response missing 'candidates'. Error:", result)
print(f"📝 Annotation: {annotation}")
# 写入 MySQL
s3_url = f"https://{bucket}.s3.amazonaws.com/{key}"
try:
print("🟡 Connecting to MySQL...")
conn = pymysql.connect(
host=DB_HOST,
user=DB_USER,
password=DB_PASSWORD,
database=DB_NAME,
connect_timeout=5 # 防止长时间卡死
)
print("✅ Connected to MySQL")
with conn.cursor() as cursor:
thumbnail_url = f"https://{bucket}.s3.amazonaws.com/{thumb_key}"
sql = """
INSERT INTO images (filename, s3_url, thumbnail_url, annotation)
VALUES (%s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
thumbnail_url = VALUES(thumbnail_url),
annotation = VALUES(annotation)
"""
cursor.execute(sql, (filename, s3_url, thumbnail_url, annotation))
print(f"✅ MySQL executed. Rows affected: {cursor.rowcount}")
conn.commit()
conn.close()
print("✅ MySQL connection closed")
except Exception as db_err:
print("❌ Database error!")
traceback.print_exc()
return {
'statusCode': 200,
'body': f'Annotation added: {annotation}'
}
except Exception as e:
print("❌ Lambda error occurred:")
traceback.print_exc()
return {
'statusCode': 500,
'body': f'Error occurred: {str(e)}'
}
```
文章标题:25-6-2-云计算lambda代码
文章链接:https://www.fangshaonian.cn/archives/77/
最后编辑:2025 年 11 月 10 日 18:31 By 方少年
许可协议: 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)