sea_wiki / sea_loader_batched /wiki_loader.py
sabilmakbar's picture
Add New Lang (#5)
a91c8a9
raw
history blame
42.9 kB
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
#
# 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.
# Lint as: python3
"""Wikipedia dataset containing cleaned articles of all languages."""
import os
import sys
import bz2
import codecs
import json
import re
import xml.etree.cElementTree as etree
from urllib.parse import quote
import datasets
logger = datasets.logging.get_logger(__name__)
logger.setLevel(datasets.logging.DEBUG)
_CITATION = """\
@ONLINE {wikidump,
author = {Wikimedia Foundation},
title = {Wikimedia Downloads},
url = {https://dumps.wikimedia.org}
}
"""
_DESCRIPTION = """\
Wikipedia dataset containing cleaned articles of all languages.
The datasets are built from the Wikipedia dump
(https://dumps.wikimedia.org/) with one split per language. Each example
contains the content of one full Wikipedia article with cleaning to strip
markdown and unwanted sections (references, etc.).
"""
_LICENSE = (
"This work is licensed under the Creative Commons Attribution-ShareAlike "
"3.0 Unported License. To view a copy of this license, visit "
"http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to "
"Creative Commons, PO Box 1866, Mountain View, CA 94042, USA."
)
# Source: https://en.wikipedia.org/wiki/List_of_Wikipedias (accessed 3/1/2019)
# Removed because no articles: hz.
WIKIPEDIA_LANGUAGES = [
"aa",
"ab",
"ace",
"ady",
"af",
"ak",
"als",
"am",
"an",
"ang",
"ar",
"arc",
"arz",
"as",
"ast",
"atj",
"av",
"ay",
"az",
"azb",
"ba",
"bar",
"bat-smg",
"bcl",
"be",
"be-x-old",
"bg",
"bh",
"bi",
"bjn",
"bm",
"bn",
"bo",
"bpy",
"br",
"bs",
"bug",
"bxr",
"ca",
"cbk-zam",
"cdo",
"ce",
"ceb",
"ch",
"cho",
"chr",
"chy",
"ckb",
"co",
"cr",
"crh",
"cs",
"csb",
"cu",
"cv",
"cy",
"da",
"de",
"din",
"diq",
"dsb",
"dty",
"dv",
"dz",
"ee",
"el",
"eml",
"en",
"eo",
"es",
"et",
"eu",
"ext",
"fa",
"ff",
"fi",
"fiu-vro",
"fj",
"fo",
"fr",
"frp",
"frr",
"fur",
"fy",
"ga",
"gag",
"gan",
"gd",
"gl",
"glk",
"gn",
"gom",
"gor",
"got",
"gu",
"gv",
"ha",
"hak",
"haw",
"he",
"hi",
"hif",
"ho",
"hr",
"hsb",
"ht",
"hu",
"hy",
"ia",
"id",
"ie",
"ig",
"ii",
"ik",
"ilo",
"inh",
"io",
"is",
"it",
"iu",
"ja",
"jam",
"jbo",
"jv",
"ka",
"kaa",
"kab",
"kbd",
"kbp",
"kg",
"ki",
"kj",
"kk",
"kl",
"km",
"kn",
"ko",
"koi",
"krc",
"ks",
"ksh",
"ku",
"kv",
"kw",
"ky",
"la",
"lad",
"lb",
"lbe",
"lez",
"lfn",
"lg",
"li",
"lij",
"lmo",
"ln",
"lo",
"lrc",
"lt",
"ltg",
"lv",
"mai",
"map-bms",
"mdf",
"mg",
"mh",
"mhr",
"mi",
"min",
"mk",
"ml",
"mn",
"mr",
"mrj",
"ms",
"mt",
"mus",
"mwl",
"my",
"myv",
"mzn",
"na",
"nah",
"nap",
"nds",
"nds-nl",
"ne",
"new",
"ng",
"nl",
"nn",
"no",
"nov",
"nrm",
"nso",
"nv",
"ny",
"oc",
"olo",
"om",
"or",
"os",
"pa",
"pag",
"pam",
"pap",
"pcd",
"pdc",
"pfl",
"pi",
"pih",
"pl",
"pms",
"pnb",
"pnt",
"ps",
"pt",
"qu",
"rm",
"rmy",
"rn",
"ro",
"roa-rup",
"roa-tara",
"ru",
"rue",
"rw",
"sa",
"sah",
"sat",
"sc",
"scn",
"sco",
"sd",
"se",
"sg",
"sh",
"si",
"simple",
"sk",
"sl",
"sm",
"sn",
"so",
"sq",
"sr",
"srn",
"ss",
"st",
"stq",
"su",
"sv",
"sw",
"szl",
"ta",
"tcy",
"te",
"tet",
"tg",
"th",
"ti",
"tk",
"tl",
"tn",
"to",
"tpi",
"tr",
"ts",
"tt",
"tum",
"tw",
"ty",
"tyv",
"udm",
"ug",
"uk",
"ur",
"uz",
"ve",
"vec",
"vep",
"vi",
"vls",
"vo",
"wa",
"war",
"wo",
"wuu",
"xal",
"xh",
"xmf",
"yi",
"yo",
"za",
"zea",
"zh",
"zh-classical",
"zh-min-nan",
"zh-yue",
"zu",
]
# Source: for each Wikipedia language code (example shown for "ab"), aliases for namespaces -2 and 6 accessed via this API call:
# https://ab.wikipedia.org/w/api.php?action=query&meta=siteinfo&siprop=namespacealiases|namespaces&format=json&formatversion=2 (accessed 12/21/2021)
MEDIA_ALIASES = {
"ab": ["Медиа", "Файл", "Афаил", "Амедиа", "Изображение"],
"ace": ["Beureukaih", "Gambar", "Alat", "Berkas"],
"ady": ["Медиа"],
"af": ["Lêer", "Beeld"],
"als": ["Medium", "Datei", "Bild"],
"am": ["ፋይል", "ስዕል"],
"an": ["Imachen", "Imagen"],
"ang": ["Ymele", "Biliþ"],
"ar": ["ميديا", "صورة", "وسائط", "ملف"],
"arc": ["ܠܦܦܐ", "ܡܝܕܝܐ"],
"arz": ["ميديا", "صورة", "وسائط", "ملف"],
"as": ["চিত্ৰ", "चित्र", "চিত্র", "মাধ্যম"],
"ast": ["Imaxen", "Ficheru", "Imaxe", "Archivu", "Imagen", "Medios"],
"atj": ["Tipatcimoctakewin", "Natisinahikaniwoc"],
"av": ["Медиа", "Файл", "Изображение"],
"ay": ["Medio", "Archivo", "Imagen"],
"az": ["Mediya", "Şəkil", "Fayl"],
"azb": ["رسانه", "تصویر", "مدیا", "فایل", "رسانه‌ای"],
"ba": ["Медиа", "Рәсем", "Файл", "Изображение"],
"bar": ["Medium", "Datei", "Bild"],
"bat-smg": ["Vaizdas", "Medėjė", "Abruozdielis"],
"bcl": ["Medio", "Ladawan"],
"be": ["Мультымедыя", "Файл", "Выява"],
"be-x-old": ["Мэдыя", "Файл", "Выява"],
"bg": ["Медия", "Файл", "Картинка"],
"bh": ["मीडिया", "चित्र"],
"bjn": ["Barakas", "Gambar", "Berkas"],
"bm": ["Média", "Fichier"],
"bn": ["চিত্র", "মিডিয়া"],
"bpy": ["ছবি", "মিডিয়া"],
"br": ["Skeudenn", "Restr"],
"bs": ["Mediji", "Slika", "Datoteka", "Medija"],
"bug": ["Gambar", "Berkas"],
"bxr": ["Файл", "Меди", "Изображение"],
"ca": ["Fitxer", "Imatge"],
"cbk-zam": ["Medio", "Archivo", "Imagen"],
"cdo": ["文件", "媒體", "圖像", "檔案"],
"ce": ["Хlум", "Медиа", "Сурт", "Файл", "Медйа", "Изображение"],
"ceb": ["Payl", "Medya", "Imahen"],
"ch": ["Litratu"],
"ckb": ["میدیا", "پەڕگە"],
"co": ["Immagine"],
"crh": ["Медиа", "Resim", "Файл", "Fayl", "Ресим"],
"cs": ["Soubor", "Média", "Obrázok"],
"csb": ["Òbrôzk", "Grafika"],
"cu": ["Видъ", "Ви́дъ", "Дѣло", "Срѣдьства"],
"cv": ["Медиа", "Ӳкерчĕк", "Изображение"],
"cy": ["Delwedd"],
"da": ["Billede", "Fil"],
"de": ["Medium", "Datei", "Bild"],
"din": ["Ciɛl", "Apamduööt"],
"diq": ["Medya", "Dosya"],
"dsb": ["Wobraz", "Dataja", "Bild", "Medija"],
"dty": ["चित्र", "मिडिया"],
"dv": ["ފައިލު", "މީޑިއާ", "ފައިލް"],
"el": ["Εικόνα", "Αρχείο", "Μέσο", "Μέσον"],
"eml": ["Immagine"],
"eo": ["Dosiero", "Aŭdvidaĵo"],
"es": ["Medio", "Archivo", "Imagen"],
"et": ["Pilt", "Fail", "Meedia"],
"eu": ["Irudi", "Fitxategi"],
"ext": ["Archivu", "Imagen", "Mediu"],
"fa": ["رسانه", "تصویر", "مدیا", "پرونده", "رسانه‌ای"],
"ff": ["Média", "Fichier"],
"fi": ["Kuva", "Tiedosto"],
"fiu-vro": ["Pilt", "Meediä"],
"fo": ["Miðil", "Mynd"],
"fr": ["Média", "Fichier"],
"frp": ["Émâge", "Fichiér", "Mèdia"],
"frr": ["Medium", "Datei", "Bild"],
"fur": ["Immagine", "Figure"],
"fy": ["Ofbyld"],
"ga": ["Íomhá", "Meán"],
"gag": ["Mediya", "Medya", "Resim", "Dosya", "Dosye"],
"gan": ["媒体文件", "文件", "文檔", "档案", "媒體", "图像", "圖像", "媒体", "檔案"],
"gd": ["Faidhle", "Meadhan"],
"gl": ["Imaxe", "Ficheiro", "Arquivo", "Imagem"],
"glk": ["رسانه", "تصویر", "پرونده", "فاىل", "رسانه‌ای", "مديا"],
"gn": ["Medio", "Imagen", "Ta'ãnga"],
"gom": ["माध्यम", "मिडिया", "फायल"],
"gor": ["Gambar", "Berkas"],
"got": ["𐍆𐌴𐌹𐌻𐌰"],
"gu": ["દ્રશ્ય-શ્રાવ્ય (મિડિયા)", "દ્રશ્ય-શ્રાવ્ય_(મિડિયા)", "ચિત્ર"],
"gv": ["Coadan", "Meanyn"],
"hak": ["文件", "媒體", "圖像", "檔案"],
"haw": ["Kiʻi", "Waihona", "Pāpaho"],
"he": ["תמונה", "קו", "מדיה", "קובץ"],
"hi": ["मीडिया", "चित्र"],
"hif": ["file", "saadhan"],
"hr": ["Mediji", "DT", "Slika", "F", "Datoteka"],
"hsb": ["Wobraz", "Dataja", "Bild"],
"ht": ["Imaj", "Fichye", "Medya"],
"hu": ["Kép", "Fájl", "Média"],
"hy": ["Պատկեր", "Մեդիա"],
"ia": ["Imagine", "Multimedia"],
"id": ["Gambar", "Berkas"],
"ig": ["Nká", "Midia", "Usòrò", "Ákwúkwó orünotu", "Ákwúkwó_orünotu"],
"ii": ["媒体文件", "文件", "档案", "图像", "媒体"],
"ilo": ["Midia", "Papeles"],
"inh": ["Медиа", "Файл", "Изображение"],
"io": ["Imajo", "Arkivo"],
"is": ["Miðill", "Mynd"],
"it": ["Immagine"],
"ja": ["メディア", "ファイル", "画像"],
"jbo": ["velsku", "datnyvei"],
"jv": ["Barkas", "Medhia", "Gambar", "Médhia"],
"ka": ["მედია", "სურათი", "ფაილი"],
"kaa": ["Swret", "Таспа", "سۋرەت", "Taspa", "Su'wret", "Сурет", "تاسپا"],
"kab": ["Tugna"],
"kbd": ["Медиа", "Файл"],
"kbp": ["Média", "Fichier"],
"kg": ["Fisye"],
"kk": ["Swret", "سۋرەت", "Таспа", "Taspa", "Сурет", "تاسپا"],
"kl": ["Billede", "Fiileq", "Fil"],
"km": ["ឯកសារ", "រូបភាព", "មេឌា", "មីឌា"],
"kn": ["ಚಿತ್ರ", "ಮೀಡಿಯ"],
"ko": ["미디어", "파일", "그림"],
"koi": ["Медиа", "Файл", "Изображение"],
"krc": ["Медиа", "Файл", "Изображение"],
"ks": ["میڈیا", "فَیِل"],
"ksh": ["Beld", "Meedije", "Medie", "Belld", "Medium", "Datei", "Meedijum", "Bild"],
"ku": ["میدیا", "پەڕگە", "Medya", "Wêne"],
"kv": ["Медиа", "Файл", "Изображение"],
"kw": ["Restren"],
"ky": ["Медиа", "Файл"],
"la": ["Imago", "Fasciculus"],
"lad": ["Dossia", "Medya", "Archivo", "Dosya", "Imagen", "Meddia"],
"lb": ["Fichier", "Bild"],
"lbe": ["Медиа", "Сурат", "Изображение"],
"lez": ["Медиа", "Mediya", "Файл", "Şəkil", "Изображение"],
"lfn": ["Fix"],
"li": ["Afbeelding", "Plaetje", "Aafbeilding"],
"lij": ["Immaggine", "Immagine"],
"lmo": ["Immagine", "Imàjine", "Archivi"],
"ln": ["Média", "Fichier"],
"lo": ["ສື່ອ", "ສື່", "ຮູບ"],
"lrc": ["رسانه", "تصویر", "رسانه‌ای", "جانیا", "أسگ", "ڤارئسگأر"],
"lt": ["Vaizdas", "Medija"],
"ltg": ["Medeja", "Fails"],
"lv": ["Attēls"],
"mai": ["मेडिया", "फाइल"],
"map-bms": ["Barkas", "Medhia", "Gambar", "Médhia"],
"mdf": ["Медиа", "Няйф", "Изображение"],
"mg": ["Rakitra", "Sary", "Média"],
"mhr": ["Медиа", "Файл", "Изображение"],
"min": ["Gambar", "Berkas"],
"mk": ["Податотека", "Медија", "Медиум", "Слика"],
"ml": ["പ്രമാണം", "ചി", "മീഡിയ", "പ്ര", "ചിത്രം"],
"mn": ["Медиа", "Файл", "Зураг"],
"mr": ["चित्र", "मिडिया"],
"mrj": ["Медиа", "Файл", "Изображение"],
"ms": ["Fail", "Imej"],
"mt": ["Midja", "Medja", "Stampa"],
"mwl": ["Multimédia", "Fexeiro", "Ficheiro", "Arquivo", "Imagem"],
"my": ["ဖိုင်", "မီဒီယာ"],
"myv": ["Медия", "Артовкс", "Изображение"],
"mzn": ["رسانه", "تصویر", "مه‌دیا", "مدیا", "پرونده", "رسانه‌ای"],
"nah": ["Mēdiatl", "Īxiptli", "Imagen"],
"nap": ["Fiùra", "Immagine"],
"nds": ["Datei", "Bild"],
"nds-nl": ["Ofbeelding", "Afbeelding", "Bestaand"],
"ne": ["मीडिया", "चित्र"],
"new": ["किपा", "माध्यम"],
"nl": ["Bestand", "Afbeelding"],
"nn": ["Fil", "Bilde", "Filpeikar"],
"no": ["Fil", "Medium", "Bilde"],
"nov": [],
"nrm": ["Média", "Fichier"],
"nso": ["Seswantšho"],
"nv": ["Eʼelyaaígíí"],
"oc": ["Imatge", "Fichièr", "Mèdia"],
"olo": ["Kuva", "Medii", "Failu"],
"or": ["ମାଧ୍ୟମ", "ଫାଇଲ"],
"os": ["Ныв", "Медиа", "Файл", "Изображение"],
"pa": ["ਤਸਵੀਰ", "ਮੀਡੀਆ"],
"pcd": ["Média", "Fichier"],
"pdc": ["Medium", "Datei", "Bild", "Feil"],
"pfl": ["Dadai", "Medium", "Datei", "Bild"],
"pi": ["मीडिया", "पटिमा"],
"pl": ["Plik", "Grafika"],
"pms": ["Figura", "Immagine"],
"pnb": ["میڈیا", "تصویر", "فائل"],
"pnt": ["Εικόνα", "Αρχείον", "Εικόναν", "Μέσον"],
"ps": ["انځور", "رسنۍ", "دوتنه"],
"pt": ["Multimédia", "Ficheiro", "Arquivo", "Imagem"],
"qu": ["Midya", "Imagen", "Rikcha"],
"rm": ["Multimedia", "Datoteca"],
"rmy": ["Fişier", "Mediya", "Chitro", "Imagine"],
"ro": ["Fişier", "Imagine", "Fișier"],
"roa-rup": ["Fişier", "Imagine", "Fișier"],
"roa-tara": ["Immagine"],
"ru": ["Медиа", "Файл", "Изображение"],
"rue": ["Медіа", "Медиа", "Файл", "Изображение", "Зображення"],
"rw": ["Dosiye", "Itangazamakuru"],
"sa": ["चित्रम्", "माध्यमम्", "सञ्चिका", "माध्यम", "चित्रं"],
"sah": ["Миэдьийэ", "Ойуу", "Билэ", "Изображение"],
"sat": ["ᱨᱮᱫ", "ᱢᱤᱰᱤᱭᱟ"],
"sc": ["Immàgini"],
"scn": ["Immagine", "Mmàggini", "Mèdia"],
"sd": ["عڪس", "ذريعات", "فائل"],
"se": ["Fiila"],
"sg": ["Média", "Fichier"],
"sh": ["Mediji", "Slika", "Медија", "Datoteka", "Medija", "Слика"],
"si": ["රූපය", "මාධ්‍යය", "ගොනුව"],
"sk": ["Súbor", "Obrázok", "Médiá"],
"sl": ["Slika", "Datoteka"],
"sq": ["Figura", "Skeda"],
"sr": ["Датотека", "Medij", "Slika", "Медија", "Datoteka", "Медиј", "Medija", "Слика"],
"srn": ["Afbeelding", "Gefre"],
"stq": ["Bielde", "Bild"],
"su": ["Média", "Gambar"],
"sv": ["Fil", "Bild"],
"sw": ["Faili", "Picha"],
"szl": ["Plik", "Grafika"],
"ta": ["படிமம்", "ஊடகம்"],
"tcy": ["ಮಾದ್ಯಮೊ", "ಫೈಲ್"],
"te": ["ఫైలు", "దస్త్రం", "బొమ్మ", "మీడియా"],
"tet": ["Imajen", "Arquivo", "Imagem"],
"tg": ["Акс", "Медиа"],
"th": ["ไฟล์", "สื่อ", "ภาพ"],
"ti": ["ፋይል", "ሜድያ"],
"tk": ["Faýl"],
"tl": ["Midya", "Talaksan"],
"tpi": ["Fail"],
"tr": ["Medya", "Resim", "Dosya", "Ortam"],
"tt": ["Медиа", "Рәсем", "Файл", "Räsem", "Изображение"],
"ty": ["Média", "Fichier"],
"tyv": ["Медиа", "Файл", "Изображение"],
"udm": ["Медиа", "Файл", "Суред", "Изображение"],
"ug": ["ۋاسىتە", "ھۆججەت"],
"uk": ["Медіа", "Медиа", "Файл", "Изображение", "Зображення"],
"ur": ["میڈیا", "تصویر", "وسیط", "زریعہ", "فائل", "ملف"],
"uz": ["Mediya", "Tasvir", "Fayl"],
"vec": ["Immagine", "Imàjine", "Mèdia"],
"vep": ["Pilt", "Fail"],
"vi": ["Phương_tiện", "Tập_tin", "Hình", "Tập tin", "Phương tiện"],
"vls": ["Afbeelding", "Ofbeeldienge"],
"vo": ["Ragiv", "Magod", "Nünamakanäd"],
"wa": ["Imådje"],
"war": ["Medya", "Fayl", "Paypay"],
"wo": ["Xibaarukaay", "Dencukaay"],
"wuu": ["文件", "档案", "图像", "媒体"],
"xal": ["Аһар", "Боомг", "Изображение", "Зург"],
"xmf": ["მედია", "სურათი", "ფაილი"],
"yi": ["מעדיע", "תמונה", "טעקע", "בילד"],
"yo": ["Fáìlì", "Amóhùnmáwòrán", "Àwòrán"],
"za": ["媒体文件", "文件", "档案", "图像", "媒体"],
"zea": ["Afbeelding", "Plaetje"],
"zh": ["媒体文件", "F", "文件", "媒體", "档案", "图像", "圖像", "媒体", "檔案"],
"zh-classical": ["文件", "媒體", "圖像", "檔案"],
"zh-min-nan": ["tóng-àn", "文件", "媒體", "Mûi-thé", "圖像", "檔案"],
"zh-yue": ["檔", "档", "文件", "图", "媒體", "圖", "档案", "图像", "圖像", "媒体", "檔案"],
}
# Source: for each Wikipedia language code (example shown for "ab"), aliases for namespace 14 accessed via this API call:
# https://ab.wikipedia.org/w/api.php?action=query&meta=siteinfo&siprop=namespacealiases|namespaces&format=json&formatversion=2 (accessed 12/21/2021)
CAT_ALIASES = {
"ab": ["Категория", "Акатегориа"],
"ace": ["Kawan", "Kategori"],
"af": ["Kategorie"],
"ak": ["Nkyekyem"],
"als": ["Kategorie"],
"am": ["መደብ"],
"an": ["Categoría"],
"ang": ["Flocc"],
"ar": ["تصنيف"],
"arc": ["ܣܕܪܐ"],
"arz": ["تصنيف"],
"as": ["CAT", "শ্ৰেণী", "श्रेणी", "শ্রেণী"],
"ast": ["Categoría"],
"atj": ["Tipanictawin"],
"av": ["Категория"],
"ay": ["Categoría"],
"az": ["Kateqoriya"],
"azb": ["بؤلمه"],
"ba": ["Төркөм", "Категория"],
"bar": ["Kategorie"],
"bat-smg": ["Kategorija", "Kateguorėjė"],
"bcl": ["Kategorya"],
"be": ["Катэгорыя"],
"be-x-old": ["Катэгорыя"],
"bg": ["Категория"],
"bh": ["श्रेणी"],
"bjn": ["Tumbung", "Kategori"],
"bm": ["Catégorie"],
"bn": ["বিষয়শ্রেণী", "വിഭാഗം"],
"bpy": ["থাক"],
"br": ["Rummad"],
"bs": ["Kategorija"],
"bug": ["Kategori"],
"bxr": ["Категори", "Категория"],
"ca": ["Categoria"],
"cbk-zam": ["Categoría"],
"cdo": ["分類"],
"ce": ["Категори", "Тоба", "Кадегар"],
"ceb": ["Kategoriya"],
"ch": ["Katigoria"],
"ckb": ["پ", "پۆل"],
"co": ["Categoria"],
"crh": ["Категория", "Kategoriya"],
"cs": ["Kategorie"],
"csb": ["Kategòrëjô"],
"cu": ["Катигорї", "Категория", "Катигорїꙗ"],
"cv": ["Категори"],
"cy": ["Categori"],
"da": ["Kategori"],
"de": ["Kategorie"],
"din": ["Bekätakthook"],
"diq": ["Kategoriye", "Kategori"],
"dsb": ["Kategorija"],
"dty": ["श्रेणी"],
"dv": ["ޤިސްމު"],
"el": ["Κατηγορία"],
"eml": ["Categoria"],
"eo": ["Kategorio"],
"es": ["CAT", "Categoría"],
"et": ["Kategooria"],
"eu": ["Kategoria"],
"ext": ["Categoría", "Categoria"],
"fa": ["رده"],
"ff": ["Catégorie"],
"fi": ["Luokka"],
"fiu-vro": ["Katõgooria"],
"fo": ["Bólkur"],
"fr": ["Catégorie"],
"frp": ["Catègorie"],
"frr": ["Kategorie"],
"fur": ["Categorie"],
"fy": ["Kategory"],
"ga": ["Rang", "Catagóir"],
"gag": ["Kategori", "Kategoriya"],
"gan": ["分類", "分类"],
"gd": ["Roinn-seòrsa"],
"gl": ["Categoría"],
"glk": ["جرگه", "رده"],
"gn": ["Ñemohenda"],
"gom": ["वर्ग", "श्रेणी"],
"gor": ["Dalala"],
"got": ["𐌷𐌰𐌽𐍃𐌰"],
"gu": ["શ્રેણી", "CAT", "શ્રે"],
"gv": ["Ronney"],
"hak": ["分類"],
"haw": ["Māhele"],
"he": ["קטגוריה", "קט"],
"hi": ["श्र", "श्रेणी"],
"hif": ["vibhag"],
"hr": ["CT", "KT", "Kategorija"],
"hsb": ["Kategorija"],
"ht": ["Kategori"],
"hu": ["Kategória"],
"hy": ["Կատեգորիա"],
"ia": ["Categoria"],
"id": ["Kategori"],
"ie": ["Categorie"],
"ig": ["Ébéonọr", "Òtù"],
"ii": ["分类"],
"ilo": ["Kategoria"],
"inh": ["ОагӀат"],
"io": ["Kategorio"],
"is": ["Flokkur"],
"it": ["CAT", "Categoria"],
"ja": ["カテゴリ"],
"jbo": ["klesi"],
"jv": ["Kategori"],
"ka": ["კატეგორია"],
"kaa": ["Sanat", "Kategoriya", "Санат", "سانات"],
"kab": ["Taggayt"],
"kbd": ["Категория", "Категориэ"],
"kbp": ["Catégorie"],
"kg": ["Kalasi"],
"kk": ["Sanat", "Санат", "سانات"],
"kl": ["Sumut_atassuseq", "Kategori", "Sumut atassuseq"],
"km": ["ចំនាត់ថ្នាក់ក្រុម", "ចំណាត់ក្រុម", "ចំណាត់ថ្នាក់ក្រុម"],
"kn": ["ವರ್ಗ"],
"ko": ["분류"],
"koi": ["Категория"],
"krc": ["Категория"],
"ks": ["زٲژ"],
"ksh": ["Saachjropp", "Saachjrop", "Katejori", "Kategorie", "Saachjrupp", "Kattejori", "Sachjrop"],
"ku": ["Kategorî", "پۆل"],
"kv": ["Категория"],
"kw": ["Class", "Klass"],
"ky": ["Категория"],
"la": ["Categoria"],
"lad": ["Kateggoría", "Katēggoría", "Categoría"],
"lb": ["Kategorie"],
"lbe": ["Категория"],
"lez": ["Категория"],
"lfn": ["Categoria"],
"li": ["Categorie", "Kategorie"],
"lij": ["Categorîa", "Categoria"],
"lmo": ["Categuria", "Categoria"],
"ln": ["Catégorie"],
"lo": ["ໝວດ"],
"lrc": ["دأسە"],
"lt": ["Kategorija"],
"ltg": ["Kategoreja"],
"lv": ["Kategorija"],
"mai": ["CA", "श्रेणी"],
"map-bms": ["Kategori"],
"mdf": ["Категорие", "Категория"],
"mg": ["Sokajy", "Catégorie"],
"mhr": ["Категория", "Категорий"],
"min": ["Kategori"],
"mk": ["Категорија"],
"ml": ["വിഭാഗം", "വി", "വർഗ്ഗം", "വ"],
"mn": ["Ангилал"],
"mr": ["वर्ग"],
"mrj": ["Категори", "Категория"],
"ms": ["Kategori"],
"mt": ["Kategorija"],
"mwl": ["Catadorie", "Categoria"],
"my": ["ကဏ္ဍ"],
"myv": ["Категория"],
"mzn": ["رج", "رده"],
"nah": ["Neneuhcāyōtl", "Categoría"],
"nap": ["Categurìa", "Categoria"],
"nds": ["Kategorie"],
"nds-nl": ["Categorie", "Kattegerie", "Kategorie"],
"ne": ["श्रेणी"],
"new": ["पुचः"],
"nl": ["Categorie"],
"nn": ["Kategori"],
"no": ["Kategori"],
"nrm": ["Catégorie"],
"nso": ["Setensele"],
"nv": ["Tʼááłáhági_átʼéego", "Tʼááłáhági átʼéego"],
"oc": ["Categoria"],
"olo": ["Kategourii"],
"or": ["ବିଭାଗ", "ଶ୍ରେଣୀ"],
"os": ["Категори"],
"pa": ["ਸ਼੍ਰੇਣੀ"],
"pcd": ["Catégorie"],
"pdc": ["Abdeeling", "Kategorie"],
"pfl": ["Kadegorie", "Sachgrubb", "Kategorie"],
"pi": ["विभाग"],
"pl": ["Kategoria"],
"pms": ["Categorìa"],
"pnb": ["گٹھ"],
"pnt": ["Κατηγορίαν"],
"ps": ["وېشنيزه"],
"pt": ["Categoria"],
"qu": ["Katiguriya"],
"rm": ["Categoria"],
"rmy": ["Shopni"],
"ro": ["Categorie"],
"roa-rup": ["Categorie"],
"roa-tara": ["Categoria"],
"ru": ["Категория", "К"],
"rue": ["Категория", "Катеґорія"],
"rw": ["Ikiciro"],
"sa": ["वर्गः"],
"sah": ["Категория"],
"sat": ["ᱛᱷᱚᱠ"],
"sc": ["Categoria"],
"scn": ["Catigurìa"],
"sd": ["زمرو"],
"se": ["Kategoriija"],
"sg": ["Catégorie"],
"sh": ["Kategorija", "Категорија"],
"si": ["ප්‍රවර්ගය"],
"sk": ["Kategória"],
"sl": ["Kategorija"],
"sq": ["Kategoria", "Kategori"],
"sr": ["Kategorija", "Категорија"],
"srn": ["Categorie", "Guru"],
"stq": ["Kategorie"],
"su": ["Kategori"],
"sv": ["Kategori"],
"sw": ["Jamii"],
"szl": ["Kategoryjo", "Kategoria"],
"ta": ["பகுப்பு"],
"tcy": ["ವರ್ಗೊ"],
"te": ["వర్గం"],
"tet": ["Kategoría", "Kategoria"],
"tg": ["Гурӯҳ"],
"th": ["หมวดหมู่"],
"ti": ["መደብ"],
"tk": ["Kategoriýa"],
"tl": ["Kategorya", "Kaurian"],
"tpi": ["Grup"],
"tr": ["Kategori", "KAT"],
"tt": ["Төркем", "Törkem", "Категория"],
"ty": ["Catégorie"],
"tyv": ["Аңгылал", "Категория"],
"udm": ["Категория"],
"ug": ["تۈر"],
"uk": ["Категория", "Категорія"],
"ur": ["زمرہ"],
"uz": ["Turkum", "Kategoriya"],
"vec": ["Categoria"],
"vep": ["Kategorii"],
"vi": ["Thể_loại", "Thể loại"],
"vls": ["Categorie"],
"vo": ["Klad"],
"wa": ["Categoreye"],
"war": ["Kaarangay"],
"wo": ["Wàll", "Catégorie"],
"wuu": ["分类"],
"xal": ["Янз", "Әәшл"],
"xmf": ["კატეგორია"],
"yi": ["קאטעגאריע", "קאַטעגאָריע"],
"yo": ["Ẹ̀ka"],
"za": ["分类"],
"zea": ["Categorie"],
"zh": ["分类", "分類", "CAT"],
"zh-classical": ["分類", "CAT"],
"zh-min-nan": ["分類", "Lūi-pia̍t"],
"zh-yue": ["分类", "分類", "类", "類"],
}
_BASE_URL_TMPL = "https://dumps.wikimedia.org/{lang}wiki/{date}/"
_INFO_FILE = "dumpstatus.json"
_VERSION = datasets.Version("2.0.0", "")
_GiB_SIZE_IDENTIFIER = 1.074e+9
class WikipediaConfig(datasets.BuilderConfig):
"""BuilderConfig for Wikipedia."""
def __init__(self, language=None, date=None, version=_VERSION,
split_size:int=_GiB_SIZE_IDENTIFIER, subset_file_to_process:str=":",
force_rerun_split: bool=False, **kwargs):
"""BuilderConfig for Wikipedia.
Args:
language: string, the language code for the Wikipedia dump to use.
date: string, date of the Wikipedia dump in YYYYMMDD format. A list of
available dates can be found at https://dumps.wikimedia.org/enwiki/.
**kwargs: keyword arguments forwarded to super.
"""
super().__init__(
name=f"{date}.{language}",
description=f"Wikipedia dataset for {language}, parsed from {date} dump.",
version=version,
**kwargs,
)
self.date = date
self.language = language
self.split_size = split_size
self.force_rerun_split = force_rerun_split
_subsets = str(subset_file_to_process).split(":")
if len(_subsets) > 2:
raise ValueError(f"Unexpected format of `subset_file_to_process`! Received {subset_file_to_process}!")
elif len(_subsets) == 1:
if _subsets[0] == '':
#take all of the values
self.start_file_split, self.end_file_split = None, None
else:
#force cast into int, will throw an error it it's not
_subset_no = int(_subsets[0])
self.start_file_split, self.end_file_split = _subset_no, _subset_no+1
else:
if list(_subsets) == ['', ''] :
#take all of the values
self.start_file_split, self.end_file_split = None, None
else:
self.start_file_split, self.end_file_split = int(_subsets[0]), int(_subsets[1])+1
_DATE = "20220301"
class Wikipedia(datasets.BeamBasedBuilder):
"""Wikipedia dataset."""
# Use mirror (your.org) to avoid download caps.
BUILDER_CONFIG_CLASS = WikipediaConfig
BUILDER_CONFIGS = [
WikipediaConfig(
language=lang,
date=_DATE,
) # pylint:disable=g-complex-comprehension
for lang in WIKIPEDIA_LANGUAGES
]
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"id": datasets.Value("string"),
"url": datasets.Value("string"),
"title": datasets.Value("string"),
"text": datasets.Value("string"),
}
),
# No default supervised_keys.
supervised_keys=None,
homepage="https://dumps.wikimedia.org",
citation=_CITATION,
)
def _split_generators(self, dl_manager, pipeline):
def _base_url(lang):
return _BASE_URL_TMPL.format(lang=lang.replace("-", "_"), date=self.config.date)
lang = self.config.language
info_url = _base_url(lang) + _INFO_FILE
# Use dictionary since testing mock always returns the same result.
downloaded_files = dl_manager.download_and_extract({"info": info_url})
xml_urls, is_split_xml = [], []
total_bytes = 0
with open(downloaded_files["info"], encoding="utf-8") as f:
dump_info = json.load(f)
multistream_dump_info = dump_info["jobs"]["articlesmultistreamdump"]
assert (
multistream_dump_info["status"] == "done"
), "Specified dump (%s) multistream status is not 'done': %s" % (
_base_url(lang),
multistream_dump_info["status"],
)
for fname, info in multistream_dump_info["files"].items():
if ".xml" not in fname:
continue
if info["size"] > self.config.split_size:
is_split_xml.append(True)
else:
is_split_xml.append(False)
total_bytes += info["size"]
xml_urls.append(_base_url(lang) + fname)
# Use dictionary since testing mock always returns the same result.
downloaded_files = dl_manager.download({"xml": xml_urls})
logger.info("found %s file(s) needs to be splitted", str(sum(is_split_xml)))
downloaded_files = split_bz2_files(downloaded_files, is_split_xml, self.config.split_size, self.config.force_rerun_split)
# filter downloaded paths based on start-end file splits
if self.config.start_file_split is not None and self.config.end_file_split is not None:
_new_files = downloaded_files["xml"][self.config.start_file_split:self.config.end_file_split]
if len(_new_files) == 0:
raise ValueError("The config of file splits resulting in zero file to be processed!")
downloaded_files["xml"] = _new_files
if not pipeline.is_local():
downloaded_files = dl_manager.ship_files_with_pipeline(downloaded_files, pipeline)
return [
datasets.SplitGenerator( # pylint:disable=g-complex-comprehension
name=datasets.Split.TRAIN, gen_kwargs={"filepaths": downloaded_files["xml"], "language": lang}
)
]
def _build_pcollection(self, pipeline, filepaths, language):
"""Build PCollection of examples in the raw (text) form."""
import apache_beam as beam
import mwparserfromhell
def _extract_content(filepath):
"""Extracts article content from a single WikiMedia XML file."""
logger.info("generating examples from = %s", filepath)
with beam.io.filesystems.FileSystems.open(filepath) as f:
f = bz2.BZ2File(filename=f)
# Workaround due to: https://github.com/tensorflow/tensorflow/issues/33563
utf_f = codecs.getreader("utf-8")(f)
context = etree.iterparse(utf_f, events=("end",))
for _unused_event, elem in context:
if not elem.tag.endswith("page"):
continue
namespace = elem.tag[:-4]
title = elem.find(f"./{namespace}title").text
ns = elem.find(f"./{namespace}ns").text
id_ = elem.find(f"./{namespace}id").text
red_ = elem.find(f"./{namespace}redirect")
# Filter pages that are not in the "main" namespace.
if ns != "0":
elem.clear()
continue
raw_content = elem.find(f"./{namespace}revision/{namespace}text").text
elem.clear()
# Filter redirects.
if raw_content is None or red_ is not None:
beam.metrics.Metrics.counter(language, "filtered-redirects").inc()
continue
beam.metrics.Metrics.counter(language, "extracted-examples").inc()
yield (id_, title, raw_content)
def _clean_content(inputs, language):
"""Cleans raw wikicode to extract text."""
id_, title, raw_content = inputs
try:
text = _parse_and_clean_wikicode(raw_content, parser=mwparserfromhell, language=language)
except (mwparserfromhell.parser.ParserError) as e:
beam.metrics.Metrics.counter(language, "parser-error").inc()
logger.error("mwparserfromhell ParseError: %s", e)
return
if not text:
beam.metrics.Metrics.counter(language, "empty-clean-examples").inc()
return
url = _construct_url(title, language)
beam.metrics.Metrics.counter(language, "cleaned-examples").inc()
yield id_, {"id": id_, "url": url, "title": title, "text": text}
return (
pipeline
| "Initialize" >> beam.Create(filepaths)
| "Extract content" >> beam.FlatMap(_extract_content)
| "Distribute" >> beam.transforms.Reshuffle()
| "Clean content" >> beam.FlatMap(_clean_content, language=language)
)
def split_bz2_files(downloaded_files_dict:dict, is_split_xml_identifier:bool,
desired_uncompressed_filesize_per_split:int, force_rerun: bool=False):
assert len(downloaded_files_dict.keys())==1, "Unexpected format of arg `downloaded_files_dict`!"
dict_key = list(downloaded_files_dict.keys())[0]
_dict_value = list(downloaded_files_dict.values())[0]
assert isinstance(_dict_value, list), f"Expected dict value has type of `list`! Received `{type(_dict_value)}!"
def _create_chunk_file(filename: str, filecount: int):
_file_name = f"{filename if not filename.endswith('.xml.bz2') else filename[:-8]}_{str(filecount)}"
return bz2.BZ2File(_file_name, 'w'), _file_name
def _close_and_add_closing_tag(file, is_expected_to_be_opened=True):
if not file.closed:
if not is_expected_to_be_opened:
logger.debug("File isn't closed yet! Closing...")
else:
# file is expected to close, but since this indicates not the end of splitted files,
# add this tag instead
file.write(b'</mediawiki>')
file.close()
def _preempt_file_with_data(file, list_of_data):
for line in list_of_data:
file.write(line)
# inspired from this: https://stackoverflow.com/a/6411933
def _split_data_to_smaller_sizes(filename: str):
"""Extract and split bz2 filenames into smaller ones."""
# Define filename splitted list
split_filename = []
#Define FIle Header Constructor Var
header_list, keep_appending_for_header = [], True
# Define Counters
filecount, line_cnt, text_data_size = 1, 0, 0
# Open Source bz2 for splitting
logger.info("Reading bz2 file %s for splitting", filename)
bzfile = bz2.BZ2File(filename)
#open splitted chunkfile in write mode
chunk_file, chunk_file_name = _create_chunk_file(filename, filecount)
logger.info("Creating new splitted filename %s", chunk_file_name)
for line in bzfile:
chunk_file.write(line)
# generate headers that is usable for next files, since in wikidump, all split files have same format in first few lines
if keep_appending_for_header:
header_list.append(line)
#deactivate when siteinfo is found, meaning end of xml header
if b'</siteinfo>' in line:
keep_appending_for_header = False
# Update Counters
line_cnt += 1
text_data_size += sys.getsizeof(line)
# the </page> determines new wiki page
if b'</page>\n' in line and text_data_size > desired_uncompressed_filesize_per_split:
_close_and_add_closing_tag(chunk_file)
# log status and info for every successful split process
logger.debug("total new data %s has reached the threshold of %s after %d line(s)", str(text_data_size), str(desired_uncompressed_filesize_per_split), line_cnt)
split_filename.append(chunk_file_name)
# reset text_data_size and do an increment filename
text_data_size = 0
line_cnt = 0
filecount += 1
logger.info("creating new splitted filename %s", chunk_file_name)
chunk_file, chunk_file_name = _create_chunk_file(filename, filecount)
_preempt_file_with_data(chunk_file, header_list)
#check if the file isn't closed yet
_close_and_add_closing_tag(chunk_file, is_expected_to_be_opened=False)
return split_filename
new_filename_collection = []
for iter_idx, _filename in enumerate(_dict_value):
if is_split_xml_identifier[iter_idx]:
_full_path_dir = _filename.split("/")
_folder_name = "/".join(_full_path_dir[:-1])
_init_filename = _full_path_dir[-1]
detected_split_filenames = sorted([os.path.join(_folder_name, file) for file in os.listdir(_folder_name) if bool(re.match(f"{_init_filename}_\d+", file))])
if force_rerun or len(detected_split_filenames)==0:
if force_rerun:
logger.debug("force rerun true")
elif len(detected_split_filenames)==0:
logger.debug("no detected split names")
logger.info("splitting file %s", _filename)
splitted_filenames = _split_data_to_smaller_sizes(_filename)
logger.info("file has been splitted to %s", len(splitted_filenames))
new_filename_collection.extend(splitted_filenames)
else:
logger.info("existing file(s) found with total files of %d", len(detected_split_filenames))
new_filename_collection.extend(detected_split_filenames)
else:
new_filename_collection.append(_filename)
return {dict_key: new_filename_collection}
def _parse_and_clean_wikicode(raw_content, parser, language):
"""Strips formatting and unwanted sections from raw page content."""
wikicode = parser.parse(raw_content)
# Filters for magic words that are parser instructions -- e.g., __NOTOC__
re_rm_magic = re.compile("__[A-Z]*__", flags=re.UNICODE)
# Filters for file/image links.
media_prefixes = "|".join(["File", "Image", "Media"] + MEDIA_ALIASES.get(language, []))
re_rm_wikilink = re.compile(f"^(?:{media_prefixes}):", flags=re.IGNORECASE | re.UNICODE)
def rm_wikilink(obj):
return bool(re_rm_wikilink.match(str(obj.title)))
# Filters for references and tables
def rm_tag(obj):
return str(obj.tag) in {"ref", "table"}
# Leave category links in-place but remove the category prefixes
cat_prefixes = "|".join(["Category"] + CAT_ALIASES.get(language, []))
re_clean_wikilink = re.compile(f"^(?:{cat_prefixes}):", flags=re.IGNORECASE | re.UNICODE)
def is_category(obj):
return bool(re_clean_wikilink.match(str(obj.title)))
def clean_wikilink(obj):
text = obj.__strip__()
text = re.sub(re_clean_wikilink, "", text)
obj.text = text
def try_replace_obj(obj):
try:
clean_wikilink(obj)
except ValueError:
# For unknown reasons, objects are sometimes not found.
pass
def try_remove_obj(obj, section):
try:
section.remove(obj)
except ValueError:
# For unknown reasons, objects are sometimes not found.
pass
section_text = []
# Filter individual sections to clean.
for section in wikicode.get_sections(flat=True, include_lead=True, include_headings=True):
for obj in section.ifilter_wikilinks(recursive=True):
if rm_wikilink(obj):
try_remove_obj(obj, section)
elif is_category(obj):
try_replace_obj(obj)
for obj in section.ifilter_tags(matches=rm_tag, recursive=True):
try_remove_obj(obj, section)
section_text.append(re.sub(re_rm_magic, "", section.strip_code().strip()))
return "\n\n".join(section_text)
def _construct_url(title, language):
# See: https://meta.wikimedia.org/wiki/Help:URL
return f"https://{language}.wikipedia.org/wiki/{quote(title)}"