3 # original wikiq headers are: title articleid revid date_time anon
4 # editor editor_id minor text_size text_entropy text_md5 reversion
5 # additions_size deletions_size
12 from subprocess import Popen, PIPE
13 from collections import deque
14 from hashlib import sha1
16 from mwxml import Dump
18 from deltas.tokenizers import wikitext_split
21 from urllib.parse import quote
22 TO_ENCODE = ('title', 'editor')
24 from deltas import SequenceMatcher
25 from deltas import SegmentMatcher
33 def calculate_persistence(tokens_added):
34 return(sum([(len(x.revisions)-1) for x in tokens_added]),
37 def matchmake(scanned_content, rev_data, regex, label):
41 # if there are named capture groups in the regex
42 if bool(p.groupindex):
43 capture_groups = list(p.groupindex.keys())
45 # initialize the {capture_group_name:list} for each capture group
46 for cap_group in capture_groups:
47 temp_dict["{}_{}".format(label, cap_group)] = []
49 # if there are matches of some sort in this revision content, fill the lists for each cap_group
50 if p.search(scanned_content) is not None:
51 m = re.finditer(p,scanned_content)
52 matchobjects = list(m)
54 for cap_group in capture_groups:
56 for match in matchobjects:
57 # we only want to add the match for the capture group if the match is not None
58 if match.group(cap_group) != None:
59 temp_list.append(match.group(cap_group))
61 # if temp_list of matches is empty just make that column None
63 temp_dict["{}_{}".format(label, cap_group)] = None
64 # else we put in the list we made in the for-loop above
66 temp_dict["{}_{}".format(label, cap_group)] = ', '.join(temp_list)
68 # there are no matches at all in this revision content, we default values to None
70 for cap_group in capture_groups:
71 temp_dict["{}_{}".format(label, cap_group)] = None
73 # there are no capture groups, we just search for all the matches of the regex
75 #given that there are matches to be made
76 if p.search(scanned_content) is not None:
77 m = p.findall(scanned_content)
78 temp_dict[label] = ', '.join(m)
80 temp_dict[label] = None
81 # update rev_data with our new columns
82 rev_data.update(temp_dict)
83 # print(rev_data.keys())
87 class WikiqIterator():
88 def __init__(self, fh, collapse_user=False):
90 self.collapse_user = collapse_user
91 self.mwiterator = Dump.from_file(self.fh)
92 self.namespace_map = { ns.id : ns.name for ns in
93 self.mwiterator.site_info.namespaces }
94 self.__pages = self.load_pages()
97 for page in self.mwiterator:
99 namespace_map = self.namespace_map,
100 collapse_user=self.collapse_user)
106 return next(self._pages)
109 __slots__ = ('id', 'title', 'namespace', 'redirect',
110 'restrictions', 'mwpage', '__revisions',
113 def __init__(self, page, namespace_map, collapse_user=False):
115 self.namespace = page.namespace
116 # following mwxml, we assume namespace 0 in cases where
117 # page.namespace is inconsistent with namespace_map
118 if page.namespace not in namespace_map:
119 self.title = page.title
121 if page.namespace != 0:
122 self.title = ':'.join([namespace_map[page.namespace], page.title])
124 self.title = page.title
125 self.restrictions = page.restrictions
126 self.collapse_user = collapse_user
128 self.__revisions = self.rev_list()
131 # Outline for how we want to handle collapse_user=True
132 # iteration rev.user prev_rev.user add prev_rev?
139 for i, rev in enumerate(self.mwpage):
140 # never yield the first time
142 if self.collapse_user:
144 rev.collapsed_revs = collapsed_revs
147 if self.collapse_user:
148 # yield if this is the last edit in a seq by a user and reset
149 # also yield if we do know who the user is
151 if rev.deleted.user or prev_rev.deleted.user:
154 rev.collapsed_revs = collapsed_revs
156 elif not rev.user.text == prev_rev.user.text:
159 rev.collapsed_revs = collapsed_revs
160 # otherwise, add one to the counter
163 rev.collapsed_revs = collapsed_revs
164 # if collapse_user is false, we always yield
170 # also yield the final time
174 return self.__revisions
177 return next(self.__revisions)
180 def __init__(self, input_file, output_file, regex_match_revision, regex_match_comment, regex_revision_label, regex_comment_label, collapse_user=False, persist=None, urlencode=False, namespaces = None, revert_radius=15):
183 persist : what persistence method to use. Takes a PersistMethod value
186 self.input_file = input_file
187 self.output_file = output_file
188 self.collapse_user = collapse_user
189 self.persist = persist
190 self.printed_header = False
192 self.urlencode = urlencode
193 self.revert_radius = revert_radius
194 self.regex_match_revision = regex_match_revision
195 self.regex_revision_label = regex_revision_label
196 self.regex_match_comment = regex_match_comment
197 self.regex_comment_label = regex_comment_label
199 if namespaces is not None:
200 self.namespace_filter = set(namespaces)
202 self.namespace_filter = None
204 def __get_namespace_from_title(self, title):
207 for ns in self.namespaces:
208 # skip if the namespace is not defined
210 default_ns = self.namespaces[ns]
213 if title.startswith(ns + ":"):
214 return self.namespaces[ns]
216 # if we've made it this far with no matches, we return the default namespace
222 # create a regex that creates the output filename
223 # output_filename = re.sub(r'^.*/(enwiki\-\d+)\-.*p(\d+)p.*$',
224 # r'output/wikiq-\1-\2.tsv',
227 # Construct dump file iterator
228 dump = WikiqIterator(self.input_file, collapse_user=self.collapse_user)
230 # extract list of namspaces
231 self.namespaces = {ns.name : ns.id for ns in dump.mwiterator.site_info.namespaces}
237 # Iterate through pages
239 namespace = page.namespace if page.namespace is not None else self.__get_namespace_from_title(page.title)
241 # skip namespaces not in the filter
242 if self.namespace_filter is not None:
243 if namespace not in self.namespace_filter:
246 # print(self.revert_radius)
247 rev_detector = mwreverts.Detector(radius = self.revert_radius)
250 if self.persist != PersistMethod.none:
251 window = deque(maxlen=PERSISTENCE_RADIUS)
253 if self.persist == PersistMethod.sequence:
254 state = mwpersistence.DiffState(SequenceMatcher(tokenizer = wikitext_split),
255 revert_radius=PERSISTENCE_RADIUS)
257 elif self.persist == PersistMethod.segment:
258 state = mwpersistence.DiffState(SegmentMatcher(tokenizer = wikitext_split),
259 revert_radius=PERSISTENCE_RADIUS)
261 # self.persist == PersistMethod.legacy
263 from mw.lib import persistence
264 state = persistence.State()
266 # Iterate through a page's revisions
269 # initialize rev_data
272 # if the command line args only gave a label (and no regular expression is given)
273 if (self.regex_revision_label != None and self.regex_match_revision == None) or (self.regex_comment_label != None and self.regex_match_comment == None):
274 sys.exit('The given regex label(s) has no corresponding regex to search for.')
276 # if there's anything in the list of regex_match_revision
277 if self.regex_match_revision is not None:
278 if (self.regex_revision_label == None) or (len(self.regex_match_revision) != len(self.regex_revision_label)):
279 sys.exit('Each regular expression *must* come with a corresponding label and vice versa.')
281 # initialize and construct the list of regex-label tuples
283 for i in range(0,len(self.regex_match_revision)):
284 pairs.append((self.regex_match_revision[i], self.regex_revision_label[i]))
286 # for each regex/label pair, we now run matchmake to check and output columns
288 # pair[0] corresponds to the regex, pair[1] to the label
289 rev_data = matchmake(rev.text, rev_data, pair[0], pair[1])
291 # if there's anything in the list of regex_match_comment
292 if self.regex_match_comment is not None:
293 if (self.regex_comment_label == None) or (len(self.regex_match_comment) != len(self.regex_comment_label)):
294 sys.exit('Each regular expression *must* come with a corresponding label and vice versa.')
296 # initialize and construct the list of regex-label tuples
298 for i in range(0,len(self.regex_match_comment)):
299 pairs.append((self.regex_match_comment[i], self.regex_comment_label[i]))
301 # for each regex/label pair, we now run matchmake to check and output columns
303 # pair[0] corresponds to the regex, pair[1] to the label
304 rev_data = matchmake(rev.comment, rev_data, pair[0], pair[1])
306 # we fill out the rest of the data structure now
307 rev_data['revid'] = rev.id
308 rev_data['date_time'] = rev.timestamp.strftime('%Y-%m-%d %H:%M:%S')
309 rev_data['articleid'] = page.id
310 rev_data['editor_id'] = "" if rev.deleted.user == True or rev.user.id is None else rev.user.id
311 rev_data['title'] = '"' + page.title + '"'
312 rev_data['namespace'] = namespace
313 rev_data['deleted'] = "TRUE" if rev.deleted.text else "FALSE"
315 # if revisions are deleted, /many/ things will be missing
317 rev_data['text_chars'] = ""
318 rev_data['sha1'] = ""
319 rev_data['revert'] = ""
320 rev_data['reverteds'] = ""
323 # rev.text can be None if the page has no text
326 # if text exists, we'll check for a sha1 and generate one otherwise
332 text_sha1 = sha1(bytes(rev.text, "utf8")).hexdigest()
334 rev_data['sha1'] = text_sha1
336 # TODO rev.bytes doesn't work.. looks like a bug
337 rev_data['text_chars'] = len(rev.text)
339 # generate revert data
340 revert = rev_detector.process(text_sha1, rev.id)
343 rev_data['revert'] = "TRUE"
344 rev_data['reverteds'] = '"' + ",".join([str(x) for x in revert.reverteds]) + '"'
346 rev_data['revert'] = "FALSE"
347 rev_data['reverteds'] = ""
349 # if the fact that the edit was minor can be hidden, this might be an issue
350 rev_data['minor'] = "TRUE" if rev.minor else "FALSE"
352 if not rev.deleted.user:
353 # wrap user-defined editors in quotes for fread
354 rev_data['editor'] = '"' + rev.user.text + '"'
355 rev_data['anon'] = "TRUE" if rev.user.id == None else "FALSE"
358 rev_data['anon'] = ""
359 rev_data['editor'] = ""
361 #if re.match(r'^#redirect \[\[.*\]\]', rev.text, re.I):
366 #TODO missing: additions_size deletions_size
368 # if collapse user was on, lets run that
369 if self.collapse_user:
370 rev_data['collapsed_revs'] = rev.collapsed_revs
372 if self.persist != PersistMethod.none:
374 for k in ["token_revs", "tokens_added", "tokens_removed", "tokens_window"]:
375 old_rev_data[k] = None
378 if self.persist != PersistMethod.legacy:
379 _, tokens_added, tokens_removed = state.update(rev.text, rev.id)
382 _, tokens_added, tokens_removed = state.process(rev.text, rev.id, text_sha1)
384 window.append((rev.id, rev_data, tokens_added, tokens_removed))
386 if len(window) == PERSISTENCE_RADIUS:
387 old_rev_id, old_rev_data, old_tokens_added, old_tokens_removed = window[0]
389 num_token_revs, num_tokens = calculate_persistence(old_tokens_added)
391 old_rev_data["token_revs"] = num_token_revs
392 old_rev_data["tokens_added"] = num_tokens
393 old_rev_data["tokens_removed"] = len(old_tokens_removed)
394 old_rev_data["tokens_window"] = PERSISTENCE_RADIUS-1
396 self.print_rev_data(old_rev_data)
399 self.print_rev_data(rev_data)
403 if self.persist != PersistMethod.none:
404 # print out metadata for the last RADIUS revisions
405 for i, item in enumerate(window):
406 # if the window was full, we've already printed item 0
407 if len(window) == PERSISTENCE_RADIUS and i == 0:
410 rev_id, rev_data, tokens_added, tokens_removed = item
411 num_token_revs, num_tokens = calculate_persistence(tokens_added)
413 rev_data["token_revs"] = num_token_revs
414 rev_data["tokens_added"] = num_tokens
415 rev_data["tokens_removed"] = len(tokens_removed)
416 rev_data["tokens_window"] = len(window)-(i+1)
418 self.print_rev_data(rev_data)
422 print("Done: %s revisions and %s pages." % (rev_count, page_count),
425 def print_rev_data(self, rev_data):
426 # if it's the first time through, print the header
428 for field in TO_ENCODE:
429 rev_data[field] = quote(str(rev_data[field]))
431 if not self.printed_header:
432 print("\t".join([str(k) for k in sorted(rev_data.keys())]), file=self.output_file)
433 self.printed_header = True
435 print("\t".join([str(v) for k, v in sorted(rev_data.items())]), file=self.output_file)
438 def open_input_file(input_filename):
439 if re.match(r'.*\.7z$', input_filename):
440 cmd = ["7za", "x", "-so", input_filename, '*']
441 elif re.match(r'.*\.gz$', input_filename):
442 cmd = ["zcat", input_filename]
443 elif re.match(r'.*\.bz2$', input_filename):
444 cmd = ["bzcat", "-dk", input_filename]
447 input_file = Popen(cmd, stdout=PIPE).stdout
449 input_file = open(input_filename, 'r')
453 def open_output_file(input_filename):
454 # create a regex that creates the output filename
455 output_filename = re.sub(r'\.(7z|gz|bz2)?$', '', input_filename)
456 output_filename = re.sub(r'\.xml', '', output_filename)
457 output_filename = output_filename + ".tsv"
458 output_file = open(output_filename, "w")
462 parser = argparse.ArgumentParser(description='Parse MediaWiki XML database dumps into tab delimitted data.')
464 # arguments for the input direction
465 parser.add_argument('dumpfiles', metavar="DUMPFILE", nargs="*", type=str,
466 help="Filename of the compressed or uncompressed XML database dump. If absent, we'll look for content on stdin and output on stdout.")
468 parser.add_argument('-o', '--output-dir', metavar='DIR', dest='output_dir', type=str, nargs=1,
469 help="Directory for output files.")
471 parser.add_argument('-s', '--stdout', dest="stdout", action="store_true",
472 help="Write output to standard out (do not create dump file)")
474 parser.add_argument('--collapse-user', dest="collapse_user", action="store_true",
475 help="Operate only on the final revision made by user a user within all sequences of consecutive edits made by a user. This can be useful for addressing issues with text persistence measures.")
477 parser.add_argument('-p', '--persistence', dest="persist", default=None, const='', type=str, choices = ['','segment','sequence','legacy'], nargs='?',
478 help="Compute and report measures of content persistent: (1) persistent token revisions, (2) tokens added, and (3) number of revision used in computing the first measure. This may by slow. The defualt is -p=sequence, which uses the same algorithm as in the past, but with improvements to wikitext parsing. Use -p=legacy for old behavior used in older research projects. Use -p=segment for advanced persistence calculation method that is robust to content moves, but prone to bugs, and slower.")
480 parser.add_argument('-u', '--url-encode', dest="urlencode", action="store_true",
481 help="Output url encoded text strings. This works around some data issues like newlines in editor names. In the future it may be used to output other text data.")
483 parser.add_argument('-n', '--namespace-include', dest="namespace_filter", type=int, action='append',
484 help="Id number of namspace to include. Can be specified more than once.")
486 parser.add_argument('-rr',
488 dest="revert_radius",
492 help="Number of edits to check when looking for reverts (default: 15)")
494 parser.add_argument('-RP', '--revision-pattern', dest="regex_match_revision", default=None, type=str, action='append',
495 help="The regular expression to search for in revision text. The regex must be surrounded by quotes.")
497 parser.add_argument('-RPl', '--revision-pattern-label', dest="regex_revision_label", default=None, type=str, action='append',
498 help="The label for the outputted column based on matching the regex in revision text.")
500 parser.add_argument('-CP', '--comment-pattern', dest="regex_match_comment", default=None, type=str, action='append',
501 help="The regular expression to search for in comments of revisions.")
503 parser.add_argument('-CPl', '--comment-pattern-label', dest="regex_comment_label", default=None, type=str, action='append',
504 help="The label for the outputted column based on matching the regex in comments.")
506 args = parser.parse_args()
508 # set persistence method
510 if args.persist is None:
511 persist = PersistMethod.none
512 elif args.persist == "segment":
513 persist = PersistMethod.segment
514 elif args.persist == "legacy":
515 persist = PersistMethod.legacy
517 persist = PersistMethod.sequence
519 if args.namespace_filter is not None:
520 namespaces = args.namespace_filter
524 if len(args.dumpfiles) > 0:
525 for filename in args.dumpfiles:
526 input_file = open_input_file(filename)
528 # open directory for output
530 output_dir = args.output_dir[0]
534 print("Processing file: %s" % filename, file=sys.stderr)
537 output_file = sys.stdout
539 filename = os.path.join(output_dir, os.path.basename(filename))
540 output_file = open_output_file(filename)
542 wikiq = WikiqParser(input_file,
544 collapse_user=args.collapse_user,
546 urlencode=args.urlencode,
547 namespaces=namespaces,
548 revert_radius=args.revert_radius,
549 regex_match_revision = args.regex_match_revision,
550 regex_revision_label = args.regex_revision_label,
551 regex_match_comment = args.regex_match_comment,
552 regex_comment_label = args.regex_comment_label)
560 wikiq = WikiqParser(sys.stdin,
562 collapse_user=args.collapse_user,
564 #persist_legacy=args.persist_legacy,
565 urlencode=args.urlencode,
566 namespaces=namespaces,
567 revert_radius=args.revert_radius,
568 regex_match_revision = args.regex_match_revision,
569 regex_revision_label = args.regex_revision_label,
570 regex_match_comment = args.regex_match_comment,
571 regex_comment_label = args.regex_comment_label)
575 # stop_words = "a,able,about,across,after,all,almost,also,am,among,an,and,any,are,as,at,be,because,been,but,by,can,cannot,could,dear,did,do,does,either,else,ever,every,for,from,get,got,had,has,have,he,her,hers,him,his,how,however,i,if,in,into,is,it,its,just,least,let,like,likely,may,me,might,most,must,my,neither,no,nor,not,of,off,often,on,only,or,other,our,own,rather,said,say,says,she,should,since,so,some,than,that,the,their,them,then,there,these,they,this,tis,to,too,twas,us,wants,was,we,were,what,when,where,which,while,who,whom,why,will,with,would,yet,you,your"
576 # stop_words = stop_words.split(",")