gpt4 book ai didi

aws-lambda - SpaCy 模型无法在 AWS Lambda 中加载

转载 作者:行者123 更新时间:2023-12-02 19:35:31 24 4
gpt4 key购买 nike

有人让 SpaCy 2.0 在 AWS Lambda 中工作吗?我已正确压缩和打包所有内容,因为如果我测试它,我可以从 lambda 函数返回一个通用字符串。但是当我执行下面的简单函数来测试时,它停滞了大约 10 秒,然后返回空,并且我没有收到任何错误消息。我确实将 Lambda 超时设置为 60 秒,所以这不是问题。

import spacy

nlp = spacy.load('en_core_web_sm') #model package included

def lambda_handler(event, context):
doc = nlp(u'They are')
msg = doc[0].lemma_
return msg

当我加载模型包而不使用它时,它也会返回空,但如果我将其注释掉,它会按预期向我发送字符串,因此它必须与加载模型有关。

import spacy

nlp = spacy.load('en_core_web_sm') #model package included

def lambda_handler(event, context):
msg = 'message returned'
return msg

最佳答案

要优化模型加载,您必须将其存储在 S3 上,并使用您自己的脚本将其下载到 lambda 中的 tmp 文件夹,然后将其加载到 spacy 中。

从 S3 下载并运行需要 5 秒。这里最好的优化是将模型保存在热容器中并检查它是否已经下载。在热容器上,代码运行需要 0.8 秒。

以下是代码和包的链接以及示例: https://github.com/ryfeus/lambda-packs/blob/master/Spacy/source2.7/index.py

import spacy
import boto3
import os


def download_dir(client, resource, dist, local='/tmp', bucket='s3bucket'):
paginator = client.get_paginator('list_objects')
for result in paginator.paginate(Bucket=bucket, Delimiter='/', Prefix=dist):
if result.get('CommonPrefixes') is not None:
for subdir in result.get('CommonPrefixes'):
download_dir(client, resource, subdir.get('Prefix'), local, bucket)
if result.get('Contents') is not None:
for file in result.get('Contents'):
if not os.path.exists(os.path.dirname(local + os.sep + file.get('Key'))):
os.makedirs(os.path.dirname(local + os.sep + file.get('Key')))
resource.meta.client.download_file(bucket, file.get('Key'), local + os.sep + file.get('Key'))

def handler(event, context):
client = boto3.client('s3')
resource = boto3.resource('s3')
if (os.path.isdir("/tmp/en_core_web_sm")==False):
download_dir(client, resource, 'en_core_web_sm', '/tmp','ryfeus-spacy')
spacy.util.set_data_path('/tmp')
nlp = spacy.load('/tmp/en_core_web_sm/en_core_web_sm-2.0.0')
doc = nlp(u'Apple is looking at buying U.K. startup for $1 billion')
for token in doc:
print(token.text, token.pos_, token.dep_)
return 'finished'

附注要将 spacy 打包到 AWS Lambda 中,您必须剥离共享库。

关于aws-lambda - SpaCy 模型无法在 AWS Lambda 中加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47879258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com