使用textract的AWS开始文档分析不起作用

时间:2020-07-14 14:48:14

标签: python amazon-web-services aws-lambda aws-textract

我正在为我的学校做一个项目,我应该使用textract在表单上进行文档分析,然后将输出运行到A2I,算法将确定该表单是已批准,拒绝还是需要审查。将文档上载到S3后,应触发此textract lambda函数。但是,当我遵循本文档时,我遇到语法错误。 https://docs.aws.amazon.com/textract/latest/dg/API_StartDocumentAnalysis.html

我的代码是:

import urllib.parse
import boto3

print('Loading function')

##Clients
s3 = boto3.client('s3')
textract = boto3.client('textract')

def analyzedata(bucketName,documentKey):
    print("Loading")
    AnalyzedData= textract.StartDocumentAnalysis("DocumentLocation": { 
      "S3Object": { 
         "Bucket": "bucketName",
         "Name": "documentKey",
      })
    detectedText = ''

    # Print detected text
    for item in AnalyzedData['Blocks']:
        if item['BlockType'] == 'LINE':
            detectedText += item['Text'] + '\n'
            
    return detectedText
      
def writeTextractToS3File(textractData, bucketName, createdS3Document):
    print('Loading writeTextractToS3File')
    generateFilePath = os.path.splitext(createdS3Document)[0] + '.csv'
    s3.put_object(Body=textractData, Bucket=bucketName, Key=generateFilePath)
    print('Generated ' + generateFilePath)





def lambda_handler(event, context):
    #print("Received event: " + json.dumps(event, indent=2))

    # Get the object from the event and show its content type
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
    try:
        detectedText = analyzedata(bucket, key)
        writeTextractToS3File(detectedText, bucket, key)
        
        return 'Processing Done!'
        
        
        
    except Exception as e:
        print(e)
        print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
        raise e

代码尚未完成,但是我已经收到语法错误:

  "errorMessage": "Syntax error in module 'lambda_function': invalid syntax (lambda_function.py, line 13)",
  "errorType": "Runtime.UserCodeSyntaxError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\" Line 13\n        AnalyzedData= textract.Start_Document_Analysis(\"DocumentLocation\": { \n"
  ]
}

3 个答案:

答案 0 :(得分:1)

根据boto3 docs,您的语法应更像:

AnalyzedData= textract.start_document_analysis(DocumentLocation={ 
  "S3Object": { 
     "Bucket": "bucketName",
     "Name": "documentKey",
  })

还要注意,FeatureTypes参数是按要求列出的。

答案 1 :(得分:0)

您应该尝试点安装awscli

pip install awscli

或pip3(如果效果更好)

然后导入并尝试运行代码。

答案 2 :(得分:0)

我认为您为此缺少起始花括号字符。

AnalyzedData= textract.StartDocumentAnalysis("DocumentLocation": { # missing { in this line
  "S3Object": { 
     "Bucket": "bucketName",
     "Name": "documentKey",
  })