aws-samples / amazon-textract-enhancer

This workshop demonstrates how to build a Document parser and query engine with Amazon Textract and other services, such as ElasticSearch and DynamoDB.
MIT No Attribution
66 stars 34 forks source link

S3 Event sends URL encoded key names, causing Lambda handler to fail on Textract API calls #2

Open matwerber1 opened 5 years ago

matwerber1 commented 5 years ago

Hi,

Per S3 docs:

The s3 key provides information about the bucket and object involved in the event. The object key name value is URL encoded. For example, "red flower.jpg" becomes "red+flower.jpg" (Amazon S3 returns "application/x-www-form-urlencoded" as the content type in the response).

The current extract-Enhancer-TextractAsyncJobSubmitFunction Lambda does not URL decode the S3 key received in the event JSON, so I'm receiving errors when trying to parse objects that contain spaces or other URL-encoding relevant characters.

For example, If I upload a document named my test.pdf, the S3 event sent to the extract-Enhancer-TextractAsyncJobSubmitFunction function contains the key Records[0].s3.object.key = my+test.pdf.

The Textract API calls textract.start_document_analysis() and textract.start_document_text_detection() then fail because the DocumentLocation parameter has a value of my+test.pdf when it should instead be my test.pdf.

Can you add URL decoding to the S3 key name in the received events?

matwerber1 commented 5 years ago

Tested the following addition:

from urllib.parse import unquote_plus
...
document = unquote_plus(record['s3']['object']['key'])

That worked fine but ran into a new issue...

The JobTag and ClientRequestToken parameters of textract.start_document_text_detection() do not allow spaces or plusses (though they do allow dashes).

Maybe the S3 object's MD5 should instead be used as the value of ClientRequestToken?

Not sure about JobTag... haven't looked at rest of code yet, not sure if JobTag matters?

matwerber1 commented 5 years ago

Created this PR to address the issue: #3