diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..54d54b5 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,107 @@ +repos: + + +- repo: https://github.com/pre-commit/mirrors-autopep8 + rev: v1.5.4 + hooks: + - id: autopep8 + description: "Applies a subset of autopep8's fixes to Python code" + args: + - --in-place + # enable max aggresiveness because all the errors are hand picked + - -aaa + - --max-line-length + - "100" + - --select + # autopep8 is used for structure rather than style here, which is why only a few error codes are + # selected + - W292,E502,E266,E402,E713,E714,E721,E722,E731 + + +- repo: https://github.com/psf/black + rev: 20.8b1 + hooks: + - id: black + description: "Runs black over Python code" + args: ["--target-version", "py38", "--line-length", "100"] + + +- repo: https://github.com/myint/docformatter + rev: v1.3.1 + hooks: + - id: docformatter + name: docformatter + description: 'Formats docstrings to follow PEP 257.' + entry: docformatter + language: python + + +- repo: https://github.com/PyCQA/pydocstyle.git + rev: 5.1.1 + hooks: + - id: pydocstyle + name: pydocstyle + description: "Runs pydocstyle over Python code" + entry: pydocstyle + language: python + language_version: python3 + exclude: "setup.py" + types: [python] + # -e enables more verbose explainations of errors + args: ["-e", "--convention=numpy", "--add-ignore", "D100,D101,D102,D103,D104,D105,D106,D107"] + + +- repo: https://github.com/humitos/mirrors-autoflake + rev: v1.3 + hooks: + - id: autoflake + name: autoflake + description: "Runs autoflake over Python code" + entry: autoflake + language: python + language_version: python3 + types: [python] + args: ["--in-place", "--remove-unused-variables", "--remove-all-unused-imports", "--remove-duplicate-keys", "--exclude", "__init__.py"] + + +- repo: https://github.com/PyCQA/flake8 + rev: 3.8.3 + hooks: + - id: flake8 + name: flake8 + description: "Runs flake8 over Python code" + entry: flake8 + language: python + language_version: python3 + types: [python] + # http://flake8.pycqa.org/en/latest/user/error-codes.html + # F631 assertion test is a tuple, which are always True + # F721 doctest syntax error + # F821 undefined name + # F822 undefined name in __all__ + # F823 local variable name … referenced before assignment + # F901 raise NotImplemented should be raise NotImplementedError + # "We also report one extra error: E999. We report E999 when we fail to compile a file into an + # Abstract Syntax Tree for the plugins that require it." + args: ["--select=F631,F721,F821,F822,F823,E901,E999"] + + +- repo: https://github.com/pre-commit/mirrors-mypy + rev: v0.782 + hooks: + - id: mypy + description: "Runs mypy over Python code" + args: + - "--disallow-untyped-defs" + - "--no-implicit-optional" + - "--ignore-missing-imports" + - "--warn-redundant-casts" + - "--warn-unused-ignores" + - "--show-error-context" + + +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v3.2.0 + hooks: + - id: check-json + - id: trailing-whitespace diff --git a/AUTHORS.md b/AUTHORS.md new file mode 100644 index 0000000..e6520c0 --- /dev/null +++ b/AUTHORS.md @@ -0,0 +1,3 @@ +# Authors + +* Gabriel Altay (github: galtay) \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..82d7d7e --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +kwnlp@kensho.com. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..537f21e --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,20 @@ +# Contributing + +Thank you for taking the time to contribute to this project! + +## Code of Conduct + +This project adheres to the Contributor Covenant [code of conduct](CODE_OF_CONDUCT.md). +By participating, you are expected to uphold this code. +Please report unacceptable behavior to kwnlp@kensho.com. + +## Style Guide + +Please install [pre-commit](pre-commit.com) before making any pull requests. This will +run a suite of linters, type checkers, and auto formatters on any code you wish to +contribute to the project. + +```bash +pip install pre-commit +pre-commit install +``` diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4a16f18 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2020-present Kensho Technologies, LLC. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..4ecd62a --- /dev/null +++ b/README.md @@ -0,0 +1,109 @@ +# Kensho Wikimedia for Natural Language Processing - SQL Dump Parser + +kwnlp_sql_parser is a Python package for parsing [Wikipedia SQL dumps](https://meta.wikimedia.org/wiki/Data_dumps/Dump_format) into CSVs. + + +# Quick Install (Requires Python >= 3.6) + +```bash +pip install kwnlp-sql-parser +``` + +# Examples + +## Basic Usage + +To convert a Wikipedia MySQL/MariaDB dump into a CSV file, use the `to_csv` method of the `WikipediaSqlDump` class. By default, the CSV file is created in the current directory and includes all of the columns and rows in the SQL dump file. + +```python +import pandas as pd +from kwnlp_sql_parser import WikipediaSqlDump +file_path = "/path/to/data/enwiki-20200920-page.sql.gz" +wsd = WikipediaSqlDump(file_path) +wsd.to_csv() +``` + +```python +df = pd.read_csv("enwiki-20200920-page.csv", keep_default_na=False, na_values=[""]) +print(df.head()) +``` + +```bash + page_id page_namespace page_title page_restrictions page_is_redirect page_is_new page_random page_touched page_links_updated page_latest page_len page_content_model page_lang +0 10 0 AccessibleComputing NaN 1 0 0.331671 20200903074851 2.020090e+13 854851586 94 wikitext NaN +1 12 0 Anarchism NaN 0 0 0.786172 20200920023613 2.020092e+13 979267494 88697 wikitext NaN +2 13 0 AfghanistanHistory NaN 1 0 0.062150 20200909184138 2.020091e+13 783865149 90 wikitext NaN +3 14 0 AfghanistanGeography NaN 1 0 0.952234 20200915100945 2.020091e+13 783865160 92 wikitext NaN +4 15 0 AfghanistanPeople NaN 1 0 0.574721 20200917080644 2.020091e+13 783865293 95 wikitext NaN +``` + +See the "Common Issues" section below for an explanation of the pandas read_csv kwargs. + + +## Filtering Rows and Columns + +In some situations, it is convenient to filter the Wikipedia SQL dumps before writing to CSV. For example, one might only be interested in the columns `page_id` and `page_title` for Wikipedia pages that are in the (Main/Article) [namespace](https://en.wikipedia.org/wiki/Wikipedia:Namespace). + +```python +import pandas as pd +from kwnlp_sql_parser import WikipediaSqlDump +file_path = "/path/to/data/enwiki-20200920-page.sql.gz" +wsd = WikipediaSqlDump( + file_path, + keep_column_names=["page_id", "page_title"], + allowlists={"page_namespace": ["0"]}) +wsd.to_csv() +``` + +```python +df = pd.read_csv("enwiki-20200920-page.csv", keep_default_na=False, na_values=[""]) +print(df.head()) +``` + +```bash + page_id page_title +0 10 AccessibleComputing +1 12 Anarchism +2 13 AfghanistanHistory +3 14 AfghanistanGeography +4 15 AfghanistanPeople +``` + +Note that you can also specify `blocklists` instead of `allowlists` if it is more convenient for your use case. + +# Common Issues + +### Not using string values in filters + +All values in the allowlists and blocklists should be strings. + +### Pages with names treated as Null + +Be carefull when reading the CSVs in your chosen software. Some packages will treat the following page titles as null values instead of strings, + +* https://en.wikipedia.org/wiki/NaN +* https://en.wikipedia.org/wiki/Null +* https://en.wikipedia.org/wiki/Na + +In pandas this can be handled by reading in the CSV using, + +```python +df = pd.read_csv("enwiki-20200920-page.csv", keep_default_na=False, na_values=[""]) +``` + + +# Supported Tables + +* https://www.mediawiki.org/wiki/Manual:Category_table +* https://www.mediawiki.org/wiki/Manual:Categorylinks_table +* https://www.mediawiki.org/wiki/Manual:Page_table +* https://www.mediawiki.org/wiki/Manual:Page_props_table +* https://www.mediawiki.org/wiki/Manual:Pagelinks_table +* https://www.mediawiki.org/wiki/Manual:Redirect_table + + +# License + +Licensed under the Apache 2.0 License. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +Copyright 2020-present Kensho Technologies, LLC. The present date is determined by the timestamp of the most recent commit in the repository. diff --git a/kwnlp_sql_parser/__init__.py b/kwnlp_sql_parser/__init__.py new file mode 100644 index 0000000..9cbb420 --- /dev/null +++ b/kwnlp_sql_parser/__init__.py @@ -0,0 +1,6 @@ +__version__ = "0.0.1" + +from kwnlp_sql_parser.wp_sql_dump import WikipediaSqlCsvDialect +from kwnlp_sql_parser.wp_sql_dump import WikipediaSqlDump +from kwnlp_sql_parser.wp_sql_patterns import WikipediaSqlColumn +from kwnlp_sql_parser.wp_sql_patterns import WikipediaSqlRow diff --git a/kwnlp_sql_parser/wp_sql_dump.py b/kwnlp_sql_parser/wp_sql_dump.py new file mode 100644 index 0000000..4bbdfb1 --- /dev/null +++ b/kwnlp_sql_parser/wp_sql_dump.py @@ -0,0 +1,275 @@ +"""Module for parsing Wikipedia SQL dumps.""" + +import csv +import gzip +import logging +import os +import re +import sys +import time +from contextlib import contextmanager +from typing import Any, Dict, IO, Iterator, List, Match, Optional, Tuple + +from kwnlp_sql_parser.wp_sql_patterns import ( + WikipediaSqlRow, + return_columns_tuple, + return_valid_table_names, +) + +logger = logging.getLogger(__name__) + + +class WikipediaSqlCsvDialect(csv.Dialect): + """Default dialect for CSV output. + + See the Python CSV docs for more info + https://docs.python.org/3/library/csv.html#csv-fmt-params. + """ + + delimiter = "," + doublequote = True + escapechar = None + lineterminator = "\r\n" + quotechar = '"' + quoting = csv.QUOTE_MINIMAL + skipinitialspace = False + strict = False + + +class WikipediaSqlDump: + """Class for Wikipedia SQL table dump files. + + Represents a SQL dump file of the form, + + * :code:`WIKI-YYYYMMDD-TABLE_NAME.sql.gz` + + This class can handle compressed gz files or uncompressed sql files. + + Wikimedia provides documentation on the tables these dumps come from, + + * https://www.mediawiki.org/wiki/Manual:Category_table + * https://www.mediawiki.org/wiki/Manual:Redirect_table + * https://www.mediawiki.org/wiki/Manual:Page_props_table + * https://www.mediawiki.org/wiki/Manual:Page_table + * https://www.mediawiki.org/wiki/Manual:Categorylinks_table + * https://www.mediawiki.org/wiki/Manual:Pagelinks_table + + Parameters + ---------- + filename + The wikipedia SQL dump file name + keep_column_names + names of columns to keep in CSV output. if None then keep all. + allowlists + maps column names to allowlists of column values. if None then keep all. + blocklists + maps column names to blocklists of column values. if None then keep all. + """ + + _VALID_TABLE_NAMES = return_valid_table_names() + _FILE_PATTERN = re.compile( + r""" + (?P # basename group + (?P[a-z]+) # wikipedia language prefix + - # literal hyphen + (?P\d{8}) # year/month/day (e.g. 20180720) + - # literal hyphen + (?P[\w_]+) # name of wikimedia table + ) # close basname group + (?P\.sql(\.gz)?) # extension + """, + re.VERBOSE, + ) + + def __init__( + self, + filename: str, + keep_column_names: Optional[Tuple[str, ...]] = None, + allowlists: Optional[Dict[str, Tuple[str, ...]]] = None, + blocklists: Optional[Dict[str, Tuple[str, ...]]] = None, + ) -> None: + + self.filename = filename + + match_groupdict = self._get_regex_groupdict_from_filename(filename) + self.wiki = match_groupdict["wiki"] + self.yyyymmdd = match_groupdict["yyyymmdd"] + self.compressed = match_groupdict["extension"] == ".sql.gz" + self.basename = match_groupdict["basename"] + self.table_name = match_groupdict["table_name"] + if self.table_name not in self._VALID_TABLE_NAMES: + raise NotImplementedError(f"table name {self.table_name} not implemented") + + self.sqlrow = WikipediaSqlRow( + return_columns_tuple(self.table_name), + keep_column_names=keep_column_names, + allowlists=allowlists, + blocklists=blocklists, + ) + self.compiled_row_pattern = self.sqlrow.build_compiled_pattern() + logger.info(self) + + def _get_regex_groupdict_from_filename(self, filename: str) -> Dict[str, str]: + if not isinstance(filename, str): + raise ValueError("filename must be a string") + basename = os.path.basename(filename) + match = re.match(self._FILE_PATTERN, basename) + if match: + return match.groupdict() + else: + raise ValueError( + f"basename of filename {basename} does not match the required " + 'pattern "WIKI-YYYYMMDD-TABLE_NAME.sql{.gz}' + ) + + @contextmanager + def _open_dump_file(self) -> Iterator[IO[Any]]: + """Context manager that opens compressed/uncompressed dump files. + + It is important to open the file in binary mode even if it is + not compressed. This allows us to handle decoding in one place. + """ + if self.compressed: + with gzip.open(self.filename, mode="rb") as fp: + yield fp + else: + with open(self.filename, mode="rb") as fp: + yield fp + + def iter_lines(self) -> Iterator[str]: + """Generate lines from SQL dump file.""" + with self._open_dump_file() as fp: + for linebytes in fp: + yield linebytes.decode(encoding="utf-8", errors="ignore") + + def iter_matched_rows(self) -> Iterator[Tuple[int, int, Match]]: + """Generate regex row matches from SQL dump file. + + Each yield statement includes a match as well as line_num and + insert_into_num. line_num indicates the line number of the SQL + dump file the match was on and insert_into_num indicates the + insert_into statement the match was in. Both are 1-based + counters. + """ + line_num = 0 + insert_into_num = 0 + for line in self.iter_lines(): + line_num += 1 + + # we are only interested in lines that insert data + if not line.startswith("INSERT INTO"): + logger.debug(" skipping non INSERT row") + continue + else: + insert_into_num += 1 + + # iterate over regex matches (i.e. database rows) in this line + for match in re.finditer(self.compiled_row_pattern, line): + yield line_num, insert_into_num, match + + def get_csv_header(self) -> Tuple[str, ...]: + """Return CSV header.""" + return self.sqlrow.keep_column_names + + def to_csv( + self, + outfile: Optional[str] = None, + dialect: Optional[csv.Dialect] = None, + max_lines: int = sys.maxsize, + batch_size: int = 500_000, + ) -> None: + """Produce a CSV file from a SQL dump. + + Parameters + ---------- + outfile + CSV output file name + dialect + CSV output format. defaults to :py:class:`WikipediaSqlCsvDialect` + max_lines + maximum number of INSERT statements to parse + batch_size + number of rows to write to the CSV at one time + + + Wikipedia MySQL dumps contain a series of SQL commands that populate a MySql + database. The bulk of the files are `INSERT` commands followed by several + thousand values (for example) + + .. code:: sql + + INSERT INTO `pagelinks` VALUES (9773,0,'!',0),(15154,0,'!',0), ... + """ + count_row_matches = 0 + count_written = 0 + count_skipped_bc_ab_lists = 0 + + if outfile is None: + outfile = f"{self.basename}.csv" + if dialect is None: + dialect = WikipediaSqlCsvDialect() + + logger.info(f"writing CSV to {outfile}") + batch_matches = [] # type: List[Match] + t_start = time.time() + t_batch_start = time.time() + + with open(outfile, "w") as fp: + + csv_writer = csv.writer(fp, dialect=dialect) + csv_writer.writerow(self.get_csv_header()) + + # iterate over regex row matches + # line_num indicates which line of the SQL dump we're on + for line_num, insert_into_num, match in self.iter_matched_rows(): + + # return early if we need to + if insert_into_num > max_lines: + batch_rows = self.sqlrow.csv_rows_from_matches(batch_matches) + csv_writer.writerows(batch_rows) + return + + # collect matches + count_row_matches += 1 + batch_matches.append(match) + + # write batch to disk + if len(batch_matches) >= batch_size: + + batch_rows = self.sqlrow.csv_rows_from_matches(batch_matches) + csv_writer.writerows(batch_rows) + + count_written += len(batch_rows) + count_skipped_bc_ab_lists += len(batch_matches) - len(batch_rows) + batch_matches = [] + + t_batch_end = time.time() + t_batch_end - t_batch_start + dt_all = t_batch_end - t_start + rows_per_sec = count_row_matches / dt_all + logger.info( + f" time elapsed: {dt_all:.2f}s, " + f" rows matched per second: {rows_per_sec:.2f}, " + f" rows matched: {count_row_matches}, " + f" rows written to disk: {count_written}, " + f" rows skipped b/c allow/block lists: {count_skipped_bc_ab_lists}" + ) + t_batch_start = time.time() + + # write any lingering rows + batch_rows = self.sqlrow.csv_rows_from_matches(batch_matches) + csv_writer.writerows(batch_rows) + + def __str__(self) -> str: + return ( + f"{self.__class__}(" + f"filename={self.filename}, " + f"yyyymmdd={self.yyyymmdd}, " + f"compressed={self.compressed}, " + f"basename={self.basename}, " + f"table_name={self.table_name}, " + f"sqlrow={self.sqlrow})" + ) + + def __repr__(self) -> str: + return self.__str__() diff --git a/kwnlp_sql_parser/wp_sql_patterns.py b/kwnlp_sql_parser/wp_sql_patterns.py new file mode 100644 index 0000000..2b8af73 --- /dev/null +++ b/kwnlp_sql_parser/wp_sql_patterns.py @@ -0,0 +1,401 @@ +"""Regex patterns and classes for parsing Wikipedia SQL dumps.""" + +import re +from typing import Dict, FrozenSet, List, Match, Optional, Pattern, Tuple, Union + +# Core regex patterns +# --------------------------------------- + +# A string surrounded by single quotes that has backslash escaped text inside +# see https://stackoverflow.com/questions/430759/regex-for-managing-escaped-characters-for-items-like-string-literals +# for the theoretical underpinning +ESCAPED_STRING = re.compile( + r""" + ' # opening single quote + [^'\\]* # normal block = 0 or more characters that are not single quote or backslash + ( # begin group for (escaped normal*)* + \\. # escaped anything + [^'\\]* # normal block + )* # end (escaped normal*)* group + ' # closing single quote + """, + re.VERBOSE, +) + +DIGIT = re.compile( + r""" + (-|\+)? # optional minus or plus sign + \d # integer + """, + re.VERBOSE, +) + +DIGITS = re.compile( + r""" + (-|\+)? # optional minus or plus sign + \d+ # 1 or more integers + """, + re.VERBOSE, +) + +QUOTED_DIGITS = re.compile( + r""" + ' # opening single quote + (-|\+)? # optional minus or plus sign + \d+ # 1 or more integers + ' # closing single quote + """, + re.VERBOSE, +) + +FLOAT = re.compile( + r""" + (-|\+)? # optional minus or plus sign + \d* # 0 or more integers + \.? # optional period + \d* # 0 or more integers + """, + re.VERBOSE, +) + +SINGLE_QUOTED_ANYTHING = re.compile( + r""" + ' # opening single quote + .*? # non greedy match anything + ' # closing single quote + """, + re.VERBOSE, +) + + +# Custom column regex patterns +# --------------------------------------- +CL_TIMESTAMP = re.compile( + r""" + ' # opening single quiote + \d{4}-\d{2}-\d{2}[ ]\d{2}:\d{2}:\d{2} # yyyy-mm-dd hh:mm:ss pattern + ' # closing single quote + """, + re.VERBOSE, +) + +CL_TYPE = re.compile( + r""" + ' # opening single quote + (page|subcat|file) # explicit values we accept + ' # closing single quote + """, + re.VERBOSE, +) + + +class WikipediaSqlColumn: + + _SINGLE_QUOTE = "'" + _DOUBLE_QUOTE = '"' + _SINGLE_BACKSLASH = "\\" + _DOUBLE_BACKSLASH = "\\\\" + _BACKSLASH_SINGLE_QUOTE = "\\'" + _BACKSLASH_DOUBLE_QUOTE = '\\"' + + def __init__( + self, + name: str, + pattern: Pattern, + nullable: bool = False, + unquote: bool = False, + unescape: bool = False, + ): + """Wikipedia SQL Column. + + Fixed description of a single column in one of the Wikipedia SQL dumps. + + Parameters + ---------- + name + the name of the column + pattern + a compiled regex pattern to match the column + nullable + True if the column allows NULL + unquote + True if we want to remove outer quotes before writing to CSV + unescape + True if we want to unescape before writing to CSV + """ + self.name = name + self.pattern = pattern + self.nullable = nullable + self.unquote = unquote + self.unescape = unescape + + def build_pattern(self) -> str: + """Return a regex with one named group equal to the column name.""" + if self.nullable: + return "(?P<{}>NULL|({}))".format(self.name, self.pattern.pattern) + else: + return "(?P<{}>{})".format(self.name, self.pattern.pattern) + + def _unescape_string(self, string: str) -> str: + """Remove backslash escape characters from a string.""" + s1 = string.replace(self._BACKSLASH_SINGLE_QUOTE, self._SINGLE_QUOTE) + s2 = s1.replace(self._BACKSLASH_DOUBLE_QUOTE, self._DOUBLE_QUOTE) + s3 = s2.replace(self._DOUBLE_BACKSLASH, self._SINGLE_BACKSLASH) + return s3 + + def _unquote_string(self, string: str) -> str: + """Remove outer single quotes.""" + if string.startswith(self._SINGLE_QUOTE): + string = string[1:] + if string.endswith(self._SINGLE_QUOTE): + string = string[:-1] + return string + + def clean_string(self, string: str) -> str: + """Optionally apply unquote and unescape functions to a string.""" + if self.nullable and string == "NULL": + string = "" + if self.unquote: + string = self._unquote_string(string) + if self.unescape: + string = self._unescape_string(string) + return string + + def __str__(self) -> str: + return ( + f"{self.__class__}(name={self.name}, nullable={self.nullable}, " + f"unquote={self.unquote}, unescape={self.unescape})" + ) + + def __repr__(self) -> str: + return self.__str__() + + +class WikipediaSqlRow: + def __init__( + self, + columns: Tuple[WikipediaSqlColumn, ...], + keep_column_names: Optional[Tuple[str, ...]] = None, + allowlists: Optional[Dict[str, Tuple[str, ...]]] = None, + blocklists: Optional[Dict[str, Tuple[str, ...]]] = None, + ): + """Wikipedia SQL Row. + + Compose a series of column descriptions to create a row description. + + Parameters + ---------- + columns + all columns in the row + keep_column_names + names of columns to keep in CSV output. if None then keep all. + allowlists + maps column names to allowlists of column values. if None then keep all. + blocklists + maps column names to blocklists of column values. if None then keep all. + """ + self.columns = columns + self.all_column_names = tuple([col.name for col in self.columns]) + self.keep_column_names = self._get_keep_column_names(keep_column_names) + self.keep_columns = tuple( + [column for column in self.columns if column.name in self.keep_column_names] + ) + self.allowlists = self._get_allowlists(allowlists) + self.blocklists = self._get_blocklists(blocklists) + + def _get_keep_column_names( + self, keep_column_names: Union[None, Tuple[str, ...]] + ) -> Tuple[str, ...]: + """Validate and reorder. + + Validate column names and put keep_column_names into + all_column_names order. + """ + if keep_column_names is None: + return tuple(self.all_column_names) + + # check for duplicates in `keep_column_names` + if len(keep_column_names) > len(set(keep_column_names)): + raise ValueError(f"keep column names includes duplicates {keep_column_names}") + + # check for bad column names in `keep_column_names` + bad_col_names = set(keep_column_names) - set(self.all_column_names) + if len(bad_col_names) > 0: + raise ValueError( + f"keep column names includes {bad_col_names} which are not valid " + f"column names for this table ({self.all_column_names})" + ) + + # put `keep_column_names` in the same order as `all_column_names` + return tuple([name for name in self.all_column_names if name in keep_column_names]) + + def _get_allowlists( + self, allowlists: Union[None, Dict[str, Tuple[str, ...]]] + ) -> Dict[str, FrozenSet[str]]: + """Validate input and create sets of acceptable values.""" + if allowlists is None: + return {} + + allowsets = {} + for name, allowed in allowlists.items(): + if name not in self.all_column_names: + raise ValueError( + f"column name {name} in allowlists is not a valid column " + f"name: {self.all_column_names}" + ) + allowsets[name] = frozenset(allowed) + return allowsets + + def _get_blocklists( + self, blocklists: Union[None, Dict[str, Tuple[str, ...]]] + ) -> Dict[str, FrozenSet[str]]: + """Validate input and create sets of blocked values.""" + if blocklists is None: + return {} + + blocksets = {} + for name, blocked in blocklists.items(): + if name not in self.all_column_names: + raise ValueError( + f"column name {name} in blocklists is not a valid column " + f"name: {self.all_column_names}" + ) + blocksets[name] = frozenset(blocked) + return blocksets + + def build_pattern(self) -> str: + """Build row regex by joining column regex patterns.""" + rowpat = ",".join([column.build_pattern() for column in self.columns]) + rowpat = 4 * " " + rowpat # for consistent indentation when printing + rowpat = "\\(\n" + rowpat + "\n\\)" # add opening ( and closing ) + return rowpat + + def build_compiled_pattern(self) -> Pattern: + """Build compiled row regex.""" + return re.compile(self.build_pattern(), re.VERBOSE) + + def _clean_groupdict(self, groupdict: Dict[str, str]) -> Dict[str, str]: + """Apply column specific cleaning to each match group.""" + return {column.name: column.clean_string(groupdict[column.name]) for column in self.columns} + + def _passes_allowlist_groupdict(self, groupdict: Dict[str, str]) -> bool: + """Check groupdict against allowlists.""" + return all( + [groupdict[column_name] in allowed for column_name, allowed in self.allowlists.items()] + ) + + def _passes_blocklist_groupdict(self, groupdict: Dict[str, str]) -> bool: + """Check groupdict against blocklists.""" + return all( + [ + groupdict[column_name] not in blocked + for column_name, blocked in self.blocklists.items() + ] + ) + + def _filter_groupdict(self, groupdict: Dict[str, str]) -> Dict[str, str]: + """Remove columns we don't want to keep.""" + return {column_name: groupdict[column_name] for column_name in self.keep_column_names} + + def _csv_row_from_groupdict(self, groupdict: Dict[str, str]) -> Tuple[str, ...]: + """Produce tuple in column order from groupdict.""" + return tuple([groupdict[column_name] for column_name in self.keep_column_names]) + + def csv_rows_from_matches(self, matches: List[Match]) -> List[Tuple[str, ...]]: + """Generate CSV row tuples from an iterable of match objects.""" + csv_rows = [] + for match in matches: + match_groupdict = match.groupdict() + clean_groupdict = self._clean_groupdict(match_groupdict) + keep_row_allowlist = self._passes_allowlist_groupdict(clean_groupdict) + keep_row_blocklist = self._passes_blocklist_groupdict(clean_groupdict) + if keep_row_allowlist and keep_row_blocklist: + filtered_groupdict = self._filter_groupdict(clean_groupdict) + csv_rows.append(self._csv_row_from_groupdict(filtered_groupdict)) + return csv_rows + + def __str__(self) -> str: + return ( + f"{self.__class__}(" + f"columns={self.columns}, " + f"keep_column_names={self.keep_column_names}, " + f"allowlists={self.allowlists}, " + f"blocklists={self.blocklists})" + ) + + def __repr__(self) -> str: + return self.__str__() + + +_TABLE_COLUMN_PATTERNS = { + "category": ( + WikipediaSqlColumn("cat_id", DIGITS), + WikipediaSqlColumn("cat_title", ESCAPED_STRING, unquote=True, unescape=True), + WikipediaSqlColumn("cat_pages", DIGITS), + WikipediaSqlColumn("cat_subcats", DIGITS), + WikipediaSqlColumn("cat_files", DIGITS), + ), + "redirect": ( + WikipediaSqlColumn("rd_from", DIGITS), + WikipediaSqlColumn("rd_namespace", DIGITS), + WikipediaSqlColumn("rd_title", ESCAPED_STRING, unquote=True, unescape=True), + WikipediaSqlColumn( + "rd_interwiki", ESCAPED_STRING, nullable=True, unquote=True, unescape=True + ), + WikipediaSqlColumn( + "rd_fragment", ESCAPED_STRING, nullable=True, unquote=True, unescape=True + ), + ), + "page_props": ( + WikipediaSqlColumn("pp_page", DIGITS), + WikipediaSqlColumn("pp_propname", SINGLE_QUOTED_ANYTHING, unquote=True), + WikipediaSqlColumn("pp_value", ESCAPED_STRING, unquote=True, unescape=True), + WikipediaSqlColumn("pp_sortkey", DIGITS, nullable=True), + ), + "page": ( + WikipediaSqlColumn("page_id", DIGITS), + WikipediaSqlColumn("page_namespace", DIGITS), + WikipediaSqlColumn("page_title", ESCAPED_STRING, unquote=True, unescape=True), + WikipediaSqlColumn("page_restrictions", ESCAPED_STRING, unquote=True, unescape=True), + WikipediaSqlColumn("page_is_redirect", DIGITS), + WikipediaSqlColumn("page_is_new", DIGITS), + WikipediaSqlColumn("page_random", FLOAT), + WikipediaSqlColumn("page_touched", QUOTED_DIGITS, unquote=True), + WikipediaSqlColumn("page_links_updated", QUOTED_DIGITS, nullable=True, unquote=True), + WikipediaSqlColumn("page_latest", DIGITS), + WikipediaSqlColumn("page_len", DIGITS), + WikipediaSqlColumn( + "page_content_model", + ESCAPED_STRING, + nullable=True, + unquote=True, + unescape=True, + ), + WikipediaSqlColumn("page_lang", ESCAPED_STRING, nullable=True, unquote=True, unescape=True), + ), + "categorylinks": ( + WikipediaSqlColumn("cl_from", DIGITS), + WikipediaSqlColumn("cl_to", ESCAPED_STRING, unquote=True, unescape=True), + WikipediaSqlColumn("cl_sortkey", SINGLE_QUOTED_ANYTHING), + WikipediaSqlColumn("cl_timestamp", CL_TIMESTAMP, unquote=True), + WikipediaSqlColumn("cl_sortkey_prefix", ESCAPED_STRING, unquote=True, unescape=True), + WikipediaSqlColumn("cl_collation", ESCAPED_STRING, unquote=True, unescape=True), + WikipediaSqlColumn("cl_type", CL_TYPE, unquote=True), + ), + "pagelinks": ( + WikipediaSqlColumn("pl_from", DIGITS), + WikipediaSqlColumn("pl_namespace", DIGITS), + WikipediaSqlColumn("pl_title", ESCAPED_STRING, unquote=True, unescape=True), + WikipediaSqlColumn("pl_from_namespace", DIGITS), + ), +} # type: Dict[str, Tuple[WikipediaSqlColumn, ...]] + + +def return_valid_table_names() -> Tuple[str, ...]: + """Get a tuple of valid table names.""" + return tuple(_TABLE_COLUMN_PATTERNS.keys()) + + +def return_columns_tuple(table_name: str) -> Tuple[WikipediaSqlColumn, ...]: + """Get a tuple of column patterns for a table.""" + return _TABLE_COLUMN_PATTERNS[table_name] diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..afff94d --- /dev/null +++ b/setup.py @@ -0,0 +1,66 @@ +import codecs +import os + +from setuptools import find_packages, setup + + +# single sourcing package version strategy taken from +# https://packaging.python.org/guides/single-sourcing-package-version + + +PACKAGE_NAME = "kwnlp_sql_parser" + + +def read_file(filename: str) -> str: + """Read package file as text to get name and version.""" + here = os.path.abspath(os.path.dirname(__file__)) + with codecs.open(os.path.join(here, PACKAGE_NAME, filename), "r") as f: + return f.read() + + +def find_version() -> str: + """Only define version in one place.""" + for line in read_file("__init__.py").splitlines(): + if line.startswith("__version__"): + delim = '"' if '"' in line else "'" + return line.split(delim)[1] + else: + raise RuntimeError("Unable to find version string.") + + +def find_long_description() -> str: + """Return the content of the README.rst file.""" + return read_file("../README.md") + + +setup( + name=PACKAGE_NAME, + version=find_version(), + description="Utility for parsing Wikipedia SQL dumps into CSVs.", + long_description=find_long_description(), + long_description_content_type="text/markdown", + url="https://github.com/kensho-technologies/kwnlp-sql-parser", + author="Kensho Technologies LLC.", + author_email="kwnlp@kensho.com", + license="Apache 2.0", + packages=find_packages(exclude=["tests*"]), + package_data={"": []}, + install_requires=[], + extras_require={ + "dev": [ + "pre-commit", + ] + }, + classifiers=[ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + ], + keywords="wikipedia sql dump open data", + python_requires=">=3.6", +)