File size: 42,935 Bytes
a91c8a9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 |
# 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)}"
|