forked from veganhacktivists/animalsupportbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
brain.py
414 lines (356 loc) · 15.3 KB
/
brain.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import argparse
import os
from pprint import pprint
import re
import string
from collections import OrderedDict
import pandas as pd
import praw
import prawcore
import spacy
from praw.models import Comment, Submission
from tinydb import Query, TinyDB
import validators
import yaml
from argmatcher import ArgMatcher
from response_templates import END_TEMPLATE, FAILURE_COMMENT, FAILURE_PM
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--limit",
help="Maximum number of mentions to check (default=-1, unlimited)",
type=int,
default=-1,
)
parser.add_argument(
"--config",
help="Config file path (default: ./config.yaml)",
type=str,
default="./config.yaml",
)
parser.add_argument(
"--log-db",
help="Log db path (default: ./lob_db.json",
type=str,
default="./log_db.json",
)
args = parser.parse_args()
if args.limit <= 0:
args.limit = None
assert os.path.isfile(args.config)
assert os.path.isfile(args.log_db)
return args
def load_config_yaml(file):
with open(file) as fp:
config = yaml.safe_load(fp)
return config
def load_myth_links(file):
df = pd.read_csv(file)
df = df.fillna("")
return OrderedDict(
{k: v for k, v in zip(df["Title"].values, df["Link"].values) if v}
)
class BrainBot:
def __init__(
self,
argmatch,
config,
db,
):
self.config = config
self.reddit = praw.Reddit(check_for_async=False, **config["user_info"])
self.inbox = praw.models.Inbox(self.reddit, _data={})
self.argmatch = argmatch
## Config/Thresholds for standard matching
self.n_neighbors = int(config["n_neighbors"])
self.threshold = float(config["threshold"])
self.certain_threshold = float(config["certain_threshold"])
## Config/Thresholds for matching with a hint
self.hint_n_neighbors = int(config["hint_n_neighbors"])
self.hint_arg_threshold = float(config["hint_arg_threshold"])
self.hint_threshold = float(config["hint_threshold"])
self.hint_certain_threshold = float(config["hint_certain_threshold"])
self.whitelisted_subreddits = set(config["whitelisted"])
self.blacklisted_subreddits = set(["suicidewatch", "depression"]).union(
set(config["blacklisted"])
)
self.whitelisted_subreddits = set(
[s.lower() for s in self.whitelisted_subreddits]
)
self.blacklisted_subreddits = set(
[s.lower() for s in self.blacklisted_subreddits]
)
self.db = db
self.replied = self.fill_replied(self.db)
self.alphabet = string.ascii_letters
self.END_TEMPLATE = END_TEMPLATE
self.FAILURE_COMMENT = FAILURE_COMMENT
self.FAILURE_PM = FAILURE_PM
def fill_replied(self, db):
"""
Returns a list of all parent and mention ids found in the log DB
"""
replied = set()
for entry in db.all():
replied.add(entry["mention_id"])
if "parent_id" in entry:
replied.add(entry["parent_id"])
return replied
def clear_already_replied(self):
"""
Go through mentions manually to tick off if we have already replied
"""
for mention in self.inbox.mentions(limit=None):
if mention.id not in self.replied:
if isinstance(mention, Comment):
parent = mention.parent()
reply_info = {
"mention_id": mention.id,
"mention_username": mention.author.name
if mention.author
else None,
"mention_text": mention.body,
"mention_date": mention.created_utc,
"subreddit": mention.subreddit.display_name.lower(),
"parent_id": parent.id,
"parent_username": parent.author.name
if parent.author
else None,
"outcome": "Already replied, but not found in DB",
}
if isinstance(parent, Comment):
parent.refresh()
replies = parent.replies.list()
elif isinstance(parent, Submission):
replies = parent.comments.list()
else:
replies = None
if replies:
reply_authors = [r.author for r in replies]
if "animalsupportbot" in reply_authors:
self.replied.add(mention.id)
self.replied.add(parent.id)
self.db.insert(reply_info)
def format_response(self, resps):
"""
Formatting responses given from the argument matcher
"""
args = OrderedDict({})
for r in resps:
inp = r["input_sentence"]
arg = r["matched_argument"]
passage = r["reply_text"]
sim = r["similarity"]
link = r["link"]
if arg not in args:
args[arg] = {
"passage": passage,
"quotes": [inp],
"sim": sim,
"link": link,
}
else:
args[arg]["quotes"].append(inp)
if args[arg]["sim"] < sim:
# replace the passage if this sentence is better matched
args[arg]["sim"] = sim
args[arg]["passage"] = passage
replies = []
for i, arg in enumerate(args):
parts = []
quotes = "".join(
[">{} \n\n".format(q) for q in args[arg]["quotes"]]
) + "> ^(({})^) \n\n".format(self.alphabet[i])
passage = args[arg]["passage"]
if i < len(args) - 1:
# Only add dividers between args
passage += "\n\n --- \n\n"
parts.append(quotes)
parts.append(passage)
arglist = "({}): {}".format(self.alphabet[i], arg)
link = args[arg]["link"]
if validators.url(link):
arglist = "[({}): {}]({})".format(self.alphabet[i], arg, link)
parts.append(self.END_TEMPLATE.format(arglist))
replies.append("\n".join(parts))
return replies
def reply_mentions(self, limit=None):
"""
Main functionality. Go through mentions and reply to parent comments
Uses persentence argmatcher
"""
for mention in self.inbox.mentions(limit=limit):
reply_info = {
"mention_id": mention.id,
"mention_username": mention.author.name if mention.author else None,
"mention_text": mention.body,
"mention_date": mention.created_utc,
"subreddit": mention.subreddit.display_name.lower(),
}
# Skip mention if not in whitelisted subreddits
if (
mention.subreddit.display_name.lower()
not in self.whitelisted_subreddits
):
reply_info[
"outcome"
] = "Mention not in whitelisted subreddit: {}".format(
mention.subreddit.display_name.lower()
)
self.replied.add(mention.id)
self.db.insert(reply_info)
continue
# Skip mention if included in blacklisted subreddits
# TODO: currently irrelevant as whitelist exists, enable this if whitelist is not enabled
if mention.subreddit.display_name.lower() in self.blacklisted_subreddits:
reply_info["outcome"] = "Blacklisted Subreddit"
self.replied.add(mention.id)
self.db.insert(reply_info)
continue
# Proceed if mention has not been dealt with
if mention.id not in self.replied:
if isinstance(mention, Comment):
parent = mention.parent()
reply_info["parent_id"] = parent.id
reply_info["parent_username"] = (
parent.author.name if parent.author else None
)
# Check if parent has been handled (in case of multiple mentions)
if parent.id in self.replied:
reply_info["outcome"] = "Parent already replied to"
self.replied.add(mention.id)
self.db.insert(reply_info)
continue
try:
if isinstance(parent, Comment):
input_text = self.remove_usernames(parent.body)
elif isinstance(parent, Submission):
input_text = self.remove_usernames(
".".join([parent.title, parent.selftext])
)
else:
input_text = None
except:
input_text = None
reply_info["input_text"] = input_text
if input_text:
input_text = self.replace_newlines(input_text)
mention_hints = self.remove_usernames(mention.body).replace(
",", "."
)
resps = self.argmatch.match_text(
input_text,
threshold=self.threshold,
certain_threshold=self.certain_threshold,
N_neighbors=self.n_neighbors,
)
if mention_hints:
# Use mention hints to match arguments
reply_info["mention_hints"] = mention_hints
# This step looks at the mention hint, and gets the arglabels hinted
# Hint arg threshold is low since we expect hint to be obvious
# TODO: look into matching only with argument titles
hint_resps = self.argmatch.match_text(
mention_hints,
threshold=self.hint_arg_threshold,
certain_threshold=0.9, # Irrelevant as N_neighbors=1
N_neighbors=1,
return_reply=False,
)
reply_info["hint_responses"] = hint_resps
arg_labels = set(
[r["matched_arglabel"] for r in hint_resps]
)
r_arg_labels = set([r["matched_arglabel"] for r in resps])
# Check only the hinted args which aren't matched already
arg_labels = arg_labels - r_arg_labels
if arg_labels:
# Pass arg_labels to match_text, restricting to hinted args
hinted_resps = self.argmatch.match_text(
input_text,
arg_labels=arg_labels,
threshold=self.hint_threshold,
certain_threshold=self.hint_certain_threshold,
N_neighbors=self.hint_n_neighbors,
)
# Adds remaining responses to hinted ones
# Skips if matched to a hinted arg
oldresps = resps
resps = hinted_resps
hinted_sents = [
r["input_sentence"] for r in hinted_resps
]
for r in oldresps:
if r["input_sentence"] in hinted_sents:
# This means the sentence was matched up to a hint
continue
else:
resps.append(r)
else:
resps = []
reply_info["responses"] = resps
if resps: # Found arg match(es)
formatted_responses = self.format_response(resps)
reply_info["full_reply"] = formatted_responses
for response in formatted_responses:
try:
reply = parent.reply(response)
reply_info[
"outcome"
] = "Replied with matched argument(s)"
reply_info["reply_id"] = reply.id
except prawcore.exceptions.Forbidden:
reply_info[
"outcome"
] = "Found arguments but failed to reply: Forbidden"
else: # Failed to find arg match
mention.reply(self.FAILURE_COMMENT)
try:
mention.author.message(
"We couldn't find a response!",
self.FAILURE_PM.format(
self.argmatch.prefilter(parent.body)
),
)
except:
# PM-ing people sometimes fails, but this is not critical
pass
reply_info["outcome"] = "Failed to find any matched arguments"
# Add both the mention and the parent to the replied list
self.replied.add(mention.id)
self.replied.add(parent.id)
self.db.insert(reply_info)
def run_once(self, limit=None):
"""
Run the bot once, checking all new mentions
"""
self.reply_mentions(limit=limit)
print("Successfully checked and/or replied to mentions, exiting brain...")
@staticmethod
def remove_usernames(text):
"""
Removes any /u/username or u/username strings
"""
newtext = re.sub("\/u\/[A-Za-z0-9_-]+", "", text)
newtext = re.sub("u\/[A-Za-z0-9_-]+", "", newtext)
return newtext
@staticmethod
def replace_newlines(text):
"""
Replaces newline symbols with periods
"""
return text.replace("\n", ". ")
if __name__ == "__main__":
args = parse_args()
config = load_config_yaml(args.config)
nlp = spacy.load("en_core_web_lg")
nlp.add_pipe("universal_sentence_encoder", config={"model_name": "en_use_lg"})
db = TinyDB(args.log_db)
argm = ArgMatcher(nlp, None, None, preload=True)
mb = BrainBot(
argm,
config,
db,
)
mb.run_once(limit=args.limit)
db.close()