from dataclasses import dataclass from io import BufferedReader from pathlib import Path from typing import List import lxml.etree from datetime import datetime class MediaWikiRevision: id: int parentid: int timestamp: str contributor: str comment: str model: str format: str text: str def __init__( self, id, parentid, timestamp, contributor, comment, model, format, text ): self.id = id self.parentid = parentid self.timestamp = datetime.fromisoformat(timestamp.replace("Z", "+00:00")) self.contributor = contributor self.comment = comment self.model = model self.format = format self.text = text @dataclass class MediaWikiPage: title: str id: int revisions: List[MediaWikiRevision] text: str class MediaWikiDump: sitename: str baseurl: str engine: str pages: List[MediaWikiPage] def __init__(self, source: Path | str | BufferedReader) -> None: if not hasattr(source, "read"): source = open(source, "rb") root = lxml.etree.parse(source).getroot() ns = {"mw": "http://www.mediawiki.org/xml/export-0.11/"} siteinfo = root.find("./mw:siteinfo", ns) self.sitename = siteinfo.find("./mw:sitename", ns).text self.baseurl = siteinfo.find("./mw:base", ns).text self.engine = siteinfo.find("./mw:generator", ns).text self.pages = [] ids = [] for page in root.findall("./mw:page", ns): title = page.find("./mw:title", ns).text id = int(page.find("./mw:id", ns).text) if id in ids: continue revisions: List[MediaWikiRevision] = [] for revision in page.findall("./mw:revision", ns): revid = int(revision.find("./mw:id", ns).text) parentid = int(revision.find("./mw:parentid", ns).text) timestamp = revision.find("./mw:timestamp", ns).text contributor = revision.find("./mw:contributor", ns).text comment = revision.find("./mw:comment", ns) comment = comment.text if comment is not None else "" model = revision.find("./mw:model", ns).text format = revision.find("./mw:format", ns).text text = revision.find("./mw:text", ns).text text = text if text is not None else "" revisions.append( MediaWikiRevision( revid, parentid, timestamp, contributor, comment, model, format, text, ) ) revisions.sort(key=lambda r: r.timestamp) revisions.reverse() text = revisions[0].text ids.append(id) self.pages.append(MediaWikiPage(title, id, revisions, text)) pass