-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvital_signs.py
1682 lines (1105 loc) · 67.4 KB
/
vital_signs.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# script
import wikilanguages_utils
from wikilanguages_utils import *
# time
import time
import datetime
from dateutil import relativedelta
import calendar
# system
import os
import sys
import shutil
import re
import random
import operator
# databases
import sqlite3
# files
import gzip
import zipfile
import bz2
import json
import csv
import codecs
# requests and others
import urllib
import webbrowser
import numpy as np
# data
import pandas as pd
import gc
# https://stats.wikimedia.org/#/all-projects
# https://meta.wikimedia.org/wiki/List_of_Wikipedias/ca
# https://meta.wikimedia.org/wiki/Research:Metrics#Volume_of_contribution
# https://meta.wikimedia.org/wiki/Research:Wikistats_metrics/Act
vital_signs_editors_db = 'vital_signs_editors.db'
vital_signs_web_db = 'vital_signs_web.db'
# MAIN
def main():
# EDITORS
create_vital_signs_editors_db()
for languagecode in wikilanguagecodes_plusmeta:
print ('*')
print (languagecode)
editor_metrics_dump_iterator(languagecode) # it fills the database cawiki_editors, cawiki_editor_metrics
print ('dump iterator done.\n')
editor_metrics_db_iterator(languagecode)
print (languagecode+" done")
print (wikilanguagecodes_plusmeta)
print ('*')
editor_metrics_primary_language_calculation()
# VITAL SIGNS
for languagecode in wikilanguagecodes_plusmeta:
vital_signs_db_iterator(languagecode) # it fills the database cawiki_vital_signs_metrics
print (languagecode)
print ('done')
################################################################
# FUNCTIONS
def create_vital_signs_editors_db():
wikilanguagecodes_plusmeta = ['meta']
conn = sqlite3.connect(databases_path + vital_signs_editors_db); cursor = conn.cursor()
conn2 = sqlite3.connect(databases_path + vital_signs_web_db); cursor2 = conn2.cursor()
# EDITORS DB
for languagecode in wikilanguagecodes_plusmeta:
table_name = languagecode+'wiki_editors'
try:
cursor.execute("DROP TABLE "+table_name+";")
except:
pass
query = ("CREATE TABLE IF NOT EXISTS "+table_name+" ("+
"user_id integer, user_name text, bot text, user_flags text, highest_flag text, highest_flag_year_month text, gender text, "+
"primarybinary integer, primarylang text, edit_count integer, primary_ecount integer, totallangs_ecount integer, primary_year_month_first_edit text, primary_lustrum_first_edit text, numberlangs integer, "+
"registration_date, year_month_registration, first_edit_timestamp text, year_month_first_edit text, year_first_edit text, lustrum_first_edit text, "+
"survived60d text, last_edit_timestamp text, year_last_edit text, lifetime_days integer, days_since_last_edit integer, PRIMARY KEY (user_name))")
cursor.execute(query)
table_name = languagecode+'wiki_editor_metrics'
try:
cursor.execute("DROP TABLE "+table_name+";")
except:
pass
query = ("CREATE TABLE IF NOT EXISTS "+table_name+" (user_id integer, user_name text, abs_value real, rel_value real, metric_name text, year_month text, timestamp text, PRIMARY KEY (user_id, metric_name, year_month, timestamp))")
cursor.execute(query)
# VITAL SIGNS DB
table_name = 'vital_signs_metrics'
try:
cursor2.execute("DROP TABLE "+table_name+";")
except:
pass
query = ("CREATE TABLE IF NOT EXISTS "+table_name+" (langcode text, year_year_month text, year_month text, topic text, m1 text, m1_calculation text, m1_value text, m2 text, m2_calculation text, m2_value text, m1_count float, m2_count float, PRIMARY KEY (langcode, year_year_month, year_month, topic, m1, m1_calculation, m1_value, m2, m2_calculation, m2_value))")
cursor2.execute(query)
conn2.commit()
def get_mediawiki_paths(languagecode):
cym = cycle_year_month
d_paths = []
print ('/public/dumps/public/other/mediawiki_history/'+cym)
if os.path.isdir('/public/dumps/public/other/mediawiki_history/'+cym)==False:
cym = datetime.datetime.strptime(cym,'%Y-%m')-dateutil.relativedelta.relativedelta(months=1)
cym = cym.strftime('%Y-%m')
print ('/public/dumps/public/other/mediawiki_history/'+cym)
dumps_path = '/public/dumps/public/other/mediawiki_history/'+cym+'/'+languagecode+'wiki/'+cym+'.'+languagecode+'wiki.all-time.tsv.bz2'
if os.path.isfile(dumps_path):
print ('one all-time file.')
d_paths.append(dumps_path)
else:
print ('multiple files.')
for year in range (1999, 2025):
dumps_path = '/public/dumps/public/other/mediawiki_history/'+cym+'/'+languagecode+'wiki/'+cym+'.'+languagecode+'wiki.'+str(year)+'.tsv.bz2'
if os.path.isfile(dumps_path):
d_paths.append(dumps_path)
if len(d_paths) == 0:
for year in range(1999, 2025): # months
for month in range(0, 13):
if month > 9:
dumps_path = '/public/dumps/public/other/mediawiki_history/'+cym+'/'+languagecode+'wiki/'+cym+'.'+languagecode+'wiki.'+str(year)+'-'+str(month)+'.tsv.bz2'
else:
dumps_path = '/public/dumps/public/other/mediawiki_history/'+cym+'/'+languagecode+'wiki/'+cym+'.'+languagecode+'wiki.'+str(year)+'-0'+str(month)+'.tsv.bz2'
if os.path.isfile(dumps_path) == True:
d_paths.append(dumps_path)
print(len(d_paths))
print (d_paths)
return d_paths, cym
def editor_metrics_dump_iterator(languagecode):
functionstartTime = time.time()
function_name = 'editor_metrics_dump_iterator '+languagecode
print (function_name)
d_paths, cym = get_mediawiki_paths(languagecode)
cym_timestamp_dt = datetime.datetime.today().replace(day=1) #.strftime('%Y-%m-%d %H:%M:%S')
# print (cym_timestamp_dt)
# input('')
if (len(d_paths)==0):
print ('dump error. this language has no mediawiki_history dump: '+languagecode)
# wikilanguages_utils.send_email_toolaccount('dump error at script '+script_name, dumps_path)
# quit()
conn = sqlite3.connect(databases_path + vital_signs_editors_db); cursor = conn.cursor()
user_id_user_name_dict = {}
user_id_bot_dict = {}
user_id_user_groups_dict = {}
editor_first_edit_timestamp = {}
editor_registration_date = {}
editor_last_edit_timestamp = {}
editor_user_group_dict = {}
editor_user_group_dict_timestamp = {}
# for the survival part
survived_dict = {}
survival_measures = []
user_id_edit_count = {}
# for the monthly part
editor_monthly_namespace_technical = {} # 8, 10
editor_monthly_namespace_coordination = {} # 4, 12
editor_monthly_edits = {}
last_year_month = 0
first_date = datetime.datetime.strptime('2001-01-01 01:15:15','%Y-%m-%d %H:%M:%S')
# print (d_paths)
# input('')
# d_paths = d_paths[15:]
for dump_path in d_paths:
print('\n'+dump_path)
iterTime = time.time()
dump_in = bz2.open(dump_path, 'r')
line = 'something'
line = dump_in.readline()
print ('year_month here: '+str(last_year_month))
# input('')
while line != '':
# print ('*')
# print (line)
# print (seconds_since_last_edit)
# print ('*')
# input('')
line = dump_in.readline()
line = line.rstrip().decode('utf-8')[:-1]
values = line.split('\t')
if len(values)==1: continue
event_entity = values[1]
event_type = values[2]
event_user_id = values[5]
try: int(event_user_id)
except:
continue
event_user_text = values[7]
if event_user_text != '': user_id_user_name_dict[event_user_id] = event_user_text
else:
continue
try:
editor_last_edit = editor_last_edit_timestamp[event_user_id]
last_edit_date_dt = datetime.datetime.strptime(editor_last_edit[:len(editor_last_edit)-2],'%Y-%m-%d %H:%M:%S')
last_edit_year_month_day = datetime.datetime.strptime(last_edit_date_dt.strftime('%Y-%m-%d'),'%Y-%m-%d')
except:
last_edit_year_month_day = ''
event_timestamp = values[3]
event_timestamp_dt = datetime.datetime.strptime(event_timestamp[:len(event_timestamp)-2],'%Y-%m-%d %H:%M:%S')
editor_last_edit_timestamp[event_user_id] = event_timestamp
editor_edit_count[event_user_id] = values[21]
event_user_groups = values[11]
if event_user_groups != '':
user_id_user_groups_dict[event_user_id] = event_user_groups
# if event_user_text in ['Barcelona']:
# print ('*')
# print (event_user_text, ',', event_user_groups, ',', 'historical:', values[10])
# print (values)
# if len(values)>37:
# user_text = values[38]
# if event_type == 'altergroups':
# print ('-')
# print (values[38])
# print ('user groups historical:',values[41])
# print ('user groups:',values[42])
# print (values)
# print ('-')
page_namespace = values[28]
if event_entity == 'user':
user_text = str(values[38]) # this is target of the event
if event_type == 'altergroups':
user_id = values[36]
cur_ug = values[41]
user_text = values[38]
if user_text != '': user_id_user_name_dict[user_id] = user_text
# editor_user_group_dict --> el que té fins ara.
# editor_user_group_dict_timestamp[user_id,event_timestamp] = [metric_name, change_[0], cur_ug] -->
if cur_ug != '' and cur_ug != None:
try:
old_ug = editor_user_group_dict[user_id]
if ',' in old_ug:
old_ug_list = old_ug.split(',')
else:
old_ug_list = [old_ug]
except:
old_ug_list = []
# print (old_ug_list)
if ',' in cur_ug:
cur_ug_list = cur_ug.split(',')
else:
cur_ug_list = [cur_ug]
# print (cur_ug_list)
i = 0
for x in cur_ug_list:
if x not in old_ug_list:
# print ('granted flag: '+x+' for user: '+user_text+' timestamp: '+ event_timestamp)
# input('')
event_ts = event_timestamp[:len(event_timestamp)-i]
editor_user_group_dict_timestamp[user_id,event_ts] = ['granted_flag', x]
i += 1
for x in old_ug_list:
if x not in cur_ug_list:
# print ('removed flag: '+x+' for user: '+user_text+' timestamp: '+ event_timestamp)
# input('')
event_ts = event_timestamp[:len(event_timestamp)-i]
editor_user_group_dict_timestamp[user_id,event_ts] = ['removed_flag', x]
i += 1
editor_user_group_dict[user_id] = cur_ug
event_is_bot_by = values[13]
if event_is_bot_by != '':
user_id_bot_dict[event_user_id] = event_is_bot_by
# print (event_user_text, event_is_bot_by)
event_user_is_anonymous = values[17]
if event_user_is_anonymous == True or event_user_id == '': continue
event_user_registration_date = values[18]
event_user_creation_date = values[19]
if event_user_id not in editor_registration_date:
if event_user_registration_date != '':
editor_registration_date[event_user_id] = event_user_registration_date
elif event_user_creation_date != '':
editor_registration_date[event_user_id] = event_user_creation_date
####### ---------
# MONTHLY EDITS COUNTER
try: editor_monthly_edits[event_user_id] = editor_monthly_edits[event_user_id]+1
except: editor_monthly_edits[event_user_id] = 1
# MONTHLY NAMESPACES EDIT COUNTER
if page_namespace == '4' or page_namespace == '12':
try: editor_monthly_namespace_coordination[event_user_id] = editor_monthly_namespace_coordination[event_user_id]+1
except: editor_monthly_namespace_coordination[event_user_id] = 1
elif page_namespace == '8' or page_namespace == '10':
try: editor_monthly_namespace_technical[event_user_id] = editor_monthly_namespace_technical[event_user_id]+1
except: editor_monthly_namespace_technical[event_user_id] = 1
#######--------- --------- --------- --------- --------- ---------
# CHECK MONTH CHANGE AND INSERT MONTHLY EDITS/NAMESPACES EDITS/SECONDS
current_year_month = datetime.datetime.strptime(event_timestamp_dt.strftime('%Y-%m'),'%Y-%m')
if last_year_month != current_year_month and last_year_month != 0:
lym = last_year_month.strftime('%Y-%m')
print ('change of month / new: ',current_year_month, 'old: ',lym)
lym_sp = lym.split('-')
ly = lym_sp[0]
lm = lym_sp[1]
lym_days = calendar.monthrange(int(ly),int(lm))[1]
monthly_edits = []
namespaces = []
for user_id, edits in editor_monthly_edits.items():
monthly_edits.append((user_id, user_id_user_name_dict[user_id], edits, None, 'monthly_edits', lym, ''))
for user_id, edits in editor_monthly_namespace_coordination.items():
try: namespaces.append((user_id, user_id_user_name_dict[user_id], edits, None, 'monthly_edits_coordination', lym, ''))
except: pass
for user_id, edits in editor_monthly_namespace_technical.items():
try: namespaces.append((user_id, user_id_user_name_dict[user_id], edits, None, 'monthly_edits_technical', lym, ''))
except: pass
for key, data in editor_user_group_dict_timestamp.items():
user_id = key[0]
timestamp = key[1]
metric_name = data[0]
flags = data[1]
try:
namespaces.append((user_id, user_id_user_name_dict[user_id], flags, None, metric_name, lym, timestamp))
# print ('#')
# print ((user_id, user_id_user_name_dict[user_id], flags, None, metric_name, lym, timestamp))
# print ('#')
except:
# print ('error.')
# print (user_id)
# print ('...'+flags)
pass
query = 'INSERT OR IGNORE INTO '+languagecode+'wiki_editor_metrics (user_id, user_name, abs_value, rel_value, metric_name, year_month, timestamp) VALUES (?,?,?,?,?,?,?);'
cursor.executemany(query,monthly_edits)
cursor.executemany(query,namespaces)
# print ('lengths: ')
# print (len(user_id_user_name_dict))
# print (len(editor_monthly_edits))
# print (len(editor_monthly_namespace_coordination))
# print (len(editor_monthly_namespace_technical))
# print (len(editor_user_group_dict_timestamp))
# print ('inserted')
conn.commit()
monthly_edits = []
namespaces = []
editor_monthly_namespace_coordination = {}
editor_monthly_namespace_technical = {}
editor_monthly_edits = {}
editor_user_group_dict_timestamp = {}
last_year_month = current_year_month
# month change
####### ---------
# SURVIVAL MEASURES
event_user_first_edit_timestamp = values[20]
if event_user_id not in editor_first_edit_timestamp:
editor_first_edit_timestamp[event_user_id] = event_user_first_edit_timestamp
if event_user_first_edit_timestamp == '' or event_user_first_edit_timestamp == None:
event_user_first_edit_timestamp = editor_first_edit_timestamp[event_user_id]
if event_user_first_edit_timestamp != '' and event_user_id not in survived_dict:
event_user_first_edit_timestamp_dt = datetime.datetime.strptime(event_user_first_edit_timestamp[:len(event_user_first_edit_timestamp)-2],'%Y-%m-%d %H:%M:%S')
# thresholds
first_edit_timestamp_1day_dt = (event_user_first_edit_timestamp_dt + relativedelta.relativedelta(days=1))
first_edit_timestamp_7days_dt = (event_user_first_edit_timestamp_dt + relativedelta.relativedelta(days=7))
first_edit_timestamp_1months_dt = (event_user_first_edit_timestamp_dt + relativedelta.relativedelta(months=1))
first_edit_timestamp_2months_dt = (event_user_first_edit_timestamp_dt + relativedelta.relativedelta(months=2))
try: ec = user_id_edit_count[event_user_id]
except: ec = 1
# at 1 day
if event_timestamp_dt >= first_edit_timestamp_1day_dt:
survival_measures.append((event_user_id, event_user_text, ec, None, 'edit_count_24h', first_edit_timestamp_1day_dt.strftime('%Y-%m'),first_edit_timestamp_1day_dt.strftime('%Y-%m-%d %H:%M:%S')))
# at 7 days
if event_timestamp_dt >= first_edit_timestamp_7days_dt:
survival_measures.append((event_user_id, event_user_text, ec, None, 'edit_count_7d', first_edit_timestamp_7days_dt.strftime('%Y-%m'),first_edit_timestamp_7days_dt.strftime('%Y-%m-%d %H:%M:%S')))
# at 1 month
if event_timestamp_dt >= first_edit_timestamp_1months_dt:
survival_measures.append((event_user_id, event_user_text, ec, None, 'edit_count_30d', first_edit_timestamp_1months_dt.strftime('%Y-%m'),first_edit_timestamp_1months_dt.strftime('%Y-%m-%d %H:%M:%S')))
# at 2 months
if event_timestamp_dt >= first_edit_timestamp_2months_dt:
survival_measures.append((event_user_id, event_user_text, ec, None, 'edit_count_60d', first_edit_timestamp_2months_dt.strftime('%Y-%m'),first_edit_timestamp_2months_dt.strftime('%Y-%m-%d %H:%M:%S')))
survived_dict[event_user_id]=event_user_text
try: del user_id_edit_count[event_user_id]
except: pass
# USER PAGE EDIT COUNT, ADD ONE MORE EDIT.
if event_user_id not in survived_dict:
# EDIT COUNT, ADD ONE MORE EDIT.
event_user_revision_count = values[21]
if event_user_revision_count != '':
user_id_edit_count[event_user_id] = event_user_revision_count
elif event_user_id in user_id_edit_count:
user_id_edit_count[event_user_id] = int(user_id_edit_count[event_user_id]) + 1
else:
user_id_edit_count[event_user_id] = 1
####### ---------
# SURVIVAL MEASURES INSERT
query = 'INSERT OR IGNORE INTO '+languagecode+'wiki_editor_metrics (user_id, user_name, abs_value, rel_value, metric_name, year_month, timestamp) VALUES (?,?,?,?,?,?,?);'
cursor.executemany(query,survival_measures)
conn.commit()
survival_measures = []
# MONTHLY EDITS/NAMESPACES INSERT (LAST ROUND)
print (last_year_month)
try:
lym = last_year_month.strftime('%Y-%m')
except:
lym = ''
if lym != cym and lym != '':
monthly_edits = []
for event_user_id, edits in editor_monthly_edits.items():
monthly_edits.append((event_user_id, user_id_user_name_dict[event_user_id], edits, None, 'monthly_edits', lym, ''))
query = 'INSERT OR IGNORE INTO '+languagecode+'wiki_editor_metrics (user_id, user_name, abs_value, rel_value, metric_name, year_month, timestamp) VALUES (?,?,?,?,?,?,?);'
cursor.executemany(query,monthly_edits)
conn.commit()
namespaces = []
for key, data in editor_user_group_dict_timestamp.items():
user_id = key[0]
timestamp = key[1]
metric_name = data[0]
flags = data[1]
try:
namespaces.append((user_id, user_id_user_name_dict[user_id], flags, None, metric_name, lym, timestamp))
except:
pass
for user_id, edits in editor_monthly_namespace_coordination.items():
try: namespaces.append((user_id, user_id_user_name_dict[user_id], edits, None, 'monthly_edits_coordination', lym, ''))
except: pass
for user_id, edits in editor_monthly_namespace_technical.items():
try: namespaces.append((user_id, user_id_user_name_dict[user_id], edits, None, 'monthly_edits_technical', lym, ''))
except: pass
query = 'INSERT OR IGNORE INTO '+languagecode+'wiki_editor_metrics (user_id, user_name, abs_value, rel_value, metric_name, year_month, timestamp) VALUES (?,?,?,?,?,?,?);'
cursor.executemany(query,monthly_edits)
cursor.executemany(query,namespaces)
conn.commit()
namespaces = []
monthly_edits = []
editor_monthly_edits = {}
editor_monthly_namespace_coordination = {}
editor_monthly_namespace_technical = {}
editor_user_group_dict_timestamp = {}
# USER CHARACTERISTICS INSERT
user_characteristics1 = []
user_characteristics2 = []
for user_id, user_name in user_id_user_name_dict.items():
try: user_flags = user_id_user_groups_dict[user_id]
except: user_flags = None
try: bot = user_id_bot_dict[user_id]
except: bot = 'editor'
if user_id in survived_dict: survived60d = '1'
else: survived60d = '0'
try:
edit_count = editor_edit_count[user_id]
except:
edit_count = None
try: registration_date = editor_registration_date[user_id]
except: registration_date = None
if registration_date == None: # THIS IS SOMETHING WE "ASSUME" BECAUSE THERE ARE MANY ACCOUNTS WITHOUT A REGISTRATION DATE.
try: registration_date = editor_first_edit_timestamp[user_id]
except: registration_date = None
if registration_date != '' and registration_date != None: year_month_registration = datetime.datetime.strptime(registration_date[:len(registration_date)-2],'%Y-%m-%d %H:%M:%S').strftime('%Y-%m')
else: year_month_registration = None
try: fe = editor_first_edit_timestamp[user_id]
except: fe = None
try:
le = editor_last_edit_timestamp[user_id]
year_last_edit = datetime.datetime.strptime(le[:len(le)-2],'%Y-%m-%d %H:%M:%S').strftime('%Y')
except:
le = None
year_last_edit = None
if fe != None and fe != '':
year_month = datetime.datetime.strptime(fe[:len(fe)-2],'%Y-%m-%d %H:%M:%S').strftime('%Y-%m')
year_first_edit = datetime.datetime.strptime(fe[:len(fe)-2],'%Y-%m-%d %H:%M:%S').strftime('%Y')
if int(year_first_edit) >= 2001 < 2006: lustrum_first_edit = '2001-2005'
if int(year_first_edit) >= 2006 < 2011: lustrum_first_edit = '2006-2010'
if int(year_first_edit) >= 2011 < 2016: lustrum_first_edit = '2011-2015'
if int(year_first_edit) >= 2016 < 2021: lustrum_first_edit = '2016-2020'
if int(year_first_edit) >= 2021 < 2026: lustrum_first_edit = '2021-2025'
fe_d = datetime.datetime.strptime(fe[:len(fe)-2],'%Y-%m-%d %H:%M:%S')
else:
year_month = None
year_first_edit = None
lustrum_first_edit = None
fe_d = None
if le != None:
le_d = datetime.datetime.strptime(le[:len(le)-2],'%Y-%m-%d %H:%M:%S')
days_since_last_edit = (cym_timestamp_dt - le_d).days
else:
le_d = None
days_since_last_edit = None
if fe != None and fe != '' and le != None: lifetime_days = (le_d - fe_d).days
else: lifetime_days = None
user_characteristics1.append((user_id, user_name, registration_date, year_month_registration, fe, year_month, year_first_edit, lustrum_first_edit))
if le != None:
user_characteristics2.append((bot, user_flags, le, year_last_edit, lifetime_days, days_since_last_edit, survived60d, edit_count, user_id, user_name))
# if user_id == 296 or user_name == 'Jolle':
# print ((user_id, user_name, registration_date, year_month_registration, fe, year_month, year_first_edit, lustrum_first_edit, survived60d))
# print ((bot, user_flags, le, year_last_edit, lifetime_days, days_since_last_edit, se, user_id, user_name))
# print (cym_timestamp_dt,le_d)
# print (editor_last_edit_timestamp[user_id])
query = 'INSERT OR IGNORE INTO '+languagecode+'wiki_editors (user_id, user_name, registration_date, year_month_registration, first_edit_timestamp, year_month_first_edit, year_first_edit, lustrum_first_edit) VALUES (?,?,?,?,?,?,?,?);'
cursor.executemany(query,user_characteristics1)
conn.commit()
query = 'INSERT OR IGNORE INTO '+languagecode+'wiki_editors (bot, user_flags, last_edit_timestamp, year_last_edit, lifetime_days, days_since_last_edit, survived60d, edit_count, user_id, user_name) VALUES (?,?,?,?,?,?,?,?,?,?);'
cursor.executemany(query,user_characteristics2)
conn.commit()
query = 'UPDATE '+languagecode+'wiki_editors SET bot = ?, user_flags = ?, last_edit_timestamp = ?, year_last_edit = ?, lifetime_days = ?, days_since_last_edit = ?, survived60d = ?, edit_count = ?, user_id = ? WHERE user_name = ?;'
cursor.executemany(query,user_characteristics2)
conn.commit()
print (len(user_characteristics1),len(user_characteristics2))
user_characteristics1 = []
user_characteristics2 = []
# user_id_user_name_dict = {}
# insert or ignore + update
user_id_bot_dict = {}
user_id_user_groups_dict = {}
editor_last_edit_timestamp = {}
editor_seconds_since_last_edit = {}
editor_edit_count = {}
# insert or ignore
editor_first_edit_timestamp = {}
editor_registration_date = {}
# keep only pending monthly edits
print ('total number of stored user_ids at the end of the dump: ')
print (len(user_id_user_name_dict))
user_id_user_name_dict2 = {}
for k in editor_monthly_edits.keys():
user_id_user_name_dict2[k]=user_id_user_name_dict[k]
for k in editor_monthly_namespace_coordination.keys():
user_id_user_name_dict2[k]=user_id_user_name_dict[k]
for k in editor_monthly_namespace_technical.keys():
user_id_user_name_dict2[k]=user_id_user_name_dict[k]
for k in editor_user_group_dict_timestamp.keys():
user_id_user_name_dict2[k[0]]=user_id_user_name_dict[k[0]]
print ('updated number of necessary user_ids: ')
print (len(user_id_user_name_dict2))
user_id_user_name_dict = user_id_user_name_dict2
user_id_user_name_dict2 = {}
# END OF THE DUMP!!!!
print ('end of the dump.')
print ('*')
print (str(datetime.timedelta(seconds=time.time() - iterTime)))
# input('')
"""
# AGGREGATED METRICS (EDIT COUNTS)
monthly_aggregated_metrics = {'monthly_edits':'edit_count'}
conn2 = sqlite3.connect(databases_path + vital_signs_editors_db); cursor2 = conn2.cursor()
for monthly_metric_name, metric_name in monthly_aggregated_metrics.items():
edit_counts = []
query = 'SELECT user_id, user_name, SUM(abs_value) FROM '+languagecode+'wiki_editor_metrics WHERE metric_name = "'+monthly_metric_name+'" GROUP BY 2;'
for row in cursor2.execute(query):
user_id = row[0]
user_name = row[1]
value = row[2]
edit_counts.append((value, user_name, user_id))
query = 'UPDATE '+languagecode+'wiki_editors SET edit_count = ? WHERE user_name = ? AND user_id = ?;'
cursor2.executemany(query,edit_counts)
conn2.commit()
print ('Updated the editors table with the edit count.')
"""
# FLAGS UPDATE
# Getting the highest flag
conn = sqlite3.connect(databases_path + vital_signs_editors_db); cursor = conn.cursor()
query = 'SELECT user_flags, count(user_id) FROM '+languagecode+'wiki_editors WHERE user_flags != "" GROUP BY 1;'
flags_count_dict = {}
for row in cursor.execute(query):
flags = row[0]
count = row[1]
if ',' in flags:
fs = flags.split(',')
for x in fs:
try:
flags_count_dict[x]+=count
except:
flags_count_dict[x]=1
else:
try:
flags_count_dict[flags]+=count
except:
flags_count_dict[flags]=1
print ('Number of editors for each flag')
print (flags_count_dict)
# print ('in')
# input('')
flag_ranks = {
'confirmed':1,'ipblock-exempt':1,
'filemover':2,'accountcreator':2,'autopatrolled':2,'reviewer':2,'autoreviewer':2,'rollbacker':2,'abusefilter':2,'abusefilter-ehlper':2,'interface-admin':2,'eventcoordinator':2,'extendedconfirmed':2,'extendedmover':2, 'filemover':2, 'massmessage-sender':2, 'patroller':2, 'researcher':2, 'templateeditor':2,
'sysop':3,'bureaucrat':3.5,
'checkuser':4,'oversight':4.5,
'steward':5.5, 'import':5,
'founder':6
}
query = 'SELECT user_id, user_flags, user_name FROM '+languagecode+'wiki_editors WHERE user_flags != "";'
params = []
user_id_flag = {}
for row in cursor.execute(query):
user_id = row[0]
user_flags = row[1]
user_name = row[2]
highest_rank = {}
highest_count = {}
if ',' in user_flags:
uf = user_flags.split(',')
for x in uf:
if x in flag_ranks and 'bot' not in x:
val = flag_ranks[x]
highest_rank[x] = val
if len(highest_rank) > 1:
maxval = max(highest_rank.values())
highest_rank = {key:val for key, val in highest_rank.items() if val == maxval} # we are choosing the flag of highest rank.
if len(highest_rank)>1:
for x in highest_rank.keys():
val = flags_count_dict[x]
highest_count[x] = val
maxval = max(highest_count.values())
highest_count = {key:val for key, val in highest_count.items() if val == maxval} # we are choosing the flag that exists more in the community.
f = list(highest_count.keys())[0]
params.append((f, user_name))
user_id_flag[user_id]=f
else:
f = list(highest_rank.keys())[0]
params.append((f, user_name))
user_id_flag[user_id]=f
else:
if user_flags in flag_ranks and 'bot' not in user_flags:
params.append((user_flags, user_name))
user_id_flag[user_id]=user_flags
query = 'UPDATE '+languagecode+'wiki_editors SET highest_flag = ? WHERE user_name = ?;'
cursor.executemany(query,params)
conn.commit()
print ('Updated the editors table with highest flag')
# let's update the highest_flag_year_month
query = 'SELECT year_month, user_id, user_name, abs_value FROM '+languagecode+'wiki_editor_metrics WHERE metric_name = "granted_flag";'
params2 = []
conn = sqlite3.connect(databases_path + vital_signs_editors_db); cursor = conn.cursor()
for row in cursor.execute(query):
year_month=row[0]
user_id=row[1]
user_name=row[2]
flag = row[3]
try:
ex_flag = user_id_flag[user_id]
except:
continue
# print ((ex_flag, flag,year_month,user_id,user_name))
if ex_flag in flag:
# print ((ex_flag, flag,year_month,user_id,user_name))
params2.append((year_month,user_name))
# print (params2)
query = 'UPDATE '+languagecode+'wiki_editors SET highest_flag_year_month = ? WHERE user_name = ?;'
cursor.executemany(query,params2)
conn.commit()
print ('Updated the editors table with the year month they obtained the highest flag.')
# print(list(highest_flag.values()).count('bureaucrat'))
# print ('stop highest flag year month'); input('stop');
# If an editor has been granted the 'bot' flag, even if it has been taken away, it must be a flag.
query = 'SELECT user_id, user_name FROM '+languagecode+'wiki_editor_metrics WHERE metric_name = "granted_flag" AND abs_value LIKE "%bot";'
params = []
for row in cursor.execute(query):
username = row[1]
if 'bot' in username:
bottype = 'name,group'
else:
bottype = 'group'
params.append((bottype,username))
query = 'UPDATE '+languagecode+'wiki_editors SET bot = ? WHERE user_name = ?;'
cursor.executemany(query,params)
conn.commit()
print ('Updated the table with the bots from flag.')
duration = str(datetime.timedelta(seconds=time.time() - functionstartTime))
print(languagecode+' '+ function_name+' '+ duration)
def editor_metrics_db_iterator(languagecode):
functionstartTime = time.time()
function_name = 'editor_metrics_db_iterator '+languagecode
print (function_name)
d_paths, cym = get_mediawiki_paths(languagecode)
cycle_year_month = cym
print (cycle_year_month)
conn = sqlite3.connect(databases_path + vital_signs_editors_db); cursor = conn.cursor()
# MONTHLY EDITS LOOP
query = 'SELECT abs_value, year_month, user_id, user_name FROM '+languagecode+'wiki_editor_metrics WHERE metric_name = "monthly_edits" ORDER BY user_name, year_month'
# AND user_name in ("Toniher","Marcmiquel","Barcelona","TaronjaSatsuma","Kippelboy")
# print (query)
user_count = 0
old_user_id = ''
old_edits = None
expected_year_month_dt = ''
# parameters = []
# editors_edits_baseline_parameters = []
active_months_row = 0
total_edits = []
edits_increase_decrease = 0
try: os.remove(databases_path +'temporary_editor_metrics.txt')
except: pass
edfile2 = open(databases_path+'temporary_editor_metrics.txt', "w")
for row in cursor.execute(query):
edits=row[0]
current_year_month = row[1]
cur_user_id = row[2]
cur_user_name = row[3]
if cur_user_id != old_user_id and old_user_id != '':
active_months_row = 0