This repository has been archived by the owner on Jun 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 45
/
lambda_function.py
127 lines (111 loc) · 4.15 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
# -*- 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
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))