X-Git-Url: https://code.communitydata.science/mediawiki_dump_tools.git/blobdiff_plain/b1bea09ad63a3b651e25b0bc36b31e9b7d6a8553..b124f9c7c891b8b98441ef1b185ba1a1a4a32179:/wikiq diff --git a/wikiq b/wikiq index 1a951e8..be90a8b 100755 --- a/wikiq +++ b/wikiq @@ -9,6 +9,7 @@ import sys import os, os.path import re from datetime import datetime,timezone +import json from subprocess import Popen, PIPE from collections import deque @@ -26,9 +27,10 @@ from deltas import SequenceMatcher from deltas import SegmentMatcher import dataclasses as dc -from dataclasses import dataclass, make_dataclass +from dataclasses import dataclass import pyarrow as pa import pyarrow.parquet as pq +from itertools import chain class PersistMethod: none = 0 @@ -133,9 +135,18 @@ class WikiqPage(): return next(self.__revisions) +""" +A RegexPair is defined by a regular expression (pattern) and a label. +The pattern can include capture groups. If it does then each capture group will have a resulting column in the output. +If the pattern does not include a capture group, then only one output column will result. +""" class RegexPair(object): def __init__(self, pattern, label): - self.pattern = re.compile(pattern) + self.pattern = pattern + + if type(self.pattern) is str: + self.pattern = re.compile(pattern) + self.label = label self.has_groups = bool(self.pattern.groupindex) if self.has_groups: @@ -191,7 +202,7 @@ class RegexPair(object): if type(content) in(str, bytes): if self.pattern.search(content) is not None: m = self.pattern.findall(content) - temp_dict[self.label] = ', '.join(m) + temp_dict[self.label] = m else: temp_dict[self.label] = None @@ -201,6 +212,22 @@ class RegexPair(object): return rev_data +""" + +We used to use a dictionary to collect fields for the output. +Now we use dataclasses. Compared to a dictionary, this should help: +- prevent some bugs +- make it easier to output parquet data. +- use class attribute '.' syntax instead of dictionary syntax. +- improve support for tooling (autocomplete, type hints) +- use type information to define formatting rules + +Depending on the parameters passed into Wikiq, the output schema can be different. +Therefore, we need to end up constructing a dataclass with the correct output schema. +It also needs to have the correct pyarrow schema so we can write parquet files. + +The RevDataBase type has all the fields that will be output no matter how wikiq is invoked. +""" @dataclass() class RevDataBase(): revid: int @@ -218,27 +245,35 @@ class RevDataBase(): editor: str = None anon: bool = None + # toggles url encoding. this isn't a dataclass field since it doesn't have a type annotation urlencode = False + + # defines pyarrow schema. + # each field in the data class needs an entry in this array. + # the names should match and be in the same order. + # this isn't a dataclass field since it doesn't have a type annotation pa_schema_fields = [ pa.field("revid", pa.int64()), - pa.field("date_time",pa.timestamp('ms')), + pa.field("date_time", pa.timestamp('ms')), pa.field("articleid",pa.int64()), pa.field("editorid",pa.int64()), pa.field("title",pa.string()), pa.field("namespace",pa.int32()), pa.field("deleted",pa.bool_()), - pa.field("test_chars",pa.int32()), + pa.field("text_chars",pa.int32()), pa.field("revert",pa.bool_()), pa.field("reverteds",pa.list_(pa.int64())), pa.field("sha1",pa.string()), pa.field("minor",pa.bool_()), pa.field("editor",pa.string()), - pa.field("anon",pa.bool_()) + pa.field("anon",pa.bool_()), ] + # pyarrow is a columnar format, so most of the work happens in the flush_parquet_buffer function def to_pyarrow(self): return dc.astuple(self) + # logic to convert each field into the wikiq tsv format goes here. def to_tsv_row(self): row = [] @@ -262,6 +297,9 @@ class RevDataBase(): elif f.type == list[int]: row.append('"' + ",".join([str(x) for x in val]) + '"') + elif f.type == list[str]: + row.append('"' + ",".join([(x) for x in val]) + '"') + elif f.type == str: if self.urlencode and f.name in TO_ENCODE: row.append(quote(str(val))) @@ -275,12 +313,26 @@ class RevDataBase(): def header_row(self): return '\t'.join(map(lambda f: f.name, dc.fields(self))) +""" + +If collapse=True we'll use a RevDataCollapse dataclass. +This class inherits from RevDataBase. This means that it has all the same fields and functions. + +It just adds a new field and updates the pyarrow schema. + +""" @dataclass() class RevDataCollapse(RevDataBase): collapsed_revs:int = None + pa_collapsed_revs_schema = pa.field('collapsed_revs',pa.int64()) pa_schema_fields = RevDataBase.pa_schema_fields + [pa_collapsed_revs_schema] +""" + +If persistence data is to be computed we'll need the fields added by RevDataPersistence. + +""" @dataclass() class RevDataPersistence(RevDataBase): token_revs:int = None @@ -296,12 +348,18 @@ class RevDataPersistence(RevDataBase): pa_schema_fields = RevDataBase.pa_schema_fields + pa_persistence_schema_fields +""" +class RevDataCollapsePersistence uses multiple inheritence to make a class that has both persistence and collapse fields. + +""" @dataclass() class RevDataCollapsePersistence(RevDataCollapse, RevDataPersistence): pa_schema_fields = RevDataCollapse.pa_schema_fields + RevDataPersistence.pa_persistence_schema_fields + + class WikiqParser(): - 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, output_parquet=True, parquet_buffer_size=2000): + 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, output_parquet=True, parquet_buffer_size=2000, siteinfo_file=None): """ Parameters: persist : what persistence method to use. Takes a PersistMethod value @@ -313,7 +371,7 @@ class WikiqParser(): self.namespaces = [] self.urlencode = urlencode self.revert_radius = revert_radius - + if namespaces is not None: self.namespace_filter = set(namespaces) else: @@ -323,6 +381,27 @@ class WikiqParser(): self.regex_revision_pairs = self.make_matchmake_pairs(regex_match_revision, regex_revision_label) self.regex_comment_pairs = self.make_matchmake_pairs(regex_match_comment, regex_comment_label) + if siteinfo_file is not None: + siteinfo = open_siteinfo(siteinfo_file) + siteinfo = json.loads(siteinfo.read()) + + magicwords = siteinfo.get('query').get('magicwords') + + if magicwords: + redirect_config = list(filter(lambda obj: obj.get("name") == "redirect", magicwords)) + redirect_aliases = chain(* map(lambda obj: obj.get("aliases"), redirect_config)) + redirect_aliases = list(map(lambda s: s.lstrip('#'), redirect_aliases)) + redirect_aliases.append('REDIRECT') # just in case + + # this regular expression is copied from pywikibot + pattern = '(?:' + '|'.join(redirect_aliases) + ')' + redirect_regex = re.compile(r'\s*#{pattern}\s*:?\s*\[\[(.+?)(?:\|.*?)?\]\]' + .format(pattern=pattern), re.IGNORECASE | re.DOTALL) + + self.regex_revision_pairs.extend(self.make_matchmake_pairs([redirect_regex], ["redirect"])) + + # This is where we set the type for revdata. + if self.collapse_user is True: if self.persist == PersistMethod.none: revdata_type = RevDataCollapse @@ -333,16 +412,23 @@ class WikiqParser(): else: revdata_type = RevDataBase + # if there are regex fields, we need to add them to the revdata type. regex_fields = [(field.name, list[str], dc.field(default=None)) for field in self.regex_schemas] - self.revdata_type = make_dataclass('RevData_Parser', - fields=regex_fields, - bases=(revdata_type,)) + # make_dataclass is a function that defines a new dataclass type. + # here we extend the type we have already chosen and add the regular expression types + self.revdata_type = dc.make_dataclass('RevData_Parser', + fields=regex_fields, + bases=(revdata_type,)) + # we also need to make sure that we have the right pyarrow schema self.revdata_type.pa_schema_fields = revdata_type.pa_schema_fields + self.regex_schemas self.revdata_type.urlencode = self.urlencode + self.schema = pa.schema(self.revdata_type.pa_schema_fields) + + # here we initialize the variables we need for output. if output_parquet is True: self.output_parquet = True self.pq_writer = None @@ -372,12 +458,12 @@ class WikiqParser(): else: sys.exit('Each regular expression *must* come with a corresponding label and vice versa.') - def matchmake(self, rev, rev_data): - rev_data = self.matchmake_revision(rev.text, rev_data) + def matchmake_revision(self, rev, rev_data): + rev_data = self.matchmake_text(rev.text, rev_data) rev_data = self.matchmake_comment(rev.comment, rev_data) return rev_data - def matchmake_revision(self, text, rev_data): + def matchmake_text(self, text, rev_data): return self.matchmake_pairs(text, rev_data, self.regex_revision_pairs) def matchmake_comment(self, comment, rev_data): @@ -420,7 +506,6 @@ class WikiqParser(): page_count = 0 rev_count = 0 - # Iterate through pages for page in dump: namespace = page.namespace if page.namespace is not None else self.__get_namespace_from_title(page.title) @@ -451,6 +536,7 @@ class WikiqParser(): # Iterate through a page's revisions for rev in page: + # create a new data object instead of a dictionary. rev_data = self.revdata_type(revid = rev.id, date_time = datetime.fromtimestamp(rev.timestamp.unix(), tz=timezone.utc), articleid = page.id, @@ -460,7 +546,7 @@ class WikiqParser(): namespace = namespace ) - rev_data = self.matchmake(rev, rev_data) + rev_data = self.matchmake_revision(rev, rev_data) if not rev.deleted.text: # rev.text can be None if the page has no text @@ -476,7 +562,7 @@ class WikiqParser(): rev_data.sha1 = text_sha1 # TODO rev.bytes doesn't work.. looks like a bug - rev_data.text_chars = len(rev.text) + rev_data.text_chars = len(rev.text) # generate revert data revert = rev_detector.process(text_sha1, rev.id) @@ -495,11 +581,6 @@ class WikiqParser(): rev_data.editor = rev.user.text rev_data.anon = rev.user.id is None - #if re.match(r'^#redirect \[\[.*\]\]', rev.text, re.I): - # redirect = True - #else: - # redirect = False - #TODO missing: additions_size deletions_size # if collapse user was on, lets run that @@ -556,6 +637,7 @@ class WikiqParser(): print("Done: %s revisions and %s pages." % (rev_count, page_count), file=sys.stderr) + # remember to flush the parquet_buffer if we're done if self.output_parquet is True: self.flush_parquet_buffer() self.pq_writer.close() @@ -564,6 +646,10 @@ class WikiqParser(): self.output_file.close() + """ + For performance reasons it's better to write parquet in batches instead of one row at a time. + So this function just puts the data on a buffer. If the buffer is full, then it gets flushed (written). + """ def write_parquet_row(self, rev_data): padata = rev_data.to_pyarrow() self.parquet_buffer.append(padata) @@ -572,10 +658,16 @@ class WikiqParser(): self.flush_parquet_buffer() + """ + Function that actually writes data to the parquet file. + It needs to transpose the data from row-by-row to column-by-column + """ def flush_parquet_buffer(self): - schema = pa.schema(self.revdata_type.pa_schema_fields) - def row_to_col(rg, types): + """ + Returns the pyarrow table that we'll write + """ + def rows_to_table(rg, schema): cols = [] first = rg[0] for col in first: @@ -586,18 +678,20 @@ class WikiqParser(): cols[j].append(row[j]) arrays = [] - for col, typ in zip(cols, types): + for col, typ in zip(cols, schema.types): arrays.append(pa.array(col, typ)) - return arrays + return pa.Table.from_arrays(arrays, schema=schema) - outtable = pa.Table.from_arrays(row_to_col(self.parquet_buffer, schema.types), schema=schema) + outtable = rows_to_table(self.parquet_buffer, self.schema) if self.pq_writer is None: - self.pq_writer = pq.ParquetWriter(self.output_file, schema, flavor='spark') + self.pq_writer = pq.ParquetWriter(self.output_file, self.schema, flavor='spark') self.pq_writer.write_table(outtable) self.parquet_buffer = [] + # depending on if we are configured to write tsv or parquet, we'll call a different function. def print_rev_data(self, rev_data): + if self.output_parquet is False: printfunc = self.write_tsv_row else: @@ -613,6 +707,21 @@ class WikiqParser(): line = rev_data.to_tsv_row() print(line, file=self.output_file) +def open_siteinfo(siteinfo_file): + if re.match(r'.*\.7z$', siteinfo_file): + cmd = ["7za", "x", "-so", siteinfo_file, "*.json"] + elif re.match(r'.*\.gz$', siteinfo_file): + cmd = ["zcat", siteinfo_file] + elif re.match(r'.*\.bz2$', siteinfo_file): + cmd = ["bzcat", "-dk", siteinfo_file] + + try: + input_file = Popen(cmd, stdout=PIPE).stdout + except NameError: + input_file = open(siteinfo_file, 'r') + + return input_file + def open_input_file(input_filename): if re.match(r'.*\.7z$', input_filename): @@ -688,6 +797,11 @@ parser.add_argument('-CP', '--comment-pattern', dest="regex_match_comment", defa parser.add_argument('-CPl', '--comment-pattern-label', dest="regex_comment_label", default=None, type=str, action='append', help="The label for the outputted column based on matching the regex in comments.") +parser.add_argument('--SI', '--siteinfo', dest="siteinfo", default=None, type=str, + help="Path to archive containing siteinfo json. This is required for resolving redirects") + + + args = parser.parse_args() @@ -730,6 +844,7 @@ if len(args.dumpfiles) > 0: filename = os.path.join(output_dir, os.path.basename(filename)) output_file = get_output_filename(filename, parquet = output_parquet) + print(args.siteinfo, file=sys.stderr) wikiq = WikiqParser(input_file, output_file, collapse_user=args.collapse_user, @@ -741,7 +856,8 @@ if len(args.dumpfiles) > 0: regex_revision_label = args.regex_revision_label, regex_match_comment = args.regex_match_comment, regex_comment_label = args.regex_comment_label, - output_parquet=output_parquet) + output_parquet=output_parquet, + siteinfo_file = args.siteinfo) wikiq.process() @@ -760,7 +876,8 @@ else: regex_match_revision = args.regex_match_revision, regex_revision_label = args.regex_revision_label, regex_match_comment = args.regex_match_comment, - regex_comment_label = args.regex_comment_label) + regex_comment_label = args.regex_comment_label, + siteinfo_file = args.siteinfo) wikiq.process()