-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_helpers.py
443 lines (399 loc) · 16.5 KB
/
db_helpers.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
"""
Helper functions to interface with DB so we don't have to use pgadmin...
"""
import os
import sys
import time
from collections import defaultdict
from pprint import pprint, pformat
import datetime
from queryset_helpers import (
list_common_features,
list_stack_specific_features,
list_reddit_specific_features
)
import pytz
def show_missing_errors():
"""one off script"""
counter = defaultdict(int)
qs = ErrorLog.objects.all().values()
for obj in qs:
if not (
SampledRedditThread.objects.filter(uid=obj['uid']).exists() or
SampledStackOverflowPost.objects.filter(uid=obj['uid']).exists()):
counter[obj['msg']] += 1
try:
dic = SampledStackOverflowPost.objects.filter(id=obj['uid']).values()[0]
print(obj)
except:
pass
print('enter to continue')
input()
print(counter)
print(len(qs))
def clear_json2db():
"""Delete entries populated by the json2db script"""
for model in [
RedditPost, StackOverflowAnswer, StackOverflowQuestion, StackOverflowUser
]:
qs = model.objects.all()
print('Going to delete {} entries from model {}'.format(qs.count(), model))
print('Enter y to continue')
if input() == 'y':
qs.delete()
def reset_revision_info():
"""Reset"""
for model in [SampledRedditThread, SampledStackOverflowPost]:
model.objects.filter(all_revisions_pulled=True).update(
has_wiki_link=False,
wiki_content_error=0,
num_wiki_links=0,
day_of_avg_score=None,
week_after_avg_score=None,
all_revisions_pulled=False,
)
WikiLink.objects.all().delete()
Revision.objects.all().delete()
ErrorLog.objects.all().delete()
def show_samples():
"""Show samples of all posts"""
from queryset_helpers import (
list_common_features,
list_reddit_specific_features, list_stack_specific_features
)
out = []
for model in [SampledRedditThread, SampledStackOverflowPost]:
if model == SampledRedditThread:
feats = list_common_features() + list_reddit_specific_features()
else:
feats = list_common_features() + list_stack_specific_features() + ['is_top', 'num_other_answers']
feats = ['title', 'body'] + feats
samples1 = model.objects.filter(has_wiki_link=False).order_by('?')[:5]
samples2 = model.objects.filter(has_wiki_link=True).order_by('?')[:5]
for index, samples in enumerate([samples1, samples2]):
if index == 0:
x = 'No WP link'
else:
x = 'Has WP link'
for sample in samples:
out.append(model.__name__ + ' ' + x)
for feat in feats:
out.append('{}, {}'.format(feat, getattr(sample, feat)))
out.append(str(sample.__dict__))
out.append('===\n')
with open('show_samples.txt', 'w') as outfile:
outfile.write('\n'.join(out))
def bulk_save():
"""Runs through all the rows and re-saves to trigger
computation"""
reddit = SampledRedditThread.objects.all().order_by('uid')
stack = SampledStackOverflowPost.objects.all().order_by('uid')
start_time = time.time()
for start, end, total, batch in batch_qs(reddit, batch_size=10000):
print('reddit', start, end, total, time.time() - start_time)
for item in batch:
item.save()
start = time.time()
for start, end, total, batch in batch_qs(stack, batch_size=10000):
print('stack', start, end, total, time.time() - start_time)
for item in batch:
item.save()
def bulk_save_rev():
for obj in Revision.objects.all():
obj.save()
qs = Revision.objects.filter(user_retained_180=True)
print(qs.count())
def save_links_and_posts():
"""
Runs through all the rows and re-saves to trigger
computation
"""
save_links()
save_posts()
def save_links():
print('saving links... (slow)')
for link in WikiLink.objects.all():
link.save()
def save_posts(sample_num=None):
"""
Re compute Wiki link rows
"""
print('saving posts... (slow)')
if sample_num is None:
sample_num = [0,1,2]
else:
sample_num = sample_num.split(',')
sample_num = [int(x) for x in sample_num]
reddit = SampledRedditThread.objects.filter(has_wiki_link=True, sample_num__in=sample_num).order_by('uid')
for start, end, total, batch in batch_qs(reddit):
print('reddit', start, end, total)
for item in batch:
item.save()
stack = SampledStackOverflowPost.objects.filter(has_wiki_link=True, sample_num__in=sample_num).order_by('uid')
for start, end, total, batch in batch_qs(stack):
print('stack', start, end, total)
for item in batch:
item.save()
def sample_articles():
"""Prints out a sample of URLs to text file"""
num_samples = 10
models = [
SampledRedditThread,
SampledStackOverflowPost]
for model in models:
qs = model.objects.filter(has_wiki_link=True).order_by('?')[:num_samples]
counter = 0
for obj in qs:
for wiki_link in obj.wiki_links.all():
outfilename = 'html/{}_sample{}of{}.html'.format(
model.__name__, counter, num_samples
)
counter += 1
if model == SampledRedditThread:
fields = [
obj.title, obj.context, str(obj.timestamp), wiki_link.title
]
else:
body = obj.body
body_as_list = body.split('<a')
final_body = 'Answered posted on: ' + str(obj.timestamp) + '\n'
for component in body_as_list:
if 'wikipedia.org/wiki/' in component:
final_body += '***'
final_body += '<a' + component
final_body = final_body[:-2]
fields = [final_body]
line = ', '.join(fields)
with open(outfilename, 'w') as outfile:
outfile.write(line + '\n')
if model == SampledStackOverflowPost:
break # don't need to repeat for all links
def extract_pairs(first, second):
filename = 'pair_{}_{}'.format(first, second)
try:
treated = SampledRedditThread.objects.get(uid=first)
control = SampledRedditThread.objects.get(uid=second)
url_template = 'https://www.reddit.com/by_id/t3_{}'
features = list_common_features() + list_reddit_specific_features()
except Exception:
treated = SampledStackOverflowPost.objects.get(uid=first)
control = SampledStackOverflowPost.objects.get(uid=second)
url_template = 'https://stackoverflow.com/questions/{}'
features = list_common_features() + list_stack_specific_features()
treated_vals_string = '|'.join(['{}:{}'.format(
feature, getattr(treated, feature)) for feature in features
])
control_vals_string = '|'.join(['{}:{}'.format(
feature, getattr(control, feature)) for feature in features
])
treated_output = 'Treatment\n{}\n{}\n'.format(
url_template.format(first),
treated_vals_string
)
control_output = 'Control\n{}\n{}\n'.format(
url_template.format(second),
control_vals_string
)
with open(filename, 'w') as outfile:
outfile.write(treated_output)
outfile.write(control_output)
def mark_top_answers():
"""marks top answers"""
qs = SampledStackOverflowPost.objects.all().order_by('uid')
for start, end, total, batch in batch_qs(qs, batch_size=10000):
print(start, end, total)
for answer in batch:
try:
question_id = StackOverflowAnswer.objects.using('secondary').filter(id=answer.uid).values('parent_id')[0]['parent_id']
other_answers = StackOverflowAnswer.objects.using('secondary').filter(parent_id=question_id)
max_score = other_answers.aggregate(Max('score'))['score__max']
print(max_score)
if answer.score == max_score:
print('marking top answer as true woohoo!')
answer.is_top = True
answer.save()
except Exception as err:
print(err)
print('MISSING QUESTION UH OH')
def print_link_titles_and_redirects():
links = WikiLink.objects.all().order_by('?')[:10]
for link in links:
print(link.url)
print(link.title)
print(link.alt_title)
def check_dupe_wikilinks():
from portal.models import SampledRedditThread
from portal.models import SampledStackOverflowPost
cache = {}
qs_r = SampledRedditThread.objects.filter(has_wiki_link=True)
qs_s = SampledStackOverflowPost.objects.filter(has_wiki_link=True)
count = 0
for obj in qs_r:
has_err = False
links = obj.wiki_links.all()
for link in links:
matching_links = WikiLink.objects.filter(title=link.title)
for matching_link in matching_links:
matching_reddit_posts = SampledRedditThread.objects.filter(wiki_links=matching_link)
matching_so_posts = SampledRedditThread.objects.filter(wiki_links=matching_link)
for matching_qs in [matching_reddit_posts, matching_so_posts]:
for post in matching_qs:
if post.uid == obj.uid:
continue
elif post.uid in cache:
continue
else:
cache[post.uid] = True
dt = obj.timestamp - post.timestamp
val = abs(dt.total_seconds())
if val < 1.21e6: # 14 days
has_err = True
before = post.num_edits, post.num_edits_prev_week
post.save()
after = post.num_edits, post.num_edits_prev_week
if after[0] - before[0] != 0 or after[1] - before[1] != 0:
print(before, after)
count += 1
if has_err:
obj.save()
cache[obj.uid] = True
print(count)
WIK = 'wikipedia.org/wiki/'
def print_potential_wikilinks():
from url_helpers import extract_urls
import csv
qs_r = SampledRedditThread.objects.filter(
url__icontains=WIK, has_wiki_link=False, sample_num__in=[0,1,2])
qs_s = SampledStackOverflowPost.objects.filter(
body__icontains=WIK, has_wiki_link=False, sample_num__in=[0,1,2])
url_list = []
for index, qs in enumerate([qs_r, qs_s]):
print('===')
print(len(qs))
for post in qs:
urls = extract_urls(post.body, WIK) if index == 1 else [post.url]
for url in urls:
if 'File:' in url or 'File%3a' in url or 'File%3A' in url:
continue
if 'www.google' in url:
continue
else:
print(url)
url_list.append(url)
print(len(url_list))
with open('url_list.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
for url in url_list:
writer.writerow([url])
nonen = SampledRedditThread.objects.filter(has_wiki_link=True).exclude(url__icontains='en.wikipedia').exclude(url__icontains='en.m.wikipedia').exclude(url__icontains='www.wikipedia').exclude(url__icontains='//wikipedia').values_list('url', 'num_edits', 'num_edits_prev_week')
with open('nonen_reddit_list.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
for line in nonen:
writer.writerow(line)
qs_r = SampledRedditThread.objects.filter(
has_wiki_link=True, day_of_avg_score__isnull=True, sample_num__in=[0,1,2])
qs_s = SampledStackOverflowPost.objects.filter(
has_wiki_link=True, day_of_avg_score__isnull=True, sample_num__in=[0,1,2])
reddit_has_link_but_no_ores = []
so_has_link_but_no_ores = []
errs = defaultdict(int)
counts = {
'reddit': defaultdict(int),
'so': defaultdict(int)
}
for post in qs_r:
url = [','.join(
[post.url, str(post.missing_ores_during_two_weeks), str(post.missing_ores_on_old_revisions), str(post.no_revisions), str(post.missing_ores_error_code)])]
if post.missing_ores_during_two_weeks:
counts['reddit']['missing_ores_during_two_weeks'] += 1
if post.missing_ores_on_old_revisions:
counts['reddit']['missing_ores_on_old_revisions'] += 1
if post.no_revisions:
counts['reddit']['no_revisions'] += 1
if post.wiki_content_error == 0:
reddit_has_link_but_no_ores.append(url)
else:
errs[post.wiki_content_error] += 1
for post in qs_s:
urls = extract_urls(post.body, WIK)
urls = [','.join(
[str(urls), str(post.missing_ores_during_two_weeks), str(post.missing_ores_on_old_revisions), str(post.no_revisions), str(post.missing_ores_error_code)])]
if post.missing_ores_during_two_weeks:
counts['so']['missing_ores_during_two_weeks'] += 1
if post.missing_ores_on_old_revisions:
counts['so']['missing_ores_on_old_revisions'] += 1
if post.no_revisions:
counts['so']['no_revisions'] += 1
if post.wiki_content_error == 0:
so_has_link_but_no_ores.append(urls)
else:
errs[post.wiki_content_error] += 1
with open('reddit_has_link_but_no_ores.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
writer.writerows(reddit_has_link_but_no_ores)
with open('so_has_link_but_no_ores.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
writer.writerows(so_has_link_but_no_ores)
print(errs)
print(counts)
def clean_then_delete():
ErrorLog.objects.delete()
def check_on_revisions():
no_users = Revision.objects.filter(user__isnull=True)
print('There are {} revs with null user field'.format(len(no_users)))
print(no_users[:5])
no_timestamps = Revision.objects.filter(timestamp__isnull=True)
print('There are {} revs with null timestamp field'.format(len(no_timestamps)))
print(no_timestamps[:5])
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dja.settings")
import django
django.setup()
from django.db.models import Max
from portal.models import (
ErrorLog, SampledRedditThread,
SampledStackOverflowPost,
WikiLink, Revision,
RedditPost, StackOverflowAnswer, StackOverflowQuestion, StackOverflowUser,
)
from queryset_helpers import batch_qs
if len(sys.argv) > 1:
if sys.argv[1] == 'reset_revision_info':
reset_revision_info()
elif sys.argv[1] == 'show_samples':
show_samples()
elif sys.argv[1] == 'bulk_save':
bulk_save()
elif sys.argv[1] == 'bulk_save_rev':
bulk_save_rev()
elif sys.argv[1] == 'save_links':
save_links()
elif sys.argv[1] == 'save_links_and_posts':
save_links_and_posts()
elif sys.argv[1] == 'save_posts':
try:
save_posts(sys.argv[2])
except:
save_posts()
elif sys.argv[1] == 'clear_json2db':
clear_json2db()
elif sys.argv[1] == 'show_missing_errors':
show_missing_errors()
elif sys.argv[1] == 'sample_articles':
sample_articles()
elif sys.argv[1] == 'extract_pairs':
extract_pairs(sys.argv[2], sys.argv[3])
elif sys.argv[1] == 'mark_top_answers':
mark_top_answers()
elif sys.argv[1] == 'quick_helper':
quick_helper()
elif sys.argv[1] == 'check_dupe_wikilinks':
check_dupe_wikilinks()
elif sys.argv[1] == 'clear_pre2016_so_pageviews':
clear_pre2016_so_pageviews()
elif sys.argv[1] == 'print_potential_wikilinks':
print_potential_wikilinks()
elif sys.argv[1] == 'clean_then_delete':
clean_then_delete()
elif sys.argv[1] == 'check_on_revisions':
check_on_revisions()