forked from amazon-archives/amazon-polly-sample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
153 lines (130 loc) · 5.02 KB
/
lambda_function.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger("boto3").setLevel(logging.WARNING)
import boto3
import os
import feedparser
from boto3 import Session
from boto3 import resource
from botocore.exceptions import BotoCoreError, ClientError
from contextlib import closing
from HTMLParser import HTMLParser
from feedgen.feed import FeedGenerator
from bs4 import BeautifulSoup
import datetime
import dateutil.parser
import hashlib
MAX_TPS = 10
MAX_CONCURENT_CONNECTIONS = 20
TASKS = 100
REQUEST_LIMIT = 1200
# Specify the buckets
source_bucket = 'audiofiles-tts-incomingtexts-long'
destination_bucket = 'audiofiles-tts'
for record in event['Records']:
bucket_name = record['s3']['bucket']['name']
object_key = record['s3']['object']['key']
if bucket_name == source_bucket:
response = s3.get_object(Bucket=bucket_name, Key=object_key)
text_content = response['Body'].read().decode('utf-8')
# Start the speech synthesis task
synthesis_task = polly.start_speech_synthesis_task(
OutputFormat='mp3',
OutputS3BucketName=destination_bucket,
OutputS3KeyPrefix='longtxts/',
Text=text_content,
Engine = 'neural',
VoiceId='Emma'
)
task_id = synthesis_task['SynthesisTask']['TaskId']
def split_content_by_dot(soup, max_len):
"""
split HTML soup into parts not bigger than max_len may break prosody where
dot is not at the end of the sentence (like "St. Louis") in some cases may
be synthesized as two separate sentences
"""
text = soup.get_text(" ", strip=True)
start = 0
while start < len(text):
if len(text) - start <= max_len:
yield text[start:]
return
max = start + max_len
index = text.rfind(".", start, max)
if index == start:
start += 1
elif index < 0:
yield text[start:max]
start = max
else:
yield text[start:index]
start = index
def get_entries(feed):
NEW_POST = u"""New post, author {author}, title {title} {content}"""
for entry in feed.entries:
if "http" in entry.id:
nid = hashlib.md5(str(entry.id))
entry.id = nid.hexdigest()
entry_content = entry.content[0].value
soup = BeautifulSoup(entry_content, 'html.parser')
chunks = split_content_by_dot(soup, REQUEST_LIMIT-len(NEW_POST))
chunks = list(chunks)
published = dateutil.parser.parse(entry.published)
for i, chunk in enumerate(chunks):
if i == 0:
chunk = NEW_POST.format(
author=entry.author,
title=entry.title,
content=chunk)
yield dict(
content=chunk,
id="%s_%d" % (entry.id, i),
title=entry.title,
published=published - datetime.timedelta(0, i),
)
remaining = chunk
def lambda_handler(event, context):
rss = event['rss']
bucket_name = event['bucket']
logging.info("Processing url: %s" % rss)
logging.info("Using bucket: %s" % bucket_name)
session = Session(region_name="us-west-2")
polly = session.client("polly")
s3 = resource('s3')
bucket = s3.Bucket(bucket_name)
logging.info("getting list of existing objects in the given bucket")
files = set(o.key for o in bucket.objects.all())
feed = feedparser.parse(rss)
title = feed['feed']['title']
fg = FeedGenerator()
fg.load_extension('podcast')
fg.title('Audio podcast based on: %s' % title)
fg.link(href=feed.feed.link, rel='alternate')
fg.subtitle(feed.feed.description)
ENTRY_URL = "http://{bucket}.s3-website.{region}.amazonaws.com/{filename}"
for entry in get_entries(feed):
filename = "%s.mp3" % entry['id']
fe = fg.add_entry()
fe.id(entry['id'])
fe.title(entry['title'])
fe.published(entry['published'])
entry_url = ENTRY_URL.format(bucket=bucket_name, filename=filename, region=os.environ["AWS_REGION"])
fe.enclosure(entry_url, 0, 'audio/mpeg')
if filename in files:
logging.info('Article "%s" with id %s already exist, skipping.'
% (entry['title'], entry['id']))
continue
try:
logging.info("Next entry, size: %d" % len(entry['content']))
logging.debug("Content: %s" % entry['content'])
response = polly.synthesize_speech(
Text=entry['content'],
OutputFormat="mp3",
VoiceId="Joanna")
with closing(response["AudioStream"]) as stream:
bucket.put_object(Key=filename, Body=stream.read())
except BotoCoreError as error:
logging.error(error)
bucket.put_object(Key='podcast.xml', Body=fg.rss_str(pretty=True))