This repository was archived by the owner on Nov 27, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
55 lines (42 loc) · 1.35 KB
/
Copy pathlambda_function.py
File metadata and controls
55 lines (42 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python
"""
pdf2txt on AWS Lambda
"""
from io import StringIO, BytesIO
from os import environ
import boto3
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
s3 = boto3.resource('s3')
PDF_BUCKET = environ['PDF_BUCKET']
TXT_BUCKET = environ['TXT_BUCKET']
def pdf2txt(pdf_obj):
"""
return pdf contents
"""
rsrcmgr = PDFResourceManager()
codec = "utf-8"
text = ""
with StringIO() as output:
device = TextConverter(rsrcmgr, output, codec=codec, laparams=LAParams())
with BytesIO(pdf_obj.read()) as inp:
interpreter = PDFPageInterpreter(rsrcmgr, device)
for page in PDFPage.get_pages(inp):
interpreter.process_page(page)
text += output.getvalue()
device.close()
return text
def lambda_handler(event, context):
"""
aws lambda handler endpoint
"""
print(event)
print(context)
s3_object_name = event["s3_object_name"]
pdf = s3.Object(PDF_BUCKET, s3_object_name).get()['Body']
txt = pdf2txt(pdf)
output_csv_filename = f'{s3_object_name}.txt'
s3.Object(TXT_BUCKET, output_csv_filename).put(Body = txt)
return ({"filename": f'{output_csv_filename}', "content": txt})