-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvcl_script-multiprocessing-c2.py
224 lines (186 loc) · 9.73 KB
/
vcl_script-multiprocessing-c2.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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import boto3, base64, datetime
import json, time
from textblob import TextBlob
from multiprocessing import Process
from AWS_CREDS import *
def consumer(shard_id):
kinesis = boto3.client('kinesis',
region_name = AWS_REGION_NAME,
aws_access_key_id = AWS_ACCESS_KEY_ID,
aws_secret_access_key = AWS_SECRET_ACCESS_KEY)
# Shard iterator
shard_it = kinesis.get_shard_iterator(StreamName=AWS_STREAM_NAME, ShardId=shard_id, \
ShardIteratorType="LATEST")["ShardIterator"]
# ----------- DATA KEYS --------------------------
KEY_TITLE = 'title'
KEY_NUM_COMMENTS = 'nc'
KEY_SCORE = 'score'
KEY_TYPE = 'type'
KEY_DATA = 'Data'
# ----------- STREAM TYPES ------------------------
REDDIT = 'reddit'
MEETUP = 'meetup'
TWITTER = 'twitter'
# These lamdas only put data into the 'live' table.
TWITTER_LIVE_TABLE_NAME = 'live_twitter_dic8'
REDDIT_LIVE_TABLE_NAME = 'live_reddit_dic8'
MEETUPS_TABLE_NAME = 'meetups_dic8'
# -------------- HEADER NAMES IN TABLES ------------
# ---------- TWITTER TABLE -------------
TWITTER_TABLE_REPLIES_HEADER = 'replies'
TWITTER_TABLE_FAVORITES_HEADER = 'favorites'
TWITTER_TABLE_RETWEETS_HEADER = 'retweets'
# ---------- REDDIT TABLE --------------
REDDIT_TABLE_SCORE_HEADER = 'score'
REDDIT_TABLE_NUM_COMMENTS_HEADER = 'num_comments'
# ---------- MEETUPS TABLE -------------
MEETUPS_LOCATION_CITY_KEY_HEADER = 'key_location_city'
MEETUPS_LOCATION_STATE_KEY_HEADER = 'key_location_state'
MEETUPS_LOCATION_COUNTRY_KEY_HEADER = 'key_location_country'
MEETUPS_TABLE_CATEGORY_HEADER = 'key_category'
MEETUPS_TABLE_VENUE_HEADER = 'venue'
MEETUPS_TABLE_NAME_HEADER = 'name'
# ---------- COMMON HEADERS ------------
TIME_HEADER = 'key_datetime'
KEYWORD_HEADER = 'key_word'
dynamodb = boto3.resource('dynamodb',
aws_access_key_id = AWS_ACCESS_KEY_ID,
aws_secret_access_key = AWS_SECRET_ACCESS_KEY,
region_name = DYNAMO_DB_REGION_NAME)
def extract_keywords(sentence):
"""
Extracts Noun Phrases. Has an external dependency on textblob.
"""
keywords = []
blob = TextBlob(sentence)
for np in blob.noun_phrases:
keywords.append(np)
return keywords
def getTimeKey():
return datetime.datetime.now().strftime("%Y-%m-%d-%H-%M")
def updateFieldInTable(table, fieldName, fieldValue, timeKey, keywords):
# print keywords
for keyword in keywords:
table.update_item(
Key = {
TIME_HEADER: timeKey,
KEYWORD_HEADER: keyword
},
UpdateExpression="set " + fieldName + " = if_not_exists(" + fieldName + ", :init) + :val",
ExpressionAttributeValues={
':val': fieldValue,
':init': 0
}
)
# print 'Key=' + {
# TIME_HEADER: timeKey,
# KEYWORD_HEADER: keyword
# }
# print 'UpdateExpression: ' + "set " + fieldName + " = " + fieldName + decimal.Decimal(fieldValue)
try:
while True:
try:
out = kinesis.get_records(ShardIterator=shard_it)
for o in out["Records"]:
data = json.loads(o["Data"])
# Work with data here.
timeKey = getTimeKey()
# print data
if data[KEY_TYPE] == REDDIT:
# Find keywords from the title.
title = data['title']
keywords = extract_keywords(title)
# Extract score and number of comments.
score = data['score']
num_comments = data['num_comments']
# print keywords
# Put these into Dynamo
table = dynamodb.Table(REDDIT_LIVE_TABLE_NAME)
updateFieldInTable(table, REDDIT_TABLE_NUM_COMMENTS_HEADER, num_comments, timeKey, keywords)
updateFieldInTable(table, REDDIT_TABLE_SCORE_HEADER, score, timeKey, keywords)
elif data[KEY_TYPE] == MEETUP:
# Find keywords from the name.
event_name = data['name']
keywords = extract_keywords(event_name)
if 'description' in data:
keywords += extract_keywords(data['description'])
# Extract venue
# NOTE: May not be present
venue = "None"
state = "None"
if 'venue' in data:
city = data['venue']['city']
country = data['venue']['country']
if 'state' in data['venue']:
state = data['venue']['state']
venue = data['venue']['name']
if 'address_1' in data['venue']:
venue += data['venue']['address_1']
if 'address_2' in data['venue']:
venue += data['venue']['address_2']
if 'address_3' in data['venue']:
venue += data['venue']['address_3']
else:
city = data['group']['city']
country = data['group']['country']
if 'state' in data['group']:
state = data['group']['state']
if 'group' in data and 'category' in data['group']['category'] and 'shortname' in data['group']['category']['shortname']:
# Extract category
event_category = data['group']['category']['shortname']
else:
event_category = 'None'
# Put these into Dynamo
table = dynamodb.Table(MEETUPS_TABLE_NAME)
for keyword in keywords:
table.put_item(
Item={
TIME_HEADER: timeKey, # Part of key. To filter on time.
KEYWORD_HEADER: keyword, # Part of key.
MEETUPS_LOCATION_CITY_KEY_HEADER: city, # Part of key. To filter on geography.
MEETUPS_LOCATION_STATE_KEY_HEADER: state, # Part of key. To filter on geography.
MEETUPS_LOCATION_COUNTRY_KEY_HEADER: country, # Part of key. To filter on geography.
MEETUPS_TABLE_CATEGORY_HEADER: event_category, # Part of key. To allow searching for popular meetups according to category.
MEETUPS_TABLE_NAME_HEADER: event_name, # Could be part of key. Will allow searching for particular events and find where they are popular.
MEETUPS_TABLE_VENUE_HEADER: venue # Could be part of key. Will allow searching for popular events at a venue.
}
)
elif data[KEY_TYPE] == TWITTER:
# Find keywords from the title.
if 'text' in data:
title = data['text']
keywords = extract_keywords(title)
# Extract number of retweets, favorites, and replies.
retweets = data['retweet_count']
favorites = data['favorite_count']
replies = data['reply_count']
# Put these into Dynamo.
table = dynamodb.Table(TWITTER_LIVE_TABLE_NAME)
updateFieldInTable(table, TWITTER_TABLE_RETWEETS_HEADER, retweets, timeKey, keywords)
updateFieldInTable(table, TWITTER_TABLE_FAVORITES_HEADER, favorites, timeKey, keywords)
updateFieldInTable(table, TWITTER_TABLE_REPLIES_HEADER, replies, timeKey, keywords)
else:
print ("Invalid data type!")
shard_it = out["NextShardIterator"]
except KeyError as e:
pass
# Try without sleep
time.sleep(1)
except KeyboardInterrupt:
pass
except:
consumer(shard_id)
if __name__ == '__main__':
# Spawn process for each shard.
kinesis = boto3.client('kinesis',
region_name = AWS_REGION_NAME,
aws_access_key_id = AWS_ACCESS_KEY_ID,
aws_secret_access_key = AWS_SECRET_ACCESS_KEY)
consumer_processes = []
shardIds = ['shardId-0000000000021', 'shardId-0000000000022', 'shardId-0000000000023']
for shardId in shardIds:
consumer_processes.append(Process(target=consumer, args=(shardId,)))
for consumer_process in consumer_processes:
consumer_process.start()
for consumer_process in consumer_processes:
consumer_process.join()