repo_id
stringlengths
15
86
file_path
stringlengths
27
180
content
stringlengths
1
1.75M
__index_level_0__
int64
0
0
hf_public_repos/datasets/src/datasets
hf_public_repos/datasets/src/datasets/utils/version.py
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow 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 """Version utils.""" import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union _VERSION_REG = re.compile(r"^(?P<major>\d+)" r"\.(?P<minor>\d+)" r"\.(?P<patch>\d+)$") @total_ordering @dataclass class Version: """Dataset version `MAJOR.MINOR.PATCH`. Args: version_str (`str`): The dataset version. description (`str`): A description of what is new in this version. major (`str`): minor (`str`): patch (`str`): Example: ```py >>> VERSION = datasets.Version("1.0.0") ``` """ version_str: str description: Optional[str] = None major: Optional[Union[str, int]] = None minor: Optional[Union[str, int]] = None patch: Optional[Union[str, int]] = None def __post_init__(self): self.major, self.minor, self.patch = _str_to_version_tuple(self.version_str) def __repr__(self): return f"{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}" @property def tuple(self): return self.major, self.minor, self.patch def _validate_operand(self, other): if isinstance(other, str): return Version(other) elif isinstance(other, Version): return other raise TypeError(f"{other} (type {type(other)}) cannot be compared to version.") def __eq__(self, other): try: other = self._validate_operand(other) except (TypeError, ValueError): return False else: return self.tuple == other.tuple def __lt__(self, other): other = self._validate_operand(other) return self.tuple < other.tuple def __hash__(self): return hash(_version_tuple_to_str(self.tuple)) @classmethod def from_dict(cls, dic): field_names = {f.name for f in dataclasses.fields(cls)} return cls(**{k: v for k, v in dic.items() if k in field_names}) def _to_yaml_string(self) -> str: return self.version_str def _str_to_version_tuple(version_str): """Return the tuple (major, minor, patch) version extracted from the str.""" res = _VERSION_REG.match(version_str) if not res: raise ValueError(f"Invalid version '{version_str}'. Format should be x.y.z with {{x,y,z}} being digits.") return tuple(int(v) for v in [res.group("major"), res.group("minor"), res.group("patch")]) def _version_tuple_to_str(version_tuple): """Return the str version from the version tuple (major, minor, patch).""" return ".".join(str(v) for v in version_tuple)
0
hf_public_repos/datasets/src/datasets/utils
hf_public_repos/datasets/src/datasets/utils/resources/creators.json
{ "language": [ "found", "crowdsourced", "expert-generated", "machine-generated", "other" ], "annotations": [ "found", "crowdsourced", "expert-generated", "machine-generated", "no-annotation", "other" ] }
0
hf_public_repos/datasets/src/datasets/utils
hf_public_repos/datasets/src/datasets/utils/resources/languages.json
{ "code": "Programming language (C++, Java, Javascript, Python, etc.)", "aa": "Afar", "aaa": "Ghotuo", "aab": "Alumu-Tesu", "aac": "Ari", "aad": "Amal", "aae": "Arbëreshë Albanian", "aaf": "Aranadan", "aag": "Ambrak", "aah": "Abu' Arapesh", "aai": "Arifama-Miniafia", "aak": "Ankave", "aal": "Afade", "aan": "Anambé", "aao": "Algerian Saharan Arabic", "aap": "Pará Arára", "aaq": "Eastern Abnaki", "aas": "Aasáx", "aat": "Arvanitika Albanian", "aau": "Abau", "aav": "Austro-Asiatic languages", "aaw": "Solong", "aax": "Mandobo Atas", "aaz": "Amarasi", "ab": "Abkhazian", "aba": "Abé", "abb": "Bankon", "abc": "Ambala Ayta", "abd": "Manide", "abe": "Western Abnaki", "abf": "Abai Sungai", "abg": "Abaga", "abh": "Tajiki Arabic", "abi": "Abidji", "abj": "Aka-Bea", "abl": "Lampung Nyo", "abm": "Abanyom", "abn": "Abua", "abo": "Abon", "abp": "Abellen Ayta", "abq": "Abaza", "abr": "Abron", "abs": "Ambonese Malay", "abt": "Ambulas", "abu": "Abure", "abv": "Baharna Arabic", "abw": "Pal", "abx": "Inabaknon", "aby": "Aneme Wake", "abz": "Abui", "aca": "Achagua", "acb": "Áncá", "acd": "Gikyode", "ace": "Achinese", "acf": "Saint Lucian Creole French", "ach": "Acoli", "aci": "Aka-Cari", "ack": "Aka-Kora", "acl": "Akar-Bale", "acm": "Mesopotamian Arabic", "acn": "Achang", "acp": "Eastern Acipa", "acq": "Ta'izzi-Adeni Arabic", "acr": "Achi", "acs": "Acroá", "act": "Achterhoeks", "acu": "Achuar-Shiwiar", "acv": "Achumawi", "acw": "Hijazi Arabic", "acx": "Omani Arabic", "acy": "Cypriot Arabic", "acz": "Acheron", "ada": "Adangme", "adb": "Atauran", "add": "Lidzonka; Dzodinka", "ade": "Adele", "adf": "Dhofari Arabic", "adg": "Andegerebinha", "adh": "Adhola", "adi": "Adi", "adj": "Adioukrou", "adl": "Galo", "adn": "Adang", "ado": "Abu", "adq": "Adangbe", "adr": "Adonara", "ads": "Adamorobe Sign Language", "adt": "Adnyamathanha", "adu": "Aduge", "adw": "Amundava", "adx": "Amdo Tibetan", "ady": "Adyghe; Adygei", "adz": "Adzera", "ae": "Avestan", "aea": "Areba", "aeb": "Tunisian Arabic", "aec": "Saidi Arabic", "aed": "Argentine Sign Language", "aee": "Northeast Pashai; Northeast Pashayi", "aek": "Haeke", "ael": "Ambele", "aem": "Arem", "aen": "Armenian Sign Language", "aeq": "Aer", "aer": "Eastern Arrernte", "aes": "Alsea", "aeu": "Akeu", "aew": "Ambakich", "aey": "Amele", "aez": "Aeka", "af": "Afrikaans", "afa": "Afro-Asiatic languages", "afb": "Gulf Arabic", "afd": "Andai", "afe": "Putukwam", "afg": "Afghan Sign Language", "afh": "Afrihili", "afi": "Akrukay; Chini", "afk": "Nanubae", "afn": "Defaka", "afo": "Eloyi", "afp": "Tapei", "afs": "Afro-Seminole Creole", "aft": "Afitti", "afu": "Awutu", "afz": "Obokuitai", "aga": "Aguano", "agb": "Legbo", "agc": "Agatu", "agd": "Agarabi", "age": "Angal", "agf": "Arguni", "agg": "Angor", "agh": "Ngelima", "agi": "Agariya", "agj": "Argobba", "agk": "Isarog Agta", "agl": "Fembe", "agm": "Angaataha", "agn": "Agutaynen", "ago": "Tainae", "agq": "Aghem", "agr": "Aguaruna", "ags": "Esimbi", "agt": "Central Cagayan Agta", "agu": "Aguacateco", "agv": "Remontado Dumagat", "agw": "Kahua", "agx": "Aghul", "agy": "Southern Alta", "agz": "Mt. Iriga Agta", "aha": "Ahanta", "ahb": "Axamb", "ahg": "Qimant", "ahh": "Aghu", "ahi": "Tiagbamrin Aizi", "ahk": "Akha", "ahl": "Igo", "ahm": "Mobumrin Aizi", "ahn": "Àhàn", "aho": "Ahom", "ahp": "Aproumu Aizi", "ahr": "Ahirani", "ahs": "Ashe", "aht": "Ahtena", "aia": "Arosi", "aib": "Ainu (China)", "aic": "Ainbai", "aid": "Alngith", "aie": "Amara", "aif": "Agi", "aig": "Antigua and Barbuda Creole English", "aih": "Ai-Cham", "aii": "Assyrian Neo-Aramaic", "aij": "Lishanid Noshan", "aik": "Ake", "ail": "Aimele", "aim": "Aimol", "ain": "Ainu (Japan)", "aio": "Aiton", "aip": "Burumakok", "aiq": "Aimaq", "air": "Airoran", "ait": "Arikem", "aiw": "Aari", "aix": "Aighon", "aiy": "Ali", "aja": "Aja (South Sudan)", "ajg": "Aja (Benin)", "aji": "Ajië", "ajn": "Andajin", "ajp": "South Levantine Arabic", "ajs": "Algerian Jewish Sign Language", "aju": "Judeo-Moroccan Arabic", "ajw": "Ajawa", "ajz": "Amri Karbi", "ak": "Akan", "akb": "Batak Angkola", "akc": "Mpur", "akd": "Ukpet-Ehom", "ake": "Akawaio", "akf": "Akpa", "akg": "Anakalangu", "akh": "Angal Heneng", "aki": "Aiome", "akj": "Aka-Jeru", "akk": "Akkadian", "akl": "Aklanon", "akm": "Aka-Bo", "ako": "Akurio", "akp": "Siwu", "akq": "Ak", "akr": "Araki", "aks": "Akaselem", "akt": "Akolet", "aku": "Akum", "akv": "Akhvakh", "akw": "Akwa", "akx": "Aka-Kede", "aky": "Aka-Kol", "akz": "Alabama", "ala": "Alago", "alc": "Qawasqar", "ald": "Alladian", "ale": "Aleut", "alf": "Alege", "alg": "Algonquian languages", "alh": "Alawa", "ali": "Amaimon", "alj": "Alangan", "alk": "Alak", "all": "Allar", "alm": "Amblong", "aln": "Gheg Albanian", "alo": "Larike-Wakasihu", "alp": "Alune", "alq": "Algonquin", "alr": "Alutor", "als": "Tosk Albanian", "alt": "Southern Altai", "alu": "'Are'are", "alv": "Atlantic-Congo languages", "alw": "Alaba-K’abeena; Wanbasana", "alx": "Amol", "aly": "Alyawarr", "alz": "Alur", "am": "Amharic", "ama": "Amanayé", "amb": "Ambo", "amc": "Amahuaca", "ame": "Yanesha'", "amf": "Hamer-Banna", "amg": "Amurdak", "ami": "Amis", "amj": "Amdang", "amk": "Ambai", "aml": "War-Jaintia", "amm": "Ama (Papua New Guinea)", "amn": "Amanab", "amo": "Amo", "amp": "Alamblak", "amq": "Amahai", "amr": "Amarakaeri", "ams": "Southern Amami-Oshima", "amt": "Amto", "amu": "Guerrero Amuzgo", "amv": "Ambelau", "amw": "Western Neo-Aramaic", "amx": "Anmatyerre", "amy": "Ami", "amz": "Atampaya", "an": "Aragonese", "ana": "Andaqui", "anb": "Andoa", "anc": "Ngas", "and": "Ansus", "ane": "Xârâcùù", "anf": "Animere", "ang": "Old English (ca. 450-1100)", "anh": "Nend", "ani": "Andi", "anj": "Anor", "ank": "Goemai", "anl": "Anu-Hkongso Chin", "anm": "Anal", "ann": "Obolo", "ano": "Andoque", "anp": "Angika", "anq": "Jarawa (India)", "anr": "Andh", "ans": "Anserma", "ant": "Antakarinya; Antikarinya", "anu": "Anuak", "anv": "Denya", "anw": "Anaang", "anx": "Andra-Hus", "any": "Anyin", "anz": "Anem", "aoa": "Angolar", "aob": "Abom", "aoc": "Pemon", "aod": "Andarum", "aoe": "Angal Enen", "aof": "Bragat", "aog": "Angoram", "aoi": "Anindilyakwa", "aoj": "Mufian", "aok": "Arhö", "aol": "Alor", "aom": "Ömie", "aon": "Bumbita Arapesh", "aor": "Aore", "aos": "Taikat", "aot": "Atong (India); A'tong", "aou": "A'ou", "aox": "Atorada", "aoz": "Uab Meto", "apa": "Apache languages", "apb": "Sa'a", "apc": "North Levantine Arabic", "apd": "Sudanese Arabic", "ape": "Bukiyip", "apf": "Pahanan Agta", "apg": "Ampanang", "aph": "Athpariya", "api": "Apiaká", "apj": "Jicarilla Apache", "apk": "Kiowa Apache", "apl": "Lipan Apache", "apm": "Mescalero-Chiricahua Apache", "apn": "Apinayé", "apo": "Ambul", "app": "Apma", "apq": "A-Pucikwar", "apr": "Arop-Lokep", "aps": "Arop-Sissano", "apt": "Apatani", "apu": "Apurinã", "apv": "Alapmunte", "apw": "Western Apache", "apx": "Aputai", "apy": "Apalaí", "apz": "Safeyoka", "aqa": "Alacalufan languages", "aqc": "Archi", "aqd": "Ampari Dogon", "aqg": "Arigidi", "aqk": "Aninka", "aql": "Algic languages", "aqm": "Atohwaim", "aqn": "Northern Alta", "aqp": "Atakapa", "aqr": "Arhâ", "aqt": "Angaité", "aqz": "Akuntsu", "ar": "Arabic", "arb": "Standard Arabic", "arc": "Official Aramaic (700-300 BCE); Imperial Aramaic (700-300 BCE)", "ard": "Arabana", "are": "Western Arrarnta", "arh": "Arhuaco", "ari": "Arikara", "arj": "Arapaso", "ark": "Arikapú", "arl": "Arabela", "arn": "Mapudungun; Mapuche", "aro": "Araona", "arp": "Arapaho", "arq": "Algerian Arabic", "arr": "Karo (Brazil)", "ars": "Najdi Arabic", "art": "Artificial languages", "aru": "Aruá (Amazonas State); Arawá", "arv": "Arbore", "arw": "Arawak", "arx": "Aruá (Rodonia State)", "ary": "Moroccan Arabic", "arz": "Egyptian Arabic", "as": "Assamese", "asa": "Asu (Tanzania)", "asb": "Assiniboine", "asc": "Casuarina Coast Asmat", "ase": "American Sign Language", "asf": "Auslan; Australian Sign Language", "asg": "Cishingini", "ash": "Abishira", "asi": "Buruwai", "asj": "Sari", "ask": "Ashkun", "asl": "Asilulu", "asn": "Xingú Asuriní", "aso": "Dano", "asp": "Algerian Sign Language", "asq": "Austrian Sign Language", "asr": "Asuri", "ass": "Ipulo", "ast": "Asturian; Asturleonese; Bable; Leonese", "asu": "Tocantins Asurini", "asv": "Asoa", "asw": "Australian Aborigines Sign Language", "asx": "Muratayak", "asy": "Yaosakor Asmat", "asz": "As", "ata": "Pele-Ata", "atb": "Zaiwa", "atc": "Atsahuaca", "atd": "Ata Manobo", "ate": "Atemble", "atg": "Ivbie North-Okpela-Arhe", "ath": "Athapascan languages", "ati": "Attié", "atj": "Atikamekw", "atk": "Ati", "atl": "Mt. Iraya Agta", "atm": "Ata", "atn": "Ashtiani", "ato": "Atong (Cameroon)", "atp": "Pudtol Atta", "atq": "Aralle-Tabulahan", "atr": "Waimiri-Atroari", "ats": "Gros Ventre", "att": "Pamplona Atta", "atu": "Reel", "atv": "Northern Altai", "atw": "Atsugewi", "atx": "Arutani", "aty": "Aneityum", "atz": "Arta", "aua": "Asumboa", "aub": "Alugu", "auc": "Waorani", "aud": "Anuta", "auf": "Arauan languages", "aug": "Aguna", "auh": "Aushi", "aui": "Anuki", "auj": "Awjilah", "auk": "Heyo", "aul": "Aulua", "aum": "Asu (Nigeria)", "aun": "Molmo One", "auo": "Auyokawa", "aup": "Makayam", "auq": "Anus; Korur", "aur": "Aruek", "aus": "Australian languages", "aut": "Austral", "auu": "Auye", "auw": "Awyi", "aux": "Aurá", "auy": "Awiyaana", "auz": "Uzbeki Arabic", "av": "Avaric", "avb": "Avau", "avd": "Alviri-Vidari", "avi": "Avikam", "avk": "Kotava", "avl": "Eastern Egyptian Bedawi Arabic", "avm": "Angkamuthi", "avn": "Avatime", "avo": "Agavotaguerra", "avs": "Aushiri", "avt": "Au", "avu": "Avokaya", "avv": "Avá-Canoeiro", "awa": "Awadhi", "awb": "Awa (Papua New Guinea)", "awc": "Cicipu", "awd": "Arawakan languages", "awe": "Awetí", "awg": "Anguthimri", "awh": "Awbono", "awi": "Aekyom", "awk": "Awabakal", "awm": "Arawum", "awn": "Awngi", "awo": "Awak", "awr": "Awera", "aws": "South Awyu", "awt": "Araweté", "awu": "Central Awyu", "awv": "Jair Awyu", "aww": "Awun", "awx": "Awara", "awy": "Edera Awyu", "axb": "Abipon", "axe": "Ayerrerenge", "axg": "Mato Grosso Arára", "axk": "Yaka (Central African Republic)", "axl": "Lower Southern Aranda", "axm": "Middle Armenian", "axx": "Xârâgurè", "ay": "Aymara", "aya": "Awar", "ayb": "Ayizo Gbe", "ayc": "Southern Aymara", "ayd": "Ayabadhu", "aye": "Ayere", "ayg": "Ginyanga", "ayh": "Hadrami Arabic", "ayi": "Leyigha", "ayk": "Akuku", "ayl": "Libyan Arabic", "ayn": "Sanaani Arabic", "ayo": "Ayoreo", "ayp": "North Mesopotamian Arabic", "ayq": "Ayi (Papua New Guinea)", "ayr": "Central Aymara", "ays": "Sorsogon Ayta", "ayt": "Magbukun Ayta", "ayu": "Ayu", "ayz": "Mai Brat", "az": "Azerbaijani", "aza": "Azha", "azb": "South Azerbaijani", "azc": "Uto-Aztecan languages", "azd": "Eastern Durango Nahuatl", "azg": "San Pedro Amuzgos Amuzgo", "azj": "North Azerbaijani", "azm": "Ipalapa Amuzgo", "azn": "Western Durango Nahuatl", "azo": "Awing", "azt": "Faire Atta", "azz": "Highland Puebla Nahuatl", "ba": "Bashkir", "baa": "Babatana", "bab": "Bainouk-Gunyuño", "bac": "Badui", "bad": "Banda languages", "bae": "Baré", "baf": "Nubaca", "bag": "Tuki", "bah": "Bahamas Creole English", "bai": "Bamileke languages", "baj": "Barakai", "bal": "Baluchi", "ban": "Balinese", "bao": "Waimaha", "bap": "Bantawa", "bar": "Bavarian", "bas": "Basa (Cameroon)", "bat": "Baltic languages", "bau": "Bada (Nigeria)", "bav": "Vengo", "baw": "Bambili-Bambui", "bax": "Bamun", "bay": "Batuley", "bba": "Baatonum", "bbb": "Barai", "bbc": "Batak Toba", "bbd": "Bau", "bbe": "Bangba", "bbf": "Baibai", "bbg": "Barama", "bbh": "Bugan", "bbi": "Barombi", "bbj": "Ghomálá'", "bbk": "Babanki", "bbl": "Bats", "bbm": "Babango", "bbn": "Uneapa", "bbo": "Northern Bobo Madaré; Konabéré", "bbp": "West Central Banda", "bbq": "Bamali", "bbr": "Girawa", "bbs": "Bakpinka", "bbt": "Mburku", "bbu": "Kulung (Nigeria)", "bbv": "Karnai", "bbw": "Baba", "bbx": "Bubia", "bby": "Befang", "bca": "Central Bai", "bcb": "Bainouk-Samik", "bcc": "Southern Balochi", "bcd": "North Babar", "bce": "Bamenyam", "bcf": "Bamu", "bcg": "Baga Pokur", "bch": "Bariai", "bci": "Baoulé", "bcj": "Bardi", "bck": "Bunuba", "bcl": "Central Bikol", "bcm": "Bannoni", "bcn": "Bali (Nigeria)", "bco": "Kaluli", "bcp": "Bali (Democratic Republic of Congo)", "bcq": "Bench", "bcr": "Babine", "bcs": "Kohumono", "bct": "Bendi", "bcu": "Awad Bing", "bcv": "Shoo-Minda-Nye", "bcw": "Bana", "bcy": "Bacama", "bcz": "Bainouk-Gunyaamolo", "bda": "Bayot", "bdb": "Basap", "bdc": "Emberá-Baudó", "bdd": "Bunama", "bde": "Bade", "bdf": "Biage", "bdg": "Bonggi", "bdh": "Baka (South Sudan)", "bdi": "Burun", "bdj": "Bai (South Sudan); Bai", "bdk": "Budukh", "bdl": "Indonesian Bajau", "bdm": "Buduma", "bdn": "Baldemu", "bdo": "Morom", "bdp": "Bende", "bdq": "Bahnar", "bdr": "West Coast Bajau", "bds": "Burunge", "bdt": "Bokoto", "bdu": "Oroko", "bdv": "Bodo Parja", "bdw": "Baham", "bdx": "Budong-Budong", "bdy": "Bandjalang", "bdz": "Badeshi", "be": "Belarusian", "bea": "Beaver", "beb": "Bebele", "bec": "Iceve-Maci", "bed": "Bedoanas", "bee": "Byangsi", "bef": "Benabena", "beg": "Belait", "beh": "Biali", "bei": "Bekati'", "bej": "Beja; Bedawiyet", "bek": "Bebeli", "bem": "Bemba (Zambia)", "beo": "Beami", "bep": "Besoa", "beq": "Beembe", "ber": "Berber languages", "bes": "Besme", "bet": "Guiberoua Béte", "beu": "Blagar", "bev": "Daloa Bété", "bew": "Betawi", "bex": "Jur Modo", "bey": "Beli (Papua New Guinea)", "bez": "Bena (Tanzania)", "bfa": "Bari", "bfb": "Pauri Bareli", "bfc": "Panyi Bai; Northern Bai", "bfd": "Bafut", "bfe": "Betaf; Tena", "bff": "Bofi", "bfg": "Busang Kayan", "bfh": "Blafe", "bfi": "British Sign Language", "bfj": "Bafanji", "bfk": "Ban Khor Sign Language", "bfl": "Banda-Ndélé", "bfm": "Mmen", "bfn": "Bunak", "bfo": "Malba Birifor", "bfp": "Beba", "bfq": "Badaga", "bfr": "Bazigar", "bfs": "Southern Bai", "bft": "Balti", "bfu": "Gahri", "bfw": "Bondo", "bfx": "Bantayanon", "bfy": "Bagheli", "bfz": "Mahasu Pahari", "bg": "Bulgarian", "bga": "Gwamhi-Wuri", "bgb": "Bobongko", "bgc": "Haryanvi", "bgd": "Rathwi Bareli", "bge": "Bauria", "bgf": "Bangandu", "bgg": "Bugun", "bgi": "Giangan", "bgj": "Bangolan", "bgk": "Bit; Buxinhua", "bgl": "Bo (Laos)", "bgn": "Western Balochi", "bgo": "Baga Koga", "bgp": "Eastern Balochi", "bgq": "Bagri", "bgr": "Bawm Chin", "bgs": "Tagabawa", "bgt": "Bughotu", "bgu": "Mbongno", "bgv": "Warkay-Bipim", "bgw": "Bhatri", "bgx": "Balkan Gagauz Turkish", "bgy": "Benggoi", "bgz": "Banggai", "bh": "Bihari languages", "bha": "Bharia", "bhb": "Bhili", "bhc": "Biga", "bhd": "Bhadrawahi", "bhe": "Bhaya", "bhf": "Odiai", "bhg": "Binandere", "bhh": "Bukharic", "bhi": "Bhilali", "bhj": "Bahing", "bhl": "Bimin", "bhm": "Bathari", "bhn": "Bohtan Neo-Aramaic", "bho": "Bhojpuri", "bhp": "Bima", "bhq": "Tukang Besi South", "bhr": "Bara Malagasy", "bhs": "Buwal", "bht": "Bhattiyali", "bhu": "Bhunjia", "bhv": "Bahau", "bhw": "Biak", "bhx": "Bhalay", "bhy": "Bhele", "bhz": "Bada (Indonesia)", "bi": "Bislama", "bia": "Badimaya", "bib": "Bissa; Bisa", "bid": "Bidiyo", "bie": "Bepour", "bif": "Biafada", "big": "Biangai", "bik": "Bikol", "bil": "Bile", "bim": "Bimoba", "bin": "Bini; Edo", "bio": "Nai", "bip": "Bila", "biq": "Bipi", "bir": "Bisorio", "bit": "Berinomo", "biu": "Biete", "biv": "Southern Birifor", "biw": "Kol (Cameroon)", "bix": "Bijori", "biy": "Birhor", "biz": "Baloi", "bja": "Budza", "bjb": "Banggarla", "bjc": "Bariji", "bje": "Biao-Jiao Mien", "bjf": "Barzani Jewish Neo-Aramaic", "bjg": "Bidyogo", "bjh": "Bahinemo", "bji": "Burji", "bjj": "Kanauji", "bjk": "Barok", "bjl": "Bulu (Papua New Guinea)", "bjm": "Bajelani", "bjn": "Banjar", "bjo": "Mid-Southern Banda", "bjp": "Fanamaket", "bjr": "Binumarien", "bjs": "Bajan", "bjt": "Balanta-Ganja", "bju": "Busuu", "bjv": "Bedjond", "bjw": "Bakwé", "bjx": "Banao Itneg", "bjy": "Bayali", "bjz": "Baruga", "bka": "Kyak", "bkc": "Baka (Cameroon)", "bkd": "Binukid; Talaandig", "bkf": "Beeke", "bkg": "Buraka", "bkh": "Bakoko", "bki": "Baki", "bkj": "Pande", "bkk": "Brokskat", "bkl": "Berik", "bkm": "Kom (Cameroon)", "bkn": "Bukitan", "bko": "Kwa'", "bkp": "Boko (Democratic Republic of Congo)", "bkq": "Bakairí", "bkr": "Bakumpai", "bks": "Northern Sorsoganon", "bkt": "Boloki", "bku": "Buhid", "bkv": "Bekwarra", "bkw": "Bekwel", "bkx": "Baikeno", "bky": "Bokyi", "bkz": "Bungku", "bla": "Siksika", "blb": "Bilua", "blc": "Bella Coola", "bld": "Bolango", "ble": "Balanta-Kentohe", "blf": "Buol", "blh": "Kuwaa", "bli": "Bolia", "blj": "Bolongan", "blk": "Pa'o Karen; Pa'O", "bll": "Biloxi", "blm": "Beli (South Sudan)", "bln": "Southern Catanduanes Bikol", "blo": "Anii", "blp": "Blablanga", "blq": "Baluan-Pam", "blr": "Blang", "bls": "Balaesang", "blt": "Tai Dam", "blv": "Kibala; Bolo", "blw": "Balangao", "blx": "Mag-Indi Ayta", "bly": "Notre", "blz": "Balantak", "bm": "Bambara", "bma": "Lame", "bmb": "Bembe", "bmc": "Biem", "bmd": "Baga Manduri", "bme": "Limassa", "bmf": "Bom-Kim", "bmg": "Bamwe", "bmh": "Kein", "bmi": "Bagirmi", "bmj": "Bote-Majhi", "bmk": "Ghayavi", "bml": "Bomboli", "bmm": "Northern Betsimisaraka Malagasy", "bmn": "Bina (Papua New Guinea)", "bmo": "Bambalang", "bmp": "Bulgebi", "bmq": "Bomu", "bmr": "Muinane", "bms": "Bilma Kanuri", "bmt": "Biao Mon", "bmu": "Somba-Siawari", "bmv": "Bum", "bmw": "Bomwali", "bmx": "Baimak", "bmz": "Baramu", "bn": "Bengali; Bangla", "bna": "Bonerate", "bnb": "Bookan", "bnc": "Bontok", "bnd": "Banda (Indonesia)", "bne": "Bintauna", "bnf": "Masiwang", "bng": "Benga", "bni": "Bangi", "bnj": "Eastern Tawbuid", "bnk": "Bierebo", "bnl": "Boon", "bnm": "Batanga", "bnn": "Bunun", "bno": "Bantoanon", "bnp": "Bola", "bnq": "Bantik", "bnr": "Butmas-Tur", "bns": "Bundeli", "bnt": "Bantu languages", "bnu": "Bentong", "bnv": "Bonerif; Beneraf; Edwas", "bnw": "Bisis", "bnx": "Bangubangu", "bny": "Bintulu", "bnz": "Beezen", "bo": "Tibetan", "boa": "Bora", "bob": "Aweer", "boe": "Mundabli", "bof": "Bolon", "bog": "Bamako Sign Language", "boh": "Boma", "boi": "Barbareño", "boj": "Anjam", "bok": "Bonjo", "bol": "Bole", "bom": "Berom", "bon": "Bine", "boo": "Tiemacèwè Bozo", "bop": "Bonkiman", "boq": "Bogaya", "bor": "Borôro", "bot": "Bongo", "bou": "Bondei", "bov": "Tuwuli", "bow": "Rema", "box": "Buamu", "boy": "Bodo (Central African Republic)", "boz": "Tiéyaxo Bozo", "bpa": "Daakaka", "bpc": "Mbuk", "bpd": "Banda-Banda", "bpe": "Bauni", "bpg": "Bonggo", "bph": "Botlikh", "bpi": "Bagupi", "bpj": "Binji", "bpk": "Orowe; 'Ôrôê", "bpl": "Broome Pearling Lugger Pidgin", "bpm": "Biyom", "bpn": "Dzao Min", "bpo": "Anasi", "bpp": "Kaure", "bpq": "Banda Malay", "bpr": "Koronadal Blaan", "bps": "Sarangani Blaan", "bpt": "Barrow Point", "bpu": "Bongu", "bpv": "Bian Marind", "bpw": "Bo (Papua New Guinea)", "bpx": "Palya Bareli", "bpy": "Bishnupriya", "bpz": "Bilba", "bqa": "Tchumbuli", "bqb": "Bagusa", "bqc": "Boko (Benin); Boo", "bqd": "Bung", "bqf": "Baga Kaloum", "bqg": "Bago-Kusuntu", "bqh": "Baima", "bqi": "Bakhtiari", "bqj": "Bandial", "bqk": "Banda-Mbrès", "bql": "Bilakura", "bqm": "Wumboko", "bqn": "Bulgarian Sign Language", "bqo": "Balo", "bqp": "Busa", "bqq": "Biritai", "bqr": "Burusu", "bqs": "Bosngun", "bqt": "Bamukumbit", "bqu": "Boguru", "bqv": "Koro Wachi; Begbere-Ejar", "bqw": "Buru (Nigeria)", "bqx": "Baangi", "bqy": "Bengkala Sign Language", "bqz": "Bakaka", "br": "Breton", "bra": "Braj", "brb": "Brao; Lave", "brc": "Berbice Creole Dutch", "brd": "Baraamu", "brf": "Bira", "brg": "Baure", "brh": "Brahui", "bri": "Mokpwe", "brj": "Bieria", "brk": "Birked", "brl": "Birwa", "brm": "Barambu", "brn": "Boruca", "bro": "Brokkat", "brp": "Barapasi", "brq": "Breri", "brr": "Birao", "brs": "Baras", "brt": "Bitare", "bru": "Eastern Bru", "brv": "Western Bru", "brw": "Bellari", "brx": "Bodo (India)", "bry": "Burui", "brz": "Bilbil", "bs": "Bosnian", "bsa": "Abinomn", "bsb": "Brunei Bisaya", "bsc": "Bassari; Oniyan", "bse": "Wushi", "bsf": "Bauchi", "bsg": "Bashkardi", "bsh": "Kati", "bsi": "Bassossi", "bsj": "Bangwinji", "bsk": "Burushaski", "bsl": "Basa-Gumna", "bsm": "Busami", "bsn": "Barasana-Eduria", "bso": "Buso", "bsp": "Baga Sitemu", "bsq": "Bassa", "bsr": "Bassa-Kontagora", "bss": "Akoose", "bst": "Basketo", "bsu": "Bahonsuai", "bsv": "Baga Sobané", "bsw": "Baiso", "bsx": "Yangkam", "bsy": "Sabah Bisaya", "bta": "Bata", "btc": "Bati (Cameroon)", "btd": "Batak Dairi", "bte": "Gamo-Ningi", "btf": "Birgit", "btg": "Gagnoa Bété", "bth": "Biatah Bidayuh", "bti": "Burate", "btj": "Bacanese Malay", "btk": "Batak languages", "btm": "Batak Mandailing", "btn": "Ratagnon", "bto": "Rinconada Bikol", "btp": "Budibud", "btq": "Batek", "btr": "Baetora", "bts": "Batak Simalungun", "btt": "Bete-Bendi", "btu": "Batu", "btv": "Bateri", "btw": "Butuanon", "btx": "Batak Karo", "bty": "Bobot", "btz": "Batak Alas-Kluet", "bua": "Buriat", "bub": "Bua", "buc": "Bushi", "bud": "Ntcham", "bue": "Beothuk", "buf": "Bushoong", "bug": "Buginese", "buh": "Younuo Bunu", "bui": "Bongili", "buj": "Basa-Gurmana", "buk": "Bugawac", "bum": "Bulu (Cameroon)", "bun": "Sherbro", "buo": "Terei", "bup": "Busoa", "buq": "Brem", "bus": "Bokobaru", "but": "Bungain", "buu": "Budu", "buv": "Bun", "buw": "Bubi", "bux": "Boghom", "buy": "Bullom So", "buz": "Bukwen", "bva": "Barein", "bvb": "Bube", "bvc": "Baelelea", "bvd": "Baeggu", "bve": "Berau Malay", "bvf": "Boor", "bvg": "Bonkeng", "bvh": "Bure", "bvi": "Belanda Viri", "bvj": "Baan", "bvk": "Bukat", "bvl": "Bolivian Sign Language", "bvm": "Bamunka", "bvn": "Buna", "bvo": "Bolgo", "bvp": "Bumang", "bvq": "Birri", "bvr": "Burarra", "bvt": "Bati (Indonesia)", "bvu": "Bukit Malay", "bvv": "Baniva", "bvw": "Boga", "bvx": "Dibole", "bvy": "Baybayanon", "bvz": "Bauzi", "bwa": "Bwatoo", "bwb": "Namosi-Naitasiri-Serua", "bwc": "Bwile", "bwd": "Bwaidoka", "bwe": "Bwe Karen", "bwf": "Boselewa", "bwg": "Barwe", "bwh": "Bishuo", "bwi": "Baniwa", "bwj": "Láá Láá Bwamu", "bwk": "Bauwaki", "bwl": "Bwela", "bwm": "Biwat", "bwn": "Wunai Bunu", "bwo": "Boro (Ethiopia); Borna (Ethiopia)", "bwp": "Mandobo Bawah", "bwq": "Southern Bobo Madaré", "bwr": "Bura-Pabir", "bws": "Bomboma", "bwt": "Bafaw-Balong", "bwu": "Buli (Ghana)", "bww": "Bwa", "bwx": "Bu-Nao Bunu", "bwy": "Cwi Bwamu", "bwz": "Bwisi", "bxa": "Tairaha", "bxb": "Belanda Bor", "bxc": "Molengue", "bxd": "Pela", "bxe": "Birale", "bxf": "Bilur; Minigir", "bxg": "Bangala", "bxh": "Buhutu", "bxi": "Pirlatapa", "bxj": "Bayungu", "bxk": "Bukusu; Lubukusu", "bxl": "Jalkunan", "bxm": "Mongolia Buriat", "bxn": "Burduna", "bxo": "Barikanchi", "bxp": "Bebil", "bxq": "Beele", "bxr": "Russia Buriat", "bxs": "Busam", "bxu": "China Buriat", "bxv": "Berakou", "bxw": "Bankagooma", "bxz": "Binahari", "bya": "Batak", "byb": "Bikya", "byc": "Ubaghara", "byd": "Benyadu'", "bye": "Pouye", "byf": "Bete", "byg": "Baygo", "byh": "Bhujel", "byi": "Buyu", "byj": "Bina (Nigeria)", "byk": "Biao", "byl": "Bayono", "bym": "Bidjara", "byn": "Bilin; Blin", "byo": "Biyo", "byp": "Bumaji", "byq": "Basay", "byr": "Baruya; Yipma", "bys": "Burak", "byt": "Berti", "byv": "Medumba", "byw": "Belhariya", "byx": "Qaqet", "byz": "Banaro", "bza": "Bandi", "bzb": "Andio", "bzc": "Southern Betsimisaraka Malagasy", "bzd": "Bribri", "bze": "Jenaama Bozo", "bzf": "Boikin", "bzg": "Babuza", "bzh": "Mapos Buang", "bzi": "Bisu", "bzj": "Belize Kriol English", "bzk": "Nicaragua Creole English", "bzl": "Boano (Sulawesi)", "bzm": "Bolondo", "bzn": "Boano (Maluku)", "bzo": "Bozaba", "bzp": "Kemberano", "bzq": "Buli (Indonesia)", "bzr": "Biri", "bzs": "Brazilian Sign Language", "bzt": "Brithenig", "bzu": "Burmeso", "bzv": "Naami", "bzw": "Basa (Nigeria)", "bzx": "Kɛlɛngaxo Bozo", "bzy": "Obanliku", "bzz": "Evant", "ca": "Catalan; Valencian", "caa": "Chortí", "cab": "Garifuna", "cac": "Chuj", "cad": "Caddo", "cae": "Lehar; Laalaa", "caf": "Southern Carrier", "cag": "Nivaclé", "cah": "Cahuarano", "cai": "Central American Indian languages", "caj": "Chané", "cak": "Kaqchikel; Cakchiquel", "cal": "Carolinian", "cam": "Cemuhî", "can": "Chambri", "cao": "Chácobo", "cap": "Chipaya", "caq": "Car Nicobarese", "car": "Galibi Carib", "cas": "Tsimané", "cau": "Caucasian languages", "cav": "Cavineña", "caw": "Callawalla", "cax": "Chiquitano", "cay": "Cayuga", "caz": "Canichana", "cba": "Chibchan languages", "cbb": "Cabiyarí", "cbc": "Carapana", "cbd": "Carijona", "cbg": "Chimila", "cbi": "Chachi", "cbj": "Ede Cabe", "cbk": "Chavacano", "cbl": "Bualkhaw Chin", "cbn": "Nyahkur", "cbo": "Izora", "cbq": "Tsucuba; Cuba", "cbr": "Cashibo-Cacataibo", "cbs": "Cashinahua", "cbt": "Chayahuita", "cbu": "Candoshi-Shapra", "cbv": "Cacua", "cbw": "Kinabalian", "cby": "Carabayo", "ccc": "Chamicuro", "ccd": "Cafundo Creole", "cce": "Chopi", "ccg": "Samba Daka", "cch": "Atsam", "ccj": "Kasanga", "ccl": "Cutchi-Swahili", "ccm": "Malaccan Creole Malay", "ccn": "North Caucasian languages", "cco": "Comaltepec Chinantec", "ccp": "Chakma", "ccr": "Cacaopera", "ccs": "South Caucasian languages", "cda": "Choni", "cdc": "Chadic languages", "cdd": "Caddoan languages", "cde": "Chenchu", "cdf": "Chiru", "cdh": "Chambeali", "cdi": "Chodri", "cdj": "Churahi", "cdm": "Chepang", "cdn": "Chaudangsi", "cdo": "Min Dong Chinese", "cdr": "Cinda-Regi-Tiyal", "cds": "Chadian Sign Language", "cdy": "Chadong", "cdz": "Koda", "ce": "Chechen", "cea": "Lower Chehalis", "ceb": "Cebuano", "ceg": "Chamacoco", "cek": "Eastern Khumi Chin", "cel": "Celtic languages", "cen": "Cen", "cet": "Centúúm", "cey": "Ekai Chin", "cfa": "Dijim-Bwilim", "cfd": "Cara", "cfg": "Como Karim", "cfm": "Falam Chin", "cga": "Changriwa", "cgc": "Kagayanen", "cgg": "Chiga", "cgk": "Chocangacakha", "ch": "Chamorro", "chb": "Chibcha", "chc": "Catawba", "chd": "Highland Oaxaca Chontal", "chf": "Tabasco Chontal", "chg": "Chagatai", "chh": "Chinook", "chj": "Ojitlán Chinantec", "chk": "Chuukese", "chl": "Cahuilla", "chm": "Mari (Russia)", "chn": "Chinook jargon", "cho": "Choctaw", "chp": "Chipewyan; Dene Suline", "chq": "Quiotepec Chinantec", "chr": "Cherokee", "cht": "Cholón", "chw": "Chuwabu", "chx": "Chantyal", "chy": "Cheyenne", "chz": "Ozumacín Chinantec", "cia": "Cia-Cia", "cib": "Ci Gbe", "cic": "Chickasaw", "cid": "Chimariko", "cie": "Cineni", "cih": "Chinali", "cik": "Chitkuli Kinnauri", "cim": "Cimbrian", "cin": "Cinta Larga", "cip": "Chiapanec", "cir": "Tiri; Haméa; Méa", "ciw": "Chippewa", "ciy": "Chaima", "cja": "Western Cham", "cje": "Chru", "cjh": "Upper Chehalis", "cji": "Chamalal", "cjk": "Chokwe", "cjm": "Eastern Cham", "cjn": "Chenapian", "cjo": "Ashéninka Pajonal", "cjp": "Cabécar", "cjs": "Shor", "cjv": "Chuave", "cjy": "Jinyu Chinese", "ckb": "Central Kurdish", "ckh": "Chak", "ckl": "Cibak", "ckm": "Chakavian", "ckn": "Kaang Chin", "cko": "Anufo", "ckq": "Kajakse", "ckr": "Kairak", "cks": "Tayo", "ckt": "Chukot", "cku": "Koasati", "ckv": "Kavalan", "ckx": "Caka", "cky": "Cakfem-Mushere", "ckz": "Cakchiquel-Quiché Mixed Language", "cla": "Ron", "clc": "Chilcotin", "cld": "Chaldean Neo-Aramaic", "cle": "Lealao Chinantec", "clh": "Chilisso", "cli": "Chakali", "clj": "Laitu Chin", "clk": "Idu-Mishmi", "cll": "Chala", "clm": "Clallam", "clo": "Lowland Oaxaca Chontal", "clt": "Lautu Chin", "clu": "Caluyanun", "clw": "Chulym", "cly": "Eastern Highland Chatino", "cma": "Maa", "cmc": "Chamic languages", "cme": "Cerma", "cmg": "Classical Mongolian", "cmi": "Emberá-Chamí", "cml": "Campalagian", "cmm": "Michigamea", "cmn": "Mandarin Chinese", "cmo": "Central Mnong", "cmr": "Mro-Khimi Chin", "cms": "Messapic", "cmt": "Camtho", "cna": "Changthang", "cnb": "Chinbon Chin", "cnc": "Côông", "cng": "Northern Qiang", "cnh": "Hakha Chin; Haka Chin", "cni": "Asháninka", "cnk": "Khumi Chin", "cnl": "Lalana Chinantec", "cno": "Con", "cnp": "Northern Ping Chinese; Northern Pinghua", "cnq": "Chung", "cnr": "Montenegrin", "cns": "Central Asmat", "cnt": "Tepetotutla Chinantec", "cnu": "Chenoua", "cnw": "Ngawn Chin", "cnx": "Middle Cornish", "co": "Corsican", "coa": "Cocos Islands Malay", "cob": "Chicomuceltec", "coc": "Cocopa", "cod": "Cocama-Cocamilla", "coe": "Koreguaje", "cof": "Colorado", "cog": "Chong", "coh": "Chonyi-Dzihana-Kauma; Chichonyi-Chidzihana-Chikauma", "coj": "Cochimi", "cok": "Santa Teresa Cora", "col": "Columbia-Wenatchi", "com": "Comanche", "con": "Cofán", "coo": "Comox", "cop": "Coptic", "coq": "Coquille", "cot": "Caquinte", "cou": "Wamey", "cov": "Cao Miao", "cow": "Cowlitz", "cox": "Nanti", "coz": "Chochotec", "cpa": "Palantla Chinantec", "cpb": "Ucayali-Yurúa Ashéninka", "cpc": "Ajyíninka Apurucayali", "cpe": "English-based creoles and pidgins", "cpf": "French-based creoles and pidgins", "cpg": "Cappadocian Greek", "cpi": "Chinese Pidgin English", "cpn": "Cherepon", "cpo": "Kpeego", "cpp": "Portuguese-based creoles and pidgins", "cps": "Capiznon", "cpu": "Pichis Ashéninka", "cpx": "Pu-Xian Chinese", "cpy": "South Ucayali Ashéninka", "cqd": "Chuanqiandian Cluster Miao", "cr": "Cree", "cra": "Chara", "crb": "Island Carib", "crc": "Lonwolwol", "crd": "Coeur d'Alene", "crf": "Caramanta", "crg": "Michif", "crh": "Crimean Tatar; Crimean Turkish", "cri": "Sãotomense", "crj": "Southern East Cree", "crk": "Plains Cree", "crl": "Northern East Cree", "crm": "Moose Cree", "crn": "El Nayar Cora", "cro": "Crow", "crp": "Creoles and pidgins", "crq": "Iyo'wujwa Chorote", "crr": "Carolina Algonquian", "crs": "Seselwa Creole French", "crt": "Iyojwa'ja Chorote", "crv": "Chaura", "crw": "Chrau", "crx": "Carrier", "cry": "Cori", "crz": "Cruzeño", "cs": "Czech", "csa": "Chiltepec Chinantec", "csb": "Kashubian", "csc": "Catalan Sign Language; Lengua de señas catalana; Llengua de Signes Catalana", "csd": "Chiangmai Sign Language", "cse": "Czech Sign Language", "csf": "Cuba Sign Language", "csg": "Chilean Sign Language", "csh": "Asho Chin", "csi": "Coast Miwok", "csj": "Songlai Chin", "csk": "Jola-Kasa", "csl": "Chinese Sign Language", "csm": "Central Sierra Miwok", "csn": "Colombian Sign Language", "cso": "Sochiapam Chinantec; Sochiapan Chinantec", "csp": "Southern Ping Chinese; Southern Pinghua", "csq": "Croatia Sign Language", "csr": "Costa Rican Sign Language", "css": "Southern Ohlone", "cst": "Northern Ohlone", "csu": "Central Sudanic languages", "csv": "Sumtu Chin", "csw": "Swampy Cree", "csx": "Cambodian Sign Language", "csy": "Siyin Chin", "csz": "Coos", "cta": "Tataltepec Chatino", "ctc": "Chetco", "ctd": "Tedim Chin", "cte": "Tepinapa Chinantec", "ctg": "Chittagonian", "cth": "Thaiphum Chin", "ctl": "Tlacoatzintepec Chinantec", "ctm": "Chitimacha", "ctn": "Chhintange", "cto": "Emberá-Catío", "ctp": "Western Highland Chatino", "cts": "Northern Catanduanes Bikol", "ctt": "Wayanad Chetti", "ctu": "Chol", "cty": "Moundadan Chetty", "ctz": "Zacatepec Chatino", "cu": "Church Slavic; Church Slavonic; Old Bulgarian; Old Church Slavonic; Old Slavonic", "cua": "Cua", "cub": "Cubeo", "cuc": "Usila Chinantec", "cuh": "Chuka; Gichuka", "cui": "Cuiba", "cuj": "Mashco Piro", "cuk": "San Blas Kuna", "cul": "Culina; Kulina", "cuo": "Cumanagoto", "cup": "Cupeño", "cuq": "Cun", "cur": "Chhulung", "cus": "Cushitic languages", "cut": "Teutila Cuicatec", "cuu": "Tai Ya", "cuv": "Cuvok", "cuw": "Chukwa", "cux": "Tepeuxila Cuicatec", "cuy": "Cuitlatec", "cv": "Chuvash", "cvg": "Chug", "cvn": "Valle Nacional Chinantec", "cwa": "Kabwa", "cwb": "Maindo", "cwd": "Woods Cree", "cwe": "Kwere", "cwg": "Chewong; Cheq Wong", "cwt": "Kuwaataay", "cy": "Welsh", "cya": "Nopala Chatino", "cyb": "Cayubaba", "cyo": "Cuyonon", "czh": "Huizhou Chinese", "czk": "Knaanic", "czn": "Zenzontepec Chatino", "czo": "Min Zhong Chinese", "czt": "Zotung Chin", "da": "Danish", "daa": "Dangaléat", "dac": "Dambi", "dad": "Marik", "dae": "Duupa", "dag": "Dagbani", "dah": "Gwahatike", "dai": "Day", "daj": "Dar Fur Daju", "dak": "Dakota", "dal": "Dahalo", "dam": "Damakawa", "dao": "Daai Chin", "daq": "Dandami Maria", "dar": "Dargwa", "das": "Daho-Doo", "dau": "Dar Sila Daju", "dav": "Taita; Dawida", "daw": "Davawenyo", "dax": "Dayi", "day": "Land Dayak languages", "daz": "Dao", "dba": "Bangime", "dbb": "Deno", "dbd": "Dadiya", "dbe": "Dabe", "dbf": "Edopi", "dbg": "Dogul Dom Dogon", "dbi": "Doka", "dbj": "Ida'an", "dbl": "Dyirbal", "dbm": "Duguri", "dbn": "Duriankere", "dbo": "Dulbu", "dbp": "Duwai", "dbq": "Daba", "dbr": "Dabarre", "dbt": "Ben Tey Dogon", "dbu": "Bondum Dom Dogon", "dbv": "Dungu", "dbw": "Bankan Tey Dogon", "dby": "Dibiyaso", "dcc": "Deccan", "dcr": "Negerhollands", "dda": "Dadi Dadi", "ddd": "Dongotono", "dde": "Doondo", "ddg": "Fataluku", "ddi": "West Goodenough", "ddj": "Jaru", "ddn": "Dendi (Benin)", "ddo": "Dido", "ddr": "Dhudhuroa", "dds": "Donno So Dogon", "ddw": "Dawera-Daweloor", "de": "German", "dec": "Dagik", "ded": "Dedua", "dee": "Dewoin", "def": "Dezfuli", "deg": "Degema", "deh": "Dehwari", "dei": "Demisa", "dek": "Dek", "del": "Delaware", "dem": "Dem", "den": "Slave (Athapascan)", "dep": "Pidgin Delaware", "deq": "Dendi (Central African Republic)", "der": "Deori", "des": "Desano", "dev": "Domung", "dez": "Dengese", "dga": "Southern Dagaare", "dgb": "Bunoge Dogon", "dgc": "Casiguran Dumagat Agta", "dgd": "Dagaari Dioula", "dge": "Degenan", "dgg": "Doga", "dgh": "Dghwede", "dgi": "Northern Dagara", "dgk": "Dagba", "dgl": "Andaandi; Dongolawi", "dgn": "Dagoman", "dgo": "Dogri (individual language)", "dgr": "Dogrib; Tłı̨chǫ", "dgs": "Dogoso", "dgt": "Ndra'ngith", "dgw": "Daungwurrung", "dgx": "Doghoro", "dgz": "Daga", "dhd": "Dhundari", "dhg": "Dhangu-Djangu; Dhangu; Djangu", "dhi": "Dhimal", "dhl": "Dhalandji", "dhm": "Zemba", "dhn": "Dhanki", "dho": "Dhodia", "dhr": "Dhargari", "dhs": "Dhaiso", "dhu": "Dhurga", "dhv": "Dehu; Drehu", "dhw": "Dhanwar (Nepal)", "dhx": "Dhungaloo", "dia": "Dia", "dib": "South Central Dinka", "dic": "Lakota Dida", "did": "Didinga", "dif": "Dieri; Diyari", "dig": "Digo; Chidigo", "dih": "Kumiai", "dii": "Dimbong", "dij": "Dai", "dik": "Southwestern Dinka", "dil": "Dilling", "dim": "Dime", "din": "Dinka", "dio": "Dibo", "dip": "Northeastern Dinka", "diq": "Dimli (individual language)", "dir": "Dirim", "dis": "Dimasa", "diu": "Diriku", "diw": "Northwestern Dinka", "dix": "Dixon Reef", "diy": "Diuwe", "diz": "Ding", "dja": "Djadjawurrung", "djb": "Djinba", "djc": "Dar Daju Daju", "djd": "Djamindjung; Ngaliwurru", "dje": "Zarma", "djf": "Djangun", "dji": "Djinang", "djj": "Djeebbana", "djk": "Eastern Maroon Creole; Businenge Tongo; Nenge", "djm": "Jamsay Dogon", "djn": "Jawoyn; Djauan", "djo": "Jangkang", "djr": "Djambarrpuyngu", "dju": "Kapriman", "djw": "Djawi", "dka": "Dakpakha", "dkg": "Kadung", "dkk": "Dakka", "dkr": "Kuijau", "dks": "Southeastern Dinka", "dkx": "Mazagway", "dlg": "Dolgan", "dlk": "Dahalik", "dlm": "Dalmatian", "dln": "Darlong", "dma": "Duma", "dmb": "Mombo Dogon", "dmc": "Gavak", "dmd": "Madhi Madhi", "dme": "Dugwor", "dmf": "Medefaidrin", "dmg": "Upper Kinabatangan", "dmk": "Domaaki", "dml": "Dameli", "dmm": "Dama", "dmn": "Mande languages", "dmo": "Kemedzung", "dmr": "East Damar", "dms": "Dampelas", "dmu": "Dubu; Tebi", "dmv": "Dumpas", "dmw": "Mudburra", "dmx": "Dema", "dmy": "Demta; Sowari", "dna": "Upper Grand Valley Dani", "dnd": "Daonda", "dne": "Ndendeule", "dng": "Dungan", "dni": "Lower Grand Valley Dani", "dnj": "Dan", "dnk": "Dengka", "dnn": "Dzùùngoo", "dno": "Ndrulo; Northern Lendu", "dnr": "Danaru", "dnt": "Mid Grand Valley Dani", "dnu": "Danau", "dnv": "Danu", "dnw": "Western Dani", "dny": "Dení", "doa": "Dom", "dob": "Dobu", "doc": "Northern Dong", "doe": "Doe", "dof": "Domu", "doh": "Dong", "doi": "Dogri (macrolanguage)", "dok": "Dondo", "dol": "Doso", "don": "Toura (Papua New Guinea)", "doo": "Dongo", "dop": "Lukpa", "doq": "Dominican Sign Language", "dor": "Dori'o", "dos": "Dogosé", "dot": "Dass", "dov": "Dombe", "dow": "Doyayo", "dox": "Bussa", "doy": "Dompo", "doz": "Dorze", "dpp": "Papar", "dra": "Dravidian languages", "drb": "Dair", "drc": "Minderico", "drd": "Darmiya", "dre": "Dolpo", "drg": "Rungus", "dri": "C'Lela", "drl": "Paakantyi", "drn": "West Damar", "dro": "Daro-Matu Melanau", "drq": "Dura", "drs": "Gedeo", "drt": "Drents", "dru": "Rukai", "dry": "Darai", "dsb": "Lower Sorbian", "dse": "Dutch Sign Language", "dsh": "Daasanach", "dsi": "Disa", "dsl": "Danish Sign Language", "dsn": "Dusner", "dso": "Desiya", "dsq": "Tadaksahak", "dsz": "Mardin Sign Language", "dta": "Daur", "dtb": "Labuk-Kinabatangan Kadazan", "dtd": "Ditidaht", "dth": "Adithinngithigh", "dti": "Ana Tinga Dogon", "dtk": "Tene Kan Dogon", "dtm": "Tomo Kan Dogon", "dtn": "Daatsʼíin", "dto": "Tommo So Dogon", "dtp": "Kadazan Dusun; Central Dusun", "dtr": "Lotud", "dts": "Toro So Dogon", "dtt": "Toro Tegu Dogon", "dtu": "Tebul Ure Dogon", "dty": "Dotyali", "dua": "Duala", "dub": "Dubli", "duc": "Duna", "due": "Umiray Dumaget Agta", "duf": "Dumbea; Drubea", "dug": "Duruma; Chiduruma", "duh": "Dungra Bhil", "dui": "Dumun", "duk": "Uyajitaya", "dul": "Alabat Island Agta", "dum": "Middle Dutch (ca. 1050-1350)", "dun": "Dusun Deyah", "duo": "Dupaninan Agta", "dup": "Duano", "duq": "Dusun Malang", "dur": "Dii", "dus": "Dumi", "duu": "Drung", "duv": "Duvle", "duw": "Dusun Witu", "dux": "Duungooma", "duy": "Dicamay Agta", "duz": "Duli-Gey", "dv": "Dhivehi; Divehi; Maldivian", "dva": "Duau", "dwa": "Diri", "dwk": "Dawik Kui", "dwr": "Dawro", "dws": "Dutton World Speedwords", "dwu": "Dhuwal", "dww": "Dawawa", "dwy": "Dhuwaya", "dwz": "Dewas Rai", "dya": "Dyan", "dyb": "Dyaberdyaber", "dyd": "Dyugun", "dyg": "Villa Viciosa Agta", "dyi": "Djimini Senoufo", "dym": "Yanda Dom Dogon", "dyn": "Dyangadi; Dhanggatti", "dyo": "Jola-Fonyi", "dyu": "Dyula", "dyy": "Djabugay; Dyaabugay", "dz": "Dzongkha", "dza": "Tunzu", "dze": "Djiwarli", "dzg": "Dazaga", "dzl": "Dzalakha", "dzn": "Dzando", "eaa": "Karenggapa", "ebc": "Beginci", "ebg": "Ebughu", "ebk": "Eastern Bontok", "ebo": "Teke-Ebo", "ebr": "Ebrié", "ebu": "Embu; Kiembu", "ecr": "Eteocretan", "ecs": "Ecuadorian Sign Language", "ecy": "Eteocypriot", "ee": "Ewe", "eee": "E", "efa": "Efai", "efe": "Efe", "efi": "Efik", "ega": "Ega", "egl": "Emilian", "egm": "Benamanga", "ego": "Eggon", "egx": "Egyptian languages", "egy": "Egyptian (Ancient)", "ehs": "Miyakubo Sign Language", "ehu": "Ehueun", "eip": "Eipomek", "eit": "Eitiep", "eiv": "Askopan", "eja": "Ejamat", "eka": "Ekajuk", "eke": "Ekit", "ekg": "Ekari", "eki": "Eki", "ekk": "Standard Estonian", "ekl": "Kol (Bangladesh); Kol", "ekm": "Elip", "eko": "Koti", "ekp": "Ekpeye", "ekr": "Yace", "eky": "Eastern Kayah", "el": "Modern Greek (1453-)", "ele": "Elepi", "elh": "El Hugeirat", "eli": "Nding", "elk": "Elkei", "elm": "Eleme", "elo": "El Molo", "elu": "Elu", "elx": "Elamite", "ema": "Emai-Iuleha-Ora", "emb": "Embaloh", "eme": "Emerillon", "emg": "Eastern Meohang", "emi": "Mussau-Emira", "emk": "Eastern Maninkakan", "emm": "Mamulique", "emn": "Eman", "emp": "Northern Emberá", "emq": "Eastern Minyag", "ems": "Pacific Gulf Yupik", "emu": "Eastern Muria", "emw": "Emplawas", "emx": "Erromintxela", "emy": "Epigraphic Mayan", "emz": "Mbessa", "en": "English", "ena": "Apali", "enb": "Markweeta", "enc": "En", "end": "Ende", "enf": "Forest Enets", "enh": "Tundra Enets", "enl": "Enlhet", "enm": "Middle English (1100-1500)", "enn": "Engenni", "eno": "Enggano", "enq": "Enga", "enr": "Emumu; Emem", "enu": "Enu", "env": "Enwan (Edo State)", "enw": "Enwan (Akwa Ibom State)", "enx": "Enxet", "eo": "Esperanto", "eot": "Beti (Côte d'Ivoire)", "epi": "Epie", "era": "Eravallan", "erg": "Sie", "erh": "Eruwa", "eri": "Ogea", "erk": "South Efate", "ero": "Horpa", "err": "Erre", "ers": "Ersu", "ert": "Eritai", "erw": "Erokwanas", "es": "Spanish; Castilian", "ese": "Ese Ejja", "esg": "Aheri Gondi", "esh": "Eshtehardi", "esi": "North Alaskan Inupiatun", "esk": "Northwest Alaska Inupiatun", "esl": "Egypt Sign Language", "esm": "Esuma", "esn": "Salvadoran Sign Language", "eso": "Estonian Sign Language", "esq": "Esselen", "ess": "Central Siberian Yupik", "esu": "Central Yupik", "esx": "Eskimo-Aleut languages", "esy": "Eskayan", "et": "Estonian", "etb": "Etebi", "etc": "Etchemin", "eth": "Ethiopian Sign Language", "etn": "Eton (Vanuatu)", "eto": "Eton (Cameroon)", "etr": "Edolo", "ets": "Yekhee", "ett": "Etruscan", "etu": "Ejagham", "etx": "Eten", "etz": "Semimi", "eu": "Basque", "euq": "Basque (family)", "eve": "Even", "evh": "Uvbie", "evn": "Evenki", "ewo": "Ewondo", "ext": "Extremaduran", "eya": "Eyak", "eyo": "Keiyo", "eza": "Ezaa", "eze": "Uzekwe", "fa": "Persian", "faa": "Fasu", "fab": "Fa d'Ambu", "fad": "Wagi", "faf": "Fagani", "fag": "Finongan", "fah": "Baissa Fali", "fai": "Faiwol", "faj": "Faita", "fak": "Fang (Cameroon)", "fal": "South Fali", "fam": "Fam", "fan": "Fang (Equatorial Guinea)", "fap": "Paloor", "far": "Fataleka", "fat": "Fanti", "fau": "Fayu", "fax": "Fala", "fay": "Southwestern Fars", "faz": "Northwestern Fars", "fbl": "West Albay Bikol", "fcs": "Quebec Sign Language", "fer": "Feroge", "ff": "Fulah", "ffi": "Foia Foia", "ffm": "Maasina Fulfulde", "fgr": "Fongoro", "fi": "Finnish", "fia": "Nobiin", "fie": "Fyer", "fif": "Faifi", "fil": "Filipino; Pilipino", "fip": "Fipa", "fir": "Firan", "fit": "Tornedalen Finnish; Meänkieli", "fiu": "Finno-Ugrian languages", "fiw": "Fiwaga", "fj": "Fijian", "fkk": "Kirya-Konzəl", "fkv": "Kven Finnish", "fla": "Kalispel-Pend d'Oreille", "flh": "Foau", "fli": "Fali", "fll": "North Fali", "fln": "Flinders Island", "flr": "Fuliiru", "fly": "Flaaitaal; Tsotsitaal", "fmp": "Fe'fe'", "fmu": "Far Western Muria", "fnb": "Fanbak", "fng": "Fanagalo", "fni": "Fania", "fo": "Faroese", "fod": "Foodo", "foi": "Foi", "fom": "Foma", "fon": "Fon", "for": "Fore", "fos": "Siraya", "fox": "Formosan languages", "fpe": "Fernando Po Creole English", "fqs": "Fas", "fr": "French", "frc": "Cajun French", "frd": "Fordata", "frk": "Frankish", "frm": "Middle French (ca. 1400-1600)", "fro": "Old French (842-ca. 1400)", "frp": "Arpitan; Francoprovençal", "frq": "Forak", "frr": "Northern Frisian", "frs": "Eastern Frisian", "frt": "Fortsenal", "fse": "Finnish Sign Language", "fsl": "French Sign Language", "fss": "Finland-Swedish Sign Language; finlandssvenskt teckenspråk; suomenruotsalainen viittomakieli", "fub": "Adamawa Fulfulde", "fuc": "Pulaar", "fud": "East Futuna", "fue": "Borgu Fulfulde", "fuf": "Pular", "fuh": "Western Niger Fulfulde", "fui": "Bagirmi Fulfulde", "fuj": "Ko", "fum": "Fum", "fun": "Fulniô", "fuq": "Central-Eastern Niger Fulfulde", "fur": "Friulian", "fut": "Futuna-Aniwa", "fuu": "Furu", "fuv": "Nigerian Fulfulde", "fuy": "Fuyug", "fvr": "Fur", "fwa": "Fwâi", "fwe": "Fwe", "fy": "Western Frisian", "ga": "Irish", "gaa": "Ga", "gab": "Gabri", "gac": "Mixed Great Andamanese", "gad": "Gaddang", "gae": "Guarequena", "gaf": "Gende", "gag": "Gagauz", "gah": "Alekano", "gai": "Borei", "gaj": "Gadsup", "gak": "Gamkonora", "gal": "Galolen", "gam": "Kandawo", "gan": "Gan Chinese", "gao": "Gants", "gap": "Gal", "gaq": "Gata'", "gar": "Galeya", "gas": "Adiwasi Garasia", "gat": "Kenati", "gau": "Mudhili Gadaba", "gaw": "Nobonob", "gax": "Borana-Arsi-Guji Oromo", "gay": "Gayo", "gaz": "West Central Oromo", "gba": "Gbaya (Central African Republic)", "gbb": "Kaytetye", "gbd": "Karajarri", "gbe": "Niksek", "gbf": "Gaikundi", "gbg": "Gbanziri", "gbh": "Defi Gbe", "gbi": "Galela", "gbj": "Bodo Gadaba", "gbk": "Gaddi", "gbl": "Gamit", "gbm": "Garhwali", "gbn": "Mo'da", "gbo": "Northern Grebo", "gbp": "Gbaya-Bossangoa", "gbq": "Gbaya-Bozoum", "gbr": "Gbagyi", "gbs": "Gbesi Gbe", "gbu": "Gagadu", "gbv": "Gbanu", "gbw": "Gabi-Gabi", "gbx": "Eastern Xwla Gbe", "gby": "Gbari", "gbz": "Zoroastrian Dari", "gcc": "Mali", "gcd": "Ganggalida", "gce": "Galice", "gcf": "Guadeloupean Creole French", "gcl": "Grenadian Creole English", "gcn": "Gaina", "gcr": "Guianese Creole French", "gct": "Colonia Tovar German", "gd": "Scottish Gaelic; Gaelic", "gda": "Gade Lohar", "gdb": "Pottangi Ollar Gadaba", "gdc": "Gugu Badhun", "gdd": "Gedaged", "gde": "Gude", "gdf": "Guduf-Gava", "gdg": "Ga'dang", "gdh": "Gadjerawang; Gajirrabeng", "gdi": "Gundi", "gdj": "Gurdjar", "gdk": "Gadang", "gdl": "Dirasha", "gdm": "Laal", "gdn": "Umanakaina", "gdo": "Ghodoberi", "gdq": "Mehri", "gdr": "Wipi", "gds": "Ghandruk Sign Language", "gdt": "Kungardutyi", "gdu": "Gudu", "gdx": "Godwari", "gea": "Geruma", "geb": "Kire", "gec": "Gboloo Grebo", "ged": "Gade", "gef": "Gerai", "geg": "Gengle", "geh": "Hutterite German; Hutterisch", "gei": "Gebe", "gej": "Gen", "gek": "Ywom", "gel": "ut-Ma'in", "gem": "Germanic languages", "geq": "Geme", "ges": "Geser-Gorom", "gev": "Eviya", "gew": "Gera", "gex": "Garre", "gey": "Enya", "gez": "Geez", "gfk": "Patpatar", "gft": "Gafat", "gga": "Gao", "ggb": "Gbii", "ggd": "Gugadj", "gge": "Gurr-goni", "ggg": "Gurgula", "ggk": "Kungarakany", "ggl": "Ganglau", "ggt": "Gitua", "ggu": "Gagu; Gban", "ggw": "Gogodala", "gha": "Ghadamès", "ghc": "Hiberno-Scottish Gaelic", "ghe": "Southern Ghale", "ghh": "Northern Ghale", "ghk": "Geko Karen", "ghl": "Ghulfan", "ghn": "Ghanongga", "gho": "Ghomara", "ghr": "Ghera", "ghs": "Guhu-Samane", "ght": "Kuke; Kutang Ghale", "gia": "Kija", "gib": "Gibanawa", "gic": "Gail", "gid": "Gidar", "gie": "Gaɓogbo; Guébie", "gig": "Goaria", "gih": "Githabul", "gii": "Girirra", "gil": "Gilbertese", "gim": "Gimi (Eastern Highlands)", "gin": "Hinukh", "gip": "Gimi (West New Britain)", "giq": "Green Gelao", "gir": "Red Gelao", "gis": "North Giziga", "git": "Gitxsan", "giu": "Mulao", "giw": "White Gelao", "gix": "Gilima", "giy": "Giyug", "giz": "South Giziga", "gjk": "Kachi Koli", "gjm": "Gunditjmara", "gjn": "Gonja", "gjr": "Gurindji Kriol", "gju": "Gujari", "gka": "Guya", "gkd": "Magɨ (Madang Province)", "gke": "Ndai", "gkn": "Gokana", "gko": "Kok-Nar", "gkp": "Guinea Kpelle", "gku": "ǂUngkue", "gl": "Galician", "glb": "Belning", "glc": "Bon Gula", "gld": "Nanai", "glh": "Northwest Pashai; Northwest Pashayi", "glj": "Gula Iro", "glk": "Gilaki", "gll": "Garlali", "glo": "Galambu", "glr": "Glaro-Twabo", "glu": "Gula (Chad)", "glw": "Glavda", "gly": "Gule", "gma": "Gambera", "gmb": "Gula'alaa", "gmd": "Mághdì", "gme": "East Germanic languages", "gmg": "Magɨyi", "gmh": "Middle High German (ca. 1050-1500)", "gml": "Middle Low German", "gmm": "Gbaya-Mbodomo", "gmn": "Gimnime", "gmq": "North Germanic languages", "gmr": "Mirning; Mirniny", "gmu": "Gumalu", "gmv": "Gamo", "gmw": "West Germanic languages", "gmx": "Magoma", "gmy": "Mycenaean Greek", "gmz": "Mgbolizhia", "gn": "Guarani", "gna": "Kaansa", "gnb": "Gangte", "gnc": "Guanche", "gnd": "Zulgo-Gemzek", "gne": "Ganang", "gng": "Ngangam", "gnh": "Lere", "gni": "Gooniyandi", "gnj": "Ngen", "gnk": "ǁGana", "gnl": "Gangulu", "gnm": "Ginuman", "gnn": "Gumatj", "gno": "Northern Gondi", "gnq": "Gana", "gnr": "Gureng Gureng", "gnt": "Guntai", "gnu": "Gnau", "gnw": "Western Bolivian Guaraní", "gnz": "Ganzi", "goa": "Guro", "gob": "Playero", "goc": "Gorakor", "god": "Godié", "goe": "Gongduk", "gof": "Gofa", "gog": "Gogo", "goh": "Old High German (ca. 750-1050)", "goi": "Gobasi", "goj": "Gowlan", "gok": "Gowli", "gol": "Gola", "gom": "Goan Konkani", "gon": "Gondi", "goo": "Gone Dau", "gop": "Yeretuar", "goq": "Gorap", "gor": "Gorontalo", "gos": "Gronings", "got": "Gothic", "gou": "Gavar", "gov": "Goo", "gow": "Gorowa", "gox": "Gobu", "goy": "Goundo", "goz": "Gozarkhani", "gpa": "Gupa-Abawa", "gpe": "Ghanaian Pidgin English", "gpn": "Taiap", "gqa": "Ga'anda", "gqi": "Guiqiong", "gqn": "Guana (Brazil)", "gqr": "Gor", "gqu": "Qau", "gra": "Rajput Garasia", "grb": "Grebo", "grc": "Ancient Greek (to 1453)", "grd": "Guruntum-Mbaaru", "grg": "Madi", "grh": "Gbiri-Niragu", "gri": "Ghari", "grj": "Southern Grebo", "grk": "Greek languages", "grm": "Kota Marudu Talantang", "gro": "Groma", "grq": "Gorovu", "grr": "Taznatit", "grs": "Gresi", "grt": "Garo", "gru": "Kistane", "grv": "Central Grebo", "grw": "Gweda", "grx": "Guriaso", "gry": "Barclayville Grebo", "grz": "Guramalum", "gse": "Ghanaian Sign Language", "gsg": "German Sign Language", "gsl": "Gusilay", "gsm": "Guatemalan Sign Language", "gsn": "Nema; Gusan", "gso": "Southwest Gbaya", "gsp": "Wasembo", "gss": "Greek Sign Language", "gsw": "Swiss German; Alemannic; Alsatian", "gta": "Guató", "gtu": "Aghu-Tharnggala", "gu": "Gujarati", "gua": "Shiki", "gub": "Guajajára", "guc": "Wayuu", "gud": "Yocoboué Dida", "gue": "Gurindji", "guf": "Gupapuyngu", "gug": "Paraguayan Guaraní", "guh": "Guahibo", "gui": "Eastern Bolivian Guaraní", "guk": "Gumuz", "gul": "Sea Island Creole English", "gum": "Guambiano", "gun": "Mbyá Guaraní", "guo": "Guayabero", "gup": "Gunwinggu", "guq": "Aché", "gur": "Farefare", "gus": "Guinean Sign Language", "gut": "Maléku Jaíka", "guu": "Yanomamö", "guw": "Gun", "gux": "Gourmanchéma", "guz": "Gusii; Ekegusii", "gv": "Manx", "gva": "Guana (Paraguay)", "gvc": "Guanano", "gve": "Duwet", "gvf": "Golin", "gvj": "Guajá", "gvl": "Gulay", "gvm": "Gurmana", "gvn": "Kuku-Yalanji", "gvo": "Gavião Do Jiparaná", "gvp": "Pará Gavião", "gvr": "Gurung", "gvs": "Gumawana", "gvy": "Guyani", "gwa": "Mbato", "gwb": "Gwa", "gwc": "Gawri; Kalami", "gwd": "Gawwada", "gwe": "Gweno", "gwf": "Gowro", "gwg": "Moo", "gwi": "Gwichʼin", "gwj": "ǀGwi", "gwm": "Awngthim", "gwn": "Gwandara", "gwr": "Gwere", "gwt": "Gawar-Bati", "gwu": "Guwamu", "gww": "Kwini", "gwx": "Gua", "gxx": "Wè Southern", "gya": "Northwest Gbaya", "gyb": "Garus", "gyd": "Kayardild", "gye": "Gyem", "gyf": "Gungabula", "gyg": "Gbayi", "gyi": "Gyele", "gyl": "Gayil", "gym": "Ngäbere", "gyn": "Guyanese Creole English", "gyo": "Gyalsumdo", "gyr": "Guarayu", "gyy": "Gunya", "gyz": "Geji; Gyaazi", "gza": "Ganza", "gzi": "Gazi", "gzn": "Gane", "ha": "Hausa", "haa": "Han", "hab": "Hanoi Sign Language", "hac": "Gurani", "had": "Hatam", "hae": "Eastern Oromo", "haf": "Haiphong Sign Language", "hag": "Hanga", "hah": "Hahon", "hai": "Haida", "haj": "Hajong", "hak": "Hakka Chinese", "hal": "Halang", "ham": "Hewa", "han": "Hangaza", "hao": "Hakö", "hap": "Hupla", "haq": "Ha", "har": "Harari", "has": "Haisla", "hav": "Havu", "haw": "Hawaiian", "hax": "Southern Haida", "hay": "Haya", "haz": "Hazaragi", "hba": "Hamba", "hbb": "Huba", "hbn": "Heiban", "hbo": "Ancient Hebrew", "hbu": "Habu", "hca": "Andaman Creole Hindi", "hch": "Huichol", "hdn": "Northern Haida", "hds": "Honduras Sign Language", "hdy": "Hadiyya", "he": "Hebrew", "hea": "Northern Qiandong Miao", "hed": "Herdé", "heg": "Helong", "heh": "Hehe", "hei": "Heiltsuk", "hem": "Hemba", "hgm": "Haiǁom", "hgw": "Haigwai", "hhi": "Hoia Hoia", "hhr": "Kerak", "hhy": "Hoyahoya", "hi": "Hindi", "hia": "Lamang", "hib": "Hibito", "hid": "Hidatsa", "hif": "Fiji Hindi", "hig": "Kamwe", "hih": "Pamosu", "hii": "Hinduri", "hij": "Hijuk", "hik": "Seit-Kaitetu", "hil": "Hiligaynon", "him": "Himachali languages; Western Pahari languages", "hio": "Tsoa", "hir": "Himarimã", "hit": "Hittite", "hiw": "Hiw", "hix": "Hixkaryána", "hji": "Haji", "hka": "Kahe", "hke": "Hunde", "hkh": "Khah; Poguli", "hkk": "Hunjara-Kaina Ke", "hkn": "Mel-Khaonh", "hks": "Hong Kong Sign Language; Heung Kong Sau Yue", "hla": "Halia", "hlb": "Halbi", "hld": "Halang Doan", "hle": "Hlersu", "hlt": "Matu Chin", "hlu": "Hieroglyphic Luwian", "hma": "Southern Mashan Hmong; Southern Mashan Miao", "hmb": "Humburi Senni Songhay", "hmc": "Central Huishui Hmong; Central Huishui Miao", "hmd": "Large Flowery Miao; A-hmaos; Da-Hua Miao", "hme": "Eastern Huishui Hmong; Eastern Huishui Miao", "hmf": "Hmong Don", "hmg": "Southwestern Guiyang Hmong", "hmh": "Southwestern Huishui Hmong; Southwestern Huishui Miao", "hmi": "Northern Huishui Hmong; Northern Huishui Miao", "hmj": "Ge; Gejia", "hmk": "Maek", "hml": "Luopohe Hmong; Luopohe Miao", "hmm": "Central Mashan Hmong; Central Mashan Miao", "hmn": "Hmong; Mong", "hmp": "Northern Mashan Hmong; Northern Mashan Miao", "hmq": "Eastern Qiandong Miao", "hmr": "Hmar", "hms": "Southern Qiandong Miao", "hmt": "Hamtai", "hmu": "Hamap", "hmv": "Hmong Dô", "hmw": "Western Mashan Hmong; Western Mashan Miao", "hmx": "Hmong-Mien languages", "hmy": "Southern Guiyang Hmong; Southern Guiyang Miao", "hmz": "Hmong Shua; Sinicized Miao", "hna": "Mina (Cameroon)", "hnd": "Southern Hindko", "hne": "Chhattisgarhi", "hng": "Hungu", "hnh": "ǁAni", "hni": "Hani", "hnj": "Hmong Njua; Mong Leng; Mong Njua", "hnn": "Hanunoo", "hno": "Northern Hindko", "hns": "Caribbean Hindustani", "hnu": "Hung", "ho": "Hiri Motu", "hoa": "Hoava", "hob": "Mari (Madang Province)", "hoc": "Ho", "hod": "Holma", "hoe": "Horom", "hoh": "Hobyót", "hoi": "Holikachuk", "hoj": "Hadothi; Haroti", "hok": "Hokan languages", "hol": "Holu", "hom": "Homa", "hoo": "Holoholo", "hop": "Hopi", "hor": "Horo", "hos": "Ho Chi Minh City Sign Language", "hot": "Hote; Malê", "hov": "Hovongan", "how": "Honi", "hoy": "Holiya", "hoz": "Hozo", "hpo": "Hpon", "hps": "Hawai'i Sign Language (HSL); Hawai'i Pidgin Sign Language", "hr": "Croatian", "hra": "Hrangkhol", "hrc": "Niwer Mil", "hre": "Hre", "hrk": "Haruku", "hrm": "Horned Miao", "hro": "Haroi", "hrp": "Nhirrpi", "hrt": "Hértevin", "hru": "Hruso", "hrw": "Warwar Feni", "hrx": "Hunsrik", "hrz": "Harzani", "hsb": "Upper Sorbian", "hsh": "Hungarian Sign Language", "hsl": "Hausa Sign Language", "hsn": "Xiang Chinese", "hss": "Harsusi", "ht": "Haitian; Haitian Creole", "hti": "Hoti", "hto": "Minica Huitoto", "hts": "Hadza", "htu": "Hitu", "htx": "Middle Hittite", "hu": "Hungarian", "hub": "Huambisa", "huc": "ǂHua; ǂʼAmkhoe", "hud": "Huaulu", "hue": "San Francisco Del Mar Huave", "huf": "Humene", "hug": "Huachipaeri", "huh": "Huilliche", "hui": "Huli", "huj": "Northern Guiyang Hmong; Northern Guiyang Miao", "huk": "Hulung", "hul": "Hula", "hum": "Hungana", "huo": "Hu", "hup": "Hupa", "huq": "Tsat", "hur": "Halkomelem", "hus": "Huastec", "hut": "Humla", "huu": "Murui Huitoto", "huv": "San Mateo Del Mar Huave", "huw": "Hukumina", "hux": "Nüpode Huitoto", "huy": "Hulaulá", "huz": "Hunzib", "hvc": "Haitian Vodoun Culture Language", "hve": "San Dionisio Del Mar Huave", "hvk": "Haveke", "hvn": "Sabu", "hvv": "Santa María Del Mar Huave", "hwa": "Wané", "hwc": "Hawai'i Creole English; Hawai'i Pidgin", "hwo": "Hwana", "hy": "Armenian", "hya": "Hya", "hyw": "Western Armenian", "hyx": "Armenian (family)", "hz": "Herero", "ia": "Interlingua (International Auxiliary Language Association)", "iai": "Iaai", "ian": "Iatmul", "iar": "Purari", "iba": "Iban", "ibb": "Ibibio", "ibd": "Iwaidja", "ibe": "Akpes", "ibg": "Ibanag", "ibh": "Bih", "ibl": "Ibaloi", "ibm": "Agoi", "ibn": "Ibino", "ibr": "Ibuoro", "ibu": "Ibu", "iby": "Ibani", "ica": "Ede Ica", "ich": "Etkywan", "icl": "Icelandic Sign Language", "icr": "Islander Creole English", "id": "Indonesian", "ida": "Idakho-Isukha-Tiriki; Luidakho-Luisukha-Lutirichi", "idb": "Indo-Portuguese", "idc": "Idon; Ajiya", "idd": "Ede Idaca", "ide": "Idere", "idi": "Idi", "idr": "Indri", "ids": "Idesa", "idt": "Idaté", "idu": "Idoma", "ie": "Interlingue; Occidental", "ifa": "Amganad Ifugao", "ifb": "Batad Ifugao; Ayangan Ifugao", "ife": "Ifè", "iff": "Ifo", "ifk": "Tuwali Ifugao", "ifm": "Teke-Fuumu", "ifu": "Mayoyao Ifugao", "ify": "Keley-I Kallahan", "ig": "Igbo", "igb": "Ebira", "ige": "Igede", "igg": "Igana", "igl": "Igala", "igm": "Kanggape", "ign": "Ignaciano", "igo": "Isebe", "igs": "Interglossa", "igw": "Igwe", "ihb": "Iha Based Pidgin", "ihi": "Ihievbe", "ihp": "Iha", "ihw": "Bidhawal", "ii": "Sichuan Yi; Nuosu", "iin": "Thiin", "iir": "Indo-Iranian languages", "ijc": "Izon", "ije": "Biseni", "ijj": "Ede Ije", "ijn": "Kalabari", "ijo": "Ijo languages", "ijs": "Southeast Ijo", "ik": "Inupiaq", "ike": "Eastern Canadian Inuktitut", "iki": "Iko", "ikk": "Ika", "ikl": "Ikulu", "iko": "Olulumo-Ikom", "ikp": "Ikpeshi", "ikr": "Ikaranggal", "iks": "Inuit Sign Language", "ikt": "Inuinnaqtun; Western Canadian Inuktitut", "ikv": "Iku-Gora-Ankwa", "ikw": "Ikwere", "ikx": "Ik", "ikz": "Ikizu", "ila": "Ile Ape", "ilb": "Ila", "ilg": "Garig-Ilgar", "ili": "Ili Turki", "ilk": "Ilongot", "ilm": "Iranun (Malaysia)", "ilo": "Iloko", "ilp": "Iranun (Philippines)", "ils": "International Sign", "ilu": "Ili'uun", "ilv": "Ilue", "ima": "Mala Malasar", "imi": "Anamgura", "iml": "Miluk", "imn": "Imonda", "imo": "Imbongu", "imr": "Imroing", "ims": "Marsian", "imt": "Imotong", "imy": "Milyan", "inb": "Inga", "inc": "Indic languages", "ine": "Indo-European languages", "ing": "Degexit'an", "inh": "Ingush", "inj": "Jungle Inga", "inl": "Indonesian Sign Language", "inm": "Minaean", "inn": "Isinai", "ino": "Inoke-Yate", "inp": "Iñapari", "ins": "Indian Sign Language", "int": "Intha", "inz": "Ineseño", "io": "Ido", "ior": "Inor", "iou": "Tuma-Irumu", "iow": "Iowa-Oto", "ipi": "Ipili", "ipo": "Ipiko", "iqu": "Iquito", "iqw": "Ikwo", "ira": "Iranian languages", "ire": "Iresim", "irh": "Irarutu", "iri": "Rigwe; Irigwe", "irk": "Iraqw", "irn": "Irántxe", "iro": "Iroquoian languages", "irr": "Ir", "iru": "Irula", "irx": "Kamberau", "iry": "Iraya", "is": "Icelandic", "isa": "Isabi", "isc": "Isconahua", "isd": "Isnag", "ise": "Italian Sign Language", "isg": "Irish Sign Language", "ish": "Esan", "isi": "Nkem-Nkum", "isk": "Ishkashimi", "ism": "Masimasi", "isn": "Isanzu", "iso": "Isoko", "isr": "Israeli Sign Language", "ist": "Istriot", "isu": "Isu (Menchum Division)", "it": "Italian", "itb": "Binongan Itneg", "itc": "Italic languages", "itd": "Southern Tidung", "ite": "Itene", "iti": "Inlaod Itneg", "itk": "Judeo-Italian", "itl": "Itelmen", "itm": "Itu Mbon Uzo", "ito": "Itonama", "itr": "Iteri", "its": "Isekiri", "itt": "Maeng Itneg", "itv": "Itawit", "itw": "Ito", "itx": "Itik", "ity": "Moyadan Itneg", "itz": "Itzá", "iu": "Inuktitut", "ium": "Iu Mien", "ivb": "Ibatan", "ivv": "Ivatan", "iwk": "I-Wak", "iwm": "Iwam", "iwo": "Iwur", "iws": "Sepik Iwam", "ixc": "Ixcatec", "ixl": "Ixil", "iya": "Iyayu", "iyo": "Mesaka", "iyx": "Yaka (Congo)", "izh": "Ingrian", "izr": "Izere", "izz": "Izii", "ja": "Japanese", "jaa": "Jamamadí", "jab": "Hyam", "jac": "Popti'; Jakalteko", "jad": "Jahanka", "jae": "Yabem", "jaf": "Jara", "jah": "Jah Hut", "jaj": "Zazao", "jak": "Jakun", "jal": "Yalahatan", "jam": "Jamaican Creole English", "jan": "Jandai", "jao": "Yanyuwa", "jaq": "Yaqay", "jas": "New Caledonian Javanese", "jat": "Jakati", "jau": "Yaur", "jax": "Jambi Malay", "jay": "Yan-nhangu; Nhangu", "jaz": "Jawe", "jbe": "Judeo-Berber", "jbi": "Badjiri", "jbj": "Arandai", "jbk": "Barikewa", "jbm": "Bijim", "jbn": "Nafusi", "jbo": "Lojban", "jbr": "Jofotek-Bromnya", "jbt": "Jabutí", "jbu": "Jukun Takum", "jbw": "Yawijibaya", "jcs": "Jamaican Country Sign Language", "jct": "Krymchak", "jda": "Jad", "jdg": "Jadgali", "jdt": "Judeo-Tat", "jeb": "Jebero", "jee": "Jerung", "jeh": "Jeh", "jei": "Yei", "jek": "Jeri Kuo", "jel": "Yelmek", "jen": "Dza", "jer": "Jere", "jet": "Manem", "jeu": "Jonkor Bourmataguil", "jgb": "Ngbee", "jge": "Judeo-Georgian", "jgk": "Gwak", "jgo": "Ngomba", "jhi": "Jehai", "jhs": "Jhankot Sign Language", "jia": "Jina", "jib": "Jibu", "jic": "Tol", "jid": "Bu (Kaduna State)", "jie": "Jilbe", "jig": "Jingulu; Djingili", "jih": "sTodsde; Shangzhai", "jii": "Jiiddu", "jil": "Jilim", "jim": "Jimi (Cameroon)", "jio": "Jiamao", "jiq": "Guanyinqiao; Lavrung", "jit": "Jita", "jiu": "Youle Jinuo", "jiv": "Shuar", "jiy": "Buyuan Jinuo", "jje": "Jejueo", "jjr": "Bankal", "jka": "Kaera", "jkm": "Mobwa Karen", "jko": "Kubo", "jkp": "Paku Karen", "jkr": "Koro (India)", "jks": "Amami Koniya Sign Language", "jku": "Labir", "jle": "Ngile", "jls": "Jamaican Sign Language", "jma": "Dima", "jmb": "Zumbun", "jmc": "Machame", "jmd": "Yamdena", "jmi": "Jimi (Nigeria)", "jml": "Jumli", "jmn": "Makuri Naga", "jmr": "Kamara", "jms": "Mashi (Nigeria)", "jmw": "Mouwase", "jmx": "Western Juxtlahuaca Mixtec", "jna": "Jangshung", "jnd": "Jandavra", "jng": "Yangman", "jni": "Janji", "jnj": "Yemsa", "jnl": "Rawat", "jns": "Jaunsari", "job": "Joba", "jod": "Wojenaka", "jog": "Jogi", "jor": "Jorá", "jos": "Jordanian Sign Language", "jow": "Jowulu", "jpa": "Jewish Palestinian Aramaic", "jpr": "Judeo-Persian", "jpx": "Japanese (family)", "jqr": "Jaqaru", "jra": "Jarai", "jrb": "Judeo-Arabic", "jrr": "Jiru", "jrt": "Jakattoe", "jru": "Japrería", "jsl": "Japanese Sign Language", "jua": "Júma", "jub": "Wannu", "juc": "Jurchen", "jud": "Worodougou", "juh": "Hõne", "jui": "Ngadjuri", "juk": "Wapan", "jul": "Jirel", "jum": "Jumjum", "jun": "Juang", "juo": "Jiba", "jup": "Hupdë", "jur": "Jurúna", "jus": "Jumla Sign Language", "jut": "Jutish", "juu": "Ju", "juw": "Wãpha", "juy": "Juray", "jv": "Javanese", "jvd": "Javindo", "jvn": "Caribbean Javanese", "jwi": "Jwira-Pepesa", "jya": "Jiarong", "jye": "Judeo-Yemeni Arabic", "jyy": "Jaya", "ka": "Georgian", "kaa": "Kara-Kalpak; Karakalpak", "kab": "Kabyle", "kac": "Kachin; Jingpho", "kad": "Adara", "kae": "Ketangalan", "kaf": "Katso", "kag": "Kajaman", "kah": "Kara (Central African Republic)", "kai": "Karekare", "kaj": "Jju", "kak": "Kalanguya; Kayapa Kallahan", "kam": "Kamba (Kenya)", "kao": "Xaasongaxango", "kap": "Bezhta", "kaq": "Capanahua", "kar": "Karen languages", "kav": "Katukína", "kaw": "Kawi", "kax": "Kao", "kay": "Kamayurá", "kba": "Kalarko", "kbb": "Kaxuiâna", "kbc": "Kadiwéu", "kbd": "Kabardian", "kbe": "Kanju", "kbg": "Khamba", "kbh": "Camsá", "kbi": "Kaptiau", "kbj": "Kari", "kbk": "Grass Koiari", "kbl": "Kanembu", "kbm": "Iwal", "kbn": "Kare (Central African Republic)", "kbo": "Keliko", "kbp": "Kabiyè", "kbq": "Kamano", "kbr": "Kafa", "kbs": "Kande", "kbt": "Abadi", "kbu": "Kabutra", "kbv": "Dera (Indonesia)", "kbw": "Kaiep", "kbx": "Ap Ma", "kby": "Manga Kanuri", "kbz": "Duhwa", "kca": "Khanty", "kcb": "Kawacha", "kcc": "Lubila", "kcd": "Ngkâlmpw Kanum", "kce": "Kaivi", "kcf": "Ukaan", "kcg": "Tyap", "kch": "Vono", "kci": "Kamantan", "kcj": "Kobiana", "kck": "Kalanga", "kcl": "Kela (Papua New Guinea); Kala", "kcm": "Gula (Central African Republic)", "kcn": "Nubi", "kco": "Kinalakna", "kcp": "Kanga", "kcq": "Kamo", "kcr": "Katla", "kcs": "Koenoem", "kct": "Kaian", "kcu": "Kami (Tanzania)", "kcv": "Kete", "kcw": "Kabwari", "kcx": "Kachama-Ganjule", "kcy": "Korandje", "kcz": "Konongo", "kda": "Worimi", "kdc": "Kutu", "kdd": "Yankunytjatjara", "kde": "Makonde", "kdf": "Mamusi", "kdg": "Seba", "kdh": "Tem", "kdi": "Kumam", "kdj": "Karamojong", "kdk": "Numèè; Kwényi", "kdl": "Tsikimba", "kdm": "Kagoma", "kdn": "Kunda", "kdo": "Kordofanian languages", "kdp": "Kaningdon-Nindem", "kdq": "Koch", "kdr": "Karaim", "kdt": "Kuy", "kdu": "Kadaru", "kdw": "Koneraw", "kdx": "Kam", "kdy": "Keder; Keijar", "kdz": "Kwaja", "kea": "Kabuverdianu", "keb": "Kélé", "kec": "Keiga", "ked": "Kerewe", "kee": "Eastern Keres", "kef": "Kpessi", "keg": "Tese", "keh": "Keak", "kei": "Kei", "kej": "Kadar", "kek": "Kekchí", "kel": "Kela (Democratic Republic of Congo)", "kem": "Kemak", "ken": "Kenyang", "keo": "Kakwa", "kep": "Kaikadi", "keq": "Kamar", "ker": "Kera", "kes": "Kugbo", "ket": "Ket", "keu": "Akebu", "kev": "Kanikkaran", "kew": "West Kewa", "kex": "Kukna", "key": "Kupia", "kez": "Kukele", "kfa": "Kodava", "kfb": "Northwestern Kolami", "kfc": "Konda-Dora", "kfd": "Korra Koraga", "kfe": "Kota (India)", "kff": "Koya", "kfg": "Kudiya", "kfh": "Kurichiya", "kfi": "Kannada Kurumba", "kfj": "Kemiehua", "kfk": "Kinnauri", "kfl": "Kung", "kfm": "Khunsari", "kfn": "Kuk", "kfo": "Koro (Côte d'Ivoire)", "kfp": "Korwa", "kfq": "Korku", "kfr": "Kachhi; Kutchi", "kfs": "Bilaspuri", "kft": "Kanjari", "kfu": "Katkari", "kfv": "Kurmukar", "kfw": "Kharam Naga", "kfx": "Kullu Pahari", "kfy": "Kumaoni", "kfz": "Koromfé", "kg": "Kongo", "kga": "Koyaga", "kgb": "Kawe", "kge": "Komering", "kgf": "Kube", "kgg": "Kusunda", "kgi": "Selangor Sign Language", "kgj": "Gamale Kham", "kgk": "Kaiwá", "kgl": "Kunggari", "kgm": "Karipúna", "kgn": "Karingani", "kgo": "Krongo", "kgp": "Kaingang", "kgq": "Kamoro", "kgr": "Abun", "kgs": "Kumbainggar", "kgt": "Somyev", "kgu": "Kobol", "kgv": "Karas", "kgw": "Karon Dori", "kgx": "Kamaru", "kgy": "Kyerung", "kha": "Khasi", "khb": "Lü", "khc": "Tukang Besi North", "khd": "Bädi Kanum", "khe": "Korowai", "khf": "Khuen", "khg": "Khams Tibetan", "khh": "Kehu", "khi": "Khoisan languages", "khj": "Kuturmi", "khk": "Halh Mongolian", "khl": "Lusi", "khn": "Khandesi", "kho": "Khotanese; Sakan", "khp": "Kapori; Kapauri", "khq": "Koyra Chiini Songhay", "khr": "Kharia", "khs": "Kasua", "kht": "Khamti", "khu": "Nkhumbi", "khv": "Khvarshi", "khw": "Khowar", "khx": "Kanu", "khy": "Kele (Democratic Republic of Congo)", "khz": "Keapara", "ki": "Kikuyu; Gikuyu", "kia": "Kim", "kib": "Koalib", "kic": "Kickapoo", "kid": "Koshin", "kie": "Kibet", "kif": "Eastern Parbate Kham", "kig": "Kimaama; Kimaghima", "kih": "Kilmeri", "kii": "Kitsai", "kij": "Kilivila", "kil": "Kariya", "kim": "Karagas", "kio": "Kiowa", "kip": "Sheshi Kham", "kiq": "Kosadle; Kosare", "kis": "Kis", "kit": "Agob", "kiu": "Kirmanjki (individual language)", "kiv": "Kimbu", "kiw": "Northeast Kiwai", "kix": "Khiamniungan Naga", "kiy": "Kirikiri", "kiz": "Kisi", "kj": "Kuanyama; Kwanyama", "kja": "Mlap", "kjb": "Q'anjob'al; Kanjobal", "kjc": "Coastal Konjo", "kjd": "Southern Kiwai", "kje": "Kisar", "kjg": "Khmu", "kjh": "Khakas", "kji": "Zabana", "kjj": "Khinalugh", "kjk": "Highland Konjo", "kjl": "Western Parbate Kham", "kjm": "Kháng", "kjn": "Kunjen", "kjo": "Harijan Kinnauri", "kjp": "Pwo Eastern Karen", "kjq": "Western Keres", "kjr": "Kurudu", "kjs": "East Kewa", "kjt": "Phrae Pwo Karen", "kju": "Kashaya", "kjv": "Kaikavian Literary Language", "kjx": "Ramopa", "kjy": "Erave", "kjz": "Bumthangkha", "kk": "Kazakh", "kka": "Kakanda", "kkb": "Kwerisa", "kkc": "Odoodee", "kkd": "Kinuku", "kke": "Kakabe", "kkf": "Kalaktang Monpa", "kkg": "Mabaka Valley Kalinga", "kkh": "Khün", "kki": "Kagulu", "kkj": "Kako", "kkk": "Kokota", "kkl": "Kosarek Yale", "kkm": "Kiong", "kkn": "Kon Keu", "kko": "Karko", "kkp": "Gugubera; Koko-Bera", "kkq": "Kaeku", "kkr": "Kir-Balar", "kks": "Giiwo", "kkt": "Koi", "kku": "Tumi", "kkv": "Kangean", "kkw": "Teke-Kukuya", "kkx": "Kohin", "kky": "Guugu Yimidhirr; Guguyimidjir", "kkz": "Kaska", "kl": "Kalaallisut; Greenlandic", "kla": "Klamath-Modoc", "klb": "Kiliwa", "klc": "Kolbila", "kld": "Gamilaraay", "kle": "Kulung (Nepal)", "klf": "Kendeje", "klg": "Tagakaulo", "klh": "Weliki", "kli": "Kalumpang", "klj": "Khalaj", "klk": "Kono (Nigeria)", "kll": "Kagan Kalagan", "klm": "Migum", "kln": "Kalenjin", "klo": "Kapya", "klp": "Kamasa", "klq": "Rumu", "klr": "Khaling", "kls": "Kalasha", "klt": "Nukna", "klu": "Klao", "klv": "Maskelynes", "klw": "Tado; Lindu", "klx": "Koluwawa", "kly": "Kalao", "klz": "Kabola", "km": "Khmer; Central Khmer", "kma": "Konni", "kmb": "Kimbundu", "kmc": "Southern Dong", "kmd": "Majukayang Kalinga", "kme": "Bakole", "kmf": "Kare (Papua New Guinea)", "kmg": "Kâte", "kmh": "Kalam", "kmi": "Kami (Nigeria)", "kmj": "Kumarbhag Paharia", "kmk": "Limos Kalinga", "kml": "Tanudan Kalinga", "kmm": "Kom (India)", "kmn": "Awtuw", "kmo": "Kwoma", "kmp": "Gimme", "kmq": "Kwama", "kmr": "Northern Kurdish", "kms": "Kamasau", "kmt": "Kemtuik", "kmu": "Kanite", "kmv": "Karipúna Creole French", "kmw": "Komo (Democratic Republic of Congo)", "kmx": "Waboda", "kmy": "Koma", "kmz": "Khorasani Turkish", "kn": "Kannada", "kna": "Dera (Nigeria)", "knb": "Lubuagan Kalinga", "knc": "Central Kanuri", "knd": "Konda", "kne": "Kankanaey", "knf": "Mankanya", "kng": "Koongo", "kni": "Kanufi", "knj": "Western Kanjobal", "knk": "Kuranko", "knl": "Keninjal", "knm": "Kanamarí", "knn": "Konkani (individual language)", "kno": "Kono (Sierra Leone)", "knp": "Kwanja", "knq": "Kintaq", "knr": "Kaningra", "kns": "Kensiu", "knt": "Panoan Katukína", "knu": "Kono (Guinea)", "knv": "Tabo", "knw": "Kung-Ekoka", "knx": "Kendayan; Salako", "kny": "Kanyok", "knz": "Kalamsé", "ko": "Korean", "koa": "Konomala", "koc": "Kpati", "kod": "Kodi", "koe": "Kacipo-Bale Suri", "kof": "Kubi", "kog": "Cogui; Kogi", "koh": "Koyo", "koi": "Komi-Permyak", "kok": "Konkani (macrolanguage)", "kol": "Kol (Papua New Guinea)", "koo": "Konzo", "kop": "Waube", "koq": "Kota (Gabon)", "kos": "Kosraean", "kot": "Lagwan", "kou": "Koke", "kov": "Kudu-Camo", "kow": "Kugama", "koy": "Koyukon", "koz": "Korak", "kpa": "Kutto", "kpb": "Mullu Kurumba", "kpc": "Curripaco", "kpd": "Koba", "kpe": "Kpelle", "kpf": "Komba", "kpg": "Kapingamarangi", "kph": "Kplang", "kpi": "Kofei", "kpj": "Karajá", "kpk": "Kpan", "kpl": "Kpala", "kpm": "Koho", "kpn": "Kepkiriwát", "kpo": "Ikposo", "kpq": "Korupun-Sela", "kpr": "Korafe-Yegha", "kps": "Tehit", "kpt": "Karata", "kpu": "Kafoa", "kpv": "Komi-Zyrian", "kpw": "Kobon", "kpx": "Mountain Koiali", "kpy": "Koryak", "kpz": "Kupsabiny", "kqa": "Mum", "kqb": "Kovai", "kqc": "Doromu-Koki", "kqd": "Koy Sanjaq Surat", "kqe": "Kalagan", "kqf": "Kakabai", "kqg": "Khe", "kqh": "Kisankasa", "kqi": "Koitabu", "kqj": "Koromira", "kqk": "Kotafon Gbe", "kql": "Kyenele", "kqm": "Khisa", "kqn": "Kaonde", "kqo": "Eastern Krahn", "kqp": "Kimré", "kqq": "Krenak", "kqr": "Kimaragang", "kqs": "Northern Kissi", "kqt": "Klias River Kadazan", "kqu": "Seroa", "kqv": "Okolod", "kqw": "Kandas", "kqx": "Mser", "kqy": "Koorete", "kqz": "Korana", "kr": "Kanuri", "kra": "Kumhali", "krb": "Karkin", "krc": "Karachay-Balkar", "krd": "Kairui-Midiki", "kre": "Panará", "krf": "Koro (Vanuatu)", "krh": "Kurama", "kri": "Krio", "krj": "Kinaray-A", "krk": "Kerek", "krl": "Karelian", "krn": "Sapo", "kro": "Kru languages", "krp": "Korop", "krr": "Krung", "krs": "Gbaya (Sudan)", "krt": "Tumari Kanuri", "kru": "Kurukh", "krv": "Kavet", "krw": "Western Krahn", "krx": "Karon", "kry": "Kryts", "krz": "Sota Kanum", "ks": "Kashmiri", "ksa": "Shuwa-Zamani", "ksb": "Shambala", "ksc": "Southern Kalinga", "ksd": "Kuanua", "kse": "Kuni", "ksf": "Bafia", "ksg": "Kusaghe", "ksh": "Kölsch", "ksi": "Krisa; I'saka", "ksj": "Uare", "ksk": "Kansa", "ksl": "Kumalu", "ksm": "Kumba", "ksn": "Kasiguranin", "kso": "Kofa", "ksp": "Kaba", "ksq": "Kwaami", "ksr": "Borong", "kss": "Southern Kisi", "kst": "Winyé", "ksu": "Khamyang", "ksv": "Kusu", "ksw": "S'gaw Karen", "ksx": "Kedang", "ksy": "Kharia Thar", "ksz": "Kodaku", "kta": "Katua", "ktb": "Kambaata", "ktc": "Kholok", "ktd": "Kokata; Kukatha", "kte": "Nubri", "ktf": "Kwami", "ktg": "Kalkutung", "kth": "Karanga", "kti": "North Muyu", "ktj": "Plapo Krumen", "ktk": "Kaniet", "ktl": "Koroshi", "ktm": "Kurti", "ktn": "Karitiâna", "kto": "Kuot", "ktp": "Kaduo", "ktq": "Katabaga", "kts": "South Muyu", "ktt": "Ketum", "ktu": "Kituba (Democratic Republic of Congo)", "ktv": "Eastern Katu", "ktw": "Kato", "ktx": "Kaxararí", "kty": "Kango (Bas-Uélé District)", "ktz": "Juǀʼhoan; Juǀʼhoansi", "ku": "Kurdish", "kub": "Kutep", "kuc": "Kwinsu", "kud": "'Auhelawa", "kue": "Kuman (Papua New Guinea)", "kuf": "Western Katu", "kug": "Kupa", "kuh": "Kushi", "kui": "Kuikúro-Kalapálo; Kalapalo", "kuj": "Kuria", "kuk": "Kepo'", "kul": "Kulere", "kum": "Kumyk", "kun": "Kunama", "kuo": "Kumukio", "kup": "Kunimaipa", "kuq": "Karipuna", "kus": "Kusaal", "kut": "Kutenai", "kuu": "Upper Kuskokwim", "kuv": "Kur", "kuw": "Kpagua", "kux": "Kukatja", "kuy": "Kuuku-Ya'u", "kuz": "Kunza", "kv": "Komi", "kva": "Bagvalal", "kvb": "Kubu", "kvc": "Kove", "kvd": "Kui (Indonesia)", "kve": "Kalabakan", "kvf": "Kabalai", "kvg": "Kuni-Boazi", "kvh": "Komodo", "kvi": "Kwang", "kvj": "Psikye", "kvk": "Korean Sign Language", "kvl": "Kayaw", "kvm": "Kendem", "kvn": "Border Kuna", "kvo": "Dobel", "kvp": "Kompane", "kvq": "Geba Karen", "kvr": "Kerinci", "kvt": "Lahta Karen; Lahta", "kvu": "Yinbaw Karen", "kvv": "Kola", "kvw": "Wersing", "kvx": "Parkari Koli", "kvy": "Yintale Karen; Yintale", "kvz": "Tsakwambo; Tsaukambo", "kw": "Cornish", "kwa": "Dâw", "kwb": "Kwa", "kwc": "Likwala", "kwd": "Kwaio", "kwe": "Kwerba", "kwf": "Kwara'ae", "kwg": "Sara Kaba Deme", "kwh": "Kowiai", "kwi": "Awa-Cuaiquer", "kwj": "Kwanga", "kwk": "Kwakiutl", "kwl": "Kofyar", "kwm": "Kwambi", "kwn": "Kwangali", "kwo": "Kwomtari", "kwp": "Kodia", "kwr": "Kwer", "kws": "Kwese", "kwt": "Kwesten", "kwu": "Kwakum", "kwv": "Sara Kaba Náà", "kww": "Kwinti", "kwx": "Khirwar", "kwy": "San Salvador Kongo", "kwz": "Kwadi", "kxa": "Kairiru", "kxb": "Krobu", "kxc": "Konso; Khonso", "kxd": "Brunei", "kxf": "Manumanaw Karen; Manumanaw", "kxh": "Karo (Ethiopia)", "kxi": "Keningau Murut", "kxj": "Kulfa", "kxk": "Zayein Karen", "kxm": "Northern Khmer", "kxn": "Kanowit-Tanjong Melanau", "kxo": "Kanoé", "kxp": "Wadiyara Koli", "kxq": "Smärky Kanum", "kxr": "Koro (Papua New Guinea)", "kxs": "Kangjia", "kxt": "Koiwat", "kxv": "Kuvi", "kxw": "Konai", "kxx": "Likuba", "kxy": "Kayong", "kxz": "Kerewo", "ky": "Kirghiz; Kyrgyz", "kya": "Kwaya", "kyb": "Butbut Kalinga", "kyc": "Kyaka", "kyd": "Karey", "kye": "Krache", "kyf": "Kouya", "kyg": "Keyagana", "kyh": "Karok", "kyi": "Kiput", "kyj": "Karao", "kyk": "Kamayo", "kyl": "Kalapuya", "kym": "Kpatili", "kyn": "Northern Binukidnon", "kyo": "Kelon", "kyp": "Kang", "kyq": "Kenga", "kyr": "Kuruáya", "kys": "Baram Kayan", "kyt": "Kayagar", "kyu": "Western Kayah", "kyv": "Kayort", "kyw": "Kudmali", "kyx": "Rapoisi", "kyy": "Kambaira", "kyz": "Kayabí", "kza": "Western Karaboro", "kzb": "Kaibobo", "kzc": "Bondoukou Kulango", "kzd": "Kadai", "kze": "Kosena", "kzf": "Da'a Kaili", "kzg": "Kikai", "kzi": "Kelabit", "kzk": "Kazukuru", "kzl": "Kayeli", "kzm": "Kais", "kzn": "Kokola", "kzo": "Kaningi", "kzp": "Kaidipang", "kzq": "Kaike", "kzr": "Karang", "kzs": "Sugut Dusun", "kzu": "Kayupulau", "kzv": "Komyandaret", "kzw": "Karirí-Xocó", "kzx": "Kamarian", "kzy": "Kango (Tshopo District)", "kzz": "Kalabra", "la": "Latin", "laa": "Southern Subanen", "lab": "Linear A", "lac": "Lacandon", "lad": "Ladino", "lae": "Pattani", "laf": "Lafofa", "lag": "Langi", "lah": "Lahnda", "lai": "Lambya", "laj": "Lango (Uganda)", "lal": "Lalia", "lam": "Lamba", "lan": "Laru", "lap": "Laka (Chad)", "laq": "Qabiao", "lar": "Larteh", "las": "Lama (Togo)", "lau": "Laba", "law": "Lauje", "lax": "Tiwa", "lay": "Lama Bai", "laz": "Aribwatsa", "lb": "Luxembourgish; Letzeburgesch", "lbb": "Label", "lbc": "Lakkia", "lbe": "Lak", "lbf": "Tinani", "lbg": "Laopang", "lbi": "La'bi", "lbj": "Ladakhi", "lbk": "Central Bontok", "lbl": "Libon Bikol", "lbm": "Lodhi", "lbn": "Rmeet", "lbo": "Laven", "lbq": "Wampar", "lbr": "Lohorung", "lbs": "Libyan Sign Language", "lbt": "Lachi", "lbu": "Labu", "lbv": "Lavatbura-Lamusong", "lbw": "Tolaki", "lbx": "Lawangan", "lby": "Lamalama; Lamu-Lamu", "lbz": "Lardil", "lcc": "Legenyem", "lcd": "Lola", "lce": "Loncong; Sekak", "lcf": "Lubu", "lch": "Luchazi", "lcl": "Lisela", "lcm": "Tungag", "lcp": "Western Lawa", "lcq": "Luhu", "lcs": "Lisabata-Nuniali", "lda": "Kla-Dan", "ldb": "Dũya", "ldd": "Luri", "ldg": "Lenyima", "ldh": "Lamja-Dengsa-Tola", "ldi": "Laari", "ldj": "Lemoro", "ldk": "Leelau", "ldl": "Kaan", "ldm": "Landoma", "ldn": "Láadan", "ldo": "Loo", "ldp": "Tso", "ldq": "Lufu", "lea": "Lega-Shabunda", "leb": "Lala-Bisa", "lec": "Leco", "led": "Lendu", "lee": "Lyélé", "lef": "Lelemi", "leh": "Lenje", "lei": "Lemio", "lej": "Lengola", "lek": "Leipon", "lel": "Lele (Democratic Republic of Congo)", "lem": "Nomaande", "len": "Lenca", "leo": "Leti (Cameroon)", "lep": "Lepcha", "leq": "Lembena", "ler": "Lenkau", "les": "Lese", "let": "Lesing-Gelimi; Amio-Gelimi", "leu": "Kara (Papua New Guinea)", "lev": "Lamma", "lew": "Ledo Kaili", "lex": "Luang", "ley": "Lemolang", "lez": "Lezghian", "lfa": "Lefa", "lfn": "Lingua Franca Nova", "lg": "Ganda; Luganda", "lga": "Lungga", "lgb": "Laghu", "lgg": "Lugbara", "lgh": "Laghuu", "lgi": "Lengilu", "lgk": "Lingarak; Neverver", "lgl": "Wala", "lgm": "Lega-Mwenga", "lgn": "T'apo; Opuuo", "lgo": "Lango (South Sudan)", "lgq": "Logba", "lgr": "Lengo", "lgt": "Pahi", "lgu": "Longgu", "lgz": "Ligenza", "lha": "Laha (Viet Nam)", "lhh": "Laha (Indonesia)", "lhi": "Lahu Shi", "lhl": "Lahul Lohar", "lhm": "Lhomi", "lhn": "Lahanan", "lhp": "Lhokpu", "lhs": "Mlahsö", "lht": "Lo-Toga", "lhu": "Lahu", "li": "Limburgan; Limburger; Limburgish", "lia": "West-Central Limba", "lib": "Likum", "lic": "Hlai", "lid": "Nyindrou", "lie": "Likila", "lif": "Limbu", "lig": "Ligbi", "lih": "Lihir", "lij": "Ligurian", "lik": "Lika", "lil": "Lillooet", "lio": "Liki", "lip": "Sekpele", "liq": "Libido", "lir": "Liberian English", "lis": "Lisu", "liu": "Logorik", "liv": "Liv", "liw": "Col", "lix": "Liabuku", "liy": "Banda-Bambari", "liz": "Libinza", "lja": "Golpa", "lje": "Rampi", "lji": "Laiyolo", "ljl": "Li'o", "ljp": "Lampung Api", "ljw": "Yirandali", "ljx": "Yuru", "lka": "Lakalei", "lkb": "Kabras; Lukabaras", "lkc": "Kucong", "lkd": "Lakondê", "lke": "Kenyi", "lkh": "Lakha", "lki": "Laki", "lkj": "Remun", "lkl": "Laeko-Libuat", "lkm": "Kalaamaya", "lkn": "Lakon; Vure", "lko": "Khayo; Olukhayo", "lkr": "Päri", "lks": "Kisa; Olushisa", "lkt": "Lakota", "lku": "Kungkari", "lky": "Lokoya", "lla": "Lala-Roba", "llb": "Lolo", "llc": "Lele (Guinea)", "lld": "Ladin", "lle": "Lele (Papua New Guinea)", "llf": "Hermit", "llg": "Lole", "llh": "Lamu", "lli": "Teke-Laali", "llj": "Ladji Ladji", "llk": "Lelak", "lll": "Lilau", "llm": "Lasalimu", "lln": "Lele (Chad)", "llp": "North Efate", "llq": "Lolak", "lls": "Lithuanian Sign Language", "llu": "Lau", "llx": "Lauan", "lma": "East Limba", "lmb": "Merei", "lmc": "Limilngan", "lmd": "Lumun", "lme": "Pévé", "lmf": "South Lembata", "lmg": "Lamogai", "lmh": "Lambichhong", "lmi": "Lombi", "lmj": "West Lembata", "lmk": "Lamkang", "lml": "Hano", "lmn": "Lambadi", "lmo": "Lombard", "lmp": "Limbum", "lmq": "Lamatuka", "lmr": "Lamalera", "lmu": "Lamenu", "lmv": "Lomaiviti", "lmw": "Lake Miwok", "lmx": "Laimbue", "lmy": "Lamboya", "ln": "Lingala", "lna": "Langbashe", "lnb": "Mbalanhu", "lnd": "Lundayeh; Lun Bawang", "lng": "Langobardic", "lnh": "Lanoh", "lni": "Daantanai'", "lnj": "Leningitij", "lnl": "South Central Banda", "lnm": "Langam", "lnn": "Lorediakarkar", "lns": "Lamnso'", "lnu": "Longuda", "lnw": "Lanima", "lnz": "Lonzo", "lo": "Lao", "loa": "Loloda", "lob": "Lobi", "loc": "Inonhan", "loe": "Saluan", "lof": "Logol", "log": "Logo", "loh": "Narim", "loi": "Loma (Côte d'Ivoire)", "loj": "Lou", "lok": "Loko", "lol": "Mongo", "lom": "Loma (Liberia)", "lon": "Malawi Lomwe", "loo": "Lombo", "lop": "Lopa", "loq": "Lobala", "lor": "Téén", "los": "Loniu", "lot": "Otuho", "lou": "Louisiana Creole", "lov": "Lopi", "low": "Tampias Lobu", "lox": "Loun", "loy": "Loke", "loz": "Lozi", "lpa": "Lelepa", "lpe": "Lepki", "lpn": "Long Phuri Naga", "lpo": "Lipo", "lpx": "Lopit", "lqr": "Logir", "lra": "Rara Bakati'", "lrc": "Northern Luri", "lre": "Laurentian", "lrg": "Laragia", "lri": "Marachi; Olumarachi", "lrk": "Loarki", "lrl": "Lari", "lrm": "Marama; Olumarama", "lrn": "Lorang", "lro": "Laro", "lrr": "Southern Yamphu", "lrt": "Larantuka Malay", "lrv": "Larevat", "lrz": "Lemerig", "lsa": "Lasgerdi", "lsb": "Burundian Sign Language; Langue des Signes Burundaise", "lsc": "Albarradas Sign Language; Lengua de señas Albarradas", "lsd": "Lishana Deni", "lse": "Lusengo", "lsh": "Lish", "lsi": "Lashi", "lsl": "Latvian Sign Language", "lsm": "Saamia; Olusamia", "lsn": "Tibetan Sign Language", "lso": "Laos Sign Language", "lsp": "Panamanian Sign Language; Lengua de Señas Panameñas", "lsr": "Aruop", "lss": "Lasi", "lst": "Trinidad and Tobago Sign Language", "lsv": "Sivia Sign Language", "lsw": "Seychelles Sign Language; Lalang Siny Seselwa; Langue des Signes Seychelloise", "lsy": "Mauritian Sign Language", "lt": "Lithuanian", "ltc": "Late Middle Chinese", "ltg": "Latgalian", "lth": "Thur", "lti": "Leti (Indonesia)", "ltn": "Latundê", "lto": "Tsotso; Olutsotso", "lts": "Tachoni; Lutachoni", "ltu": "Latu", "lu": "Luba-Katanga", "lua": "Luba-Lulua", "luc": "Aringa", "lud": "Ludian", "lue": "Luvale", "luf": "Laua", "lui": "Luiseno", "luj": "Luna", "luk": "Lunanakha", "lul": "Olu'bo", "lum": "Luimbi", "lun": "Lunda", "luo": "Luo (Kenya and Tanzania); Dholuo", "lup": "Lumbu", "luq": "Lucumi", "lur": "Laura", "lus": "Lushai", "lut": "Lushootseed", "luu": "Lumba-Yakkha", "luv": "Luwati", "luw": "Luo (Cameroon)", "luy": "Luyia; Oluluyia", "luz": "Southern Luri", "lv": "Latvian", "lva": "Maku'a", "lvi": "Lavi", "lvk": "Lavukaleve", "lvs": "Standard Latvian", "lvu": "Levuka", "lwa": "Lwalu", "lwe": "Lewo Eleng", "lwg": "Wanga; Oluwanga", "lwh": "White Lachi", "lwl": "Eastern Lawa", "lwm": "Laomian", "lwo": "Luwo", "lws": "Malawian Sign Language", "lwt": "Lewotobi", "lwu": "Lawu", "lww": "Lewo", "lxm": "Lakurumau", "lya": "Layakha", "lyg": "Lyngngam", "lyn": "Luyana", "lzh": "Literary Chinese", "lzl": "Litzlitz", "lzn": "Leinong Naga", "lzz": "Laz", "maa": "San Jerónimo Tecóatl Mazatec", "mab": "Yutanduchi Mixtec", "mad": "Madurese", "mae": "Bo-Rukul", "maf": "Mafa", "mag": "Magahi", "mai": "Maithili", "maj": "Jalapa De Díaz Mazatec", "mak": "Makasar", "mam": "Mam", "man": "Mandingo; Manding", "map": "Austronesian languages", "maq": "Chiquihuitlán Mazatec", "mas": "Masai", "mat": "San Francisco Matlatzinca", "mau": "Huautla Mazatec", "mav": "Sateré-Mawé", "maw": "Mampruli", "max": "North Moluccan Malay", "maz": "Central Mazahua", "mba": "Higaonon", "mbb": "Western Bukidnon Manobo", "mbc": "Macushi", "mbd": "Dibabawon Manobo", "mbe": "Molale", "mbf": "Baba Malay", "mbh": "Mangseng", "mbi": "Ilianen Manobo", "mbj": "Nadëb", "mbk": "Malol", "mbl": "Maxakalí", "mbm": "Ombamba", "mbn": "Macaguán", "mbo": "Mbo (Cameroon)", "mbp": "Malayo", "mbq": "Maisin", "mbr": "Nukak Makú", "mbs": "Sarangani Manobo", "mbt": "Matigsalug Manobo", "mbu": "Mbula-Bwazza", "mbv": "Mbulungish", "mbw": "Maring", "mbx": "Mari (East Sepik Province)", "mby": "Memoni", "mbz": "Amoltepec Mixtec", "mca": "Maca", "mcb": "Machiguenga", "mcc": "Bitur", "mcd": "Sharanahua", "mce": "Itundujia Mixtec", "mcf": "Matsés", "mcg": "Mapoyo", "mch": "Maquiritari", "mci": "Mese", "mcj": "Mvanip", "mck": "Mbunda", "mcl": "Macaguaje", "mcm": "Malaccan Creole Portuguese", "mcn": "Masana", "mco": "Coatlán Mixe", "mcp": "Makaa", "mcq": "Ese", "mcr": "Menya", "mcs": "Mambai", "mct": "Mengisa", "mcu": "Cameroon Mambila", "mcv": "Minanibai", "mcw": "Mawa (Chad)", "mcx": "Mpiemo", "mcy": "South Watut", "mcz": "Mawan", "mda": "Mada (Nigeria)", "mdb": "Morigi", "mdc": "Male (Papua New Guinea)", "mdd": "Mbum", "mde": "Maba (Chad)", "mdf": "Moksha", "mdg": "Massalat", "mdh": "Maguindanaon", "mdi": "Mamvu", "mdj": "Mangbetu", "mdk": "Mangbutu", "mdl": "Maltese Sign Language", "mdm": "Mayogo", "mdn": "Mbati", "mdp": "Mbala", "mdq": "Mbole", "mdr": "Mandar", "mds": "Maria (Papua New Guinea)", "mdt": "Mbere", "mdu": "Mboko", "mdv": "Santa Lucía Monteverde Mixtec", "mdw": "Mbosi", "mdx": "Dizin", "mdy": "Male (Ethiopia)", "mdz": "Suruí Do Pará", "mea": "Menka", "meb": "Ikobi", "mec": "Marra", "med": "Melpa", "mee": "Mengen", "mef": "Megam", "meh": "Southwestern Tlaxiaco Mixtec", "mei": "Midob", "mej": "Meyah", "mek": "Mekeo", "mel": "Central Melanau", "mem": "Mangala", "men": "Mende (Sierra Leone)", "meo": "Kedah Malay", "mep": "Miriwoong", "meq": "Merey", "mer": "Meru", "mes": "Masmaje", "met": "Mato", "meu": "Motu", "mev": "Mano", "mew": "Maaka", "mey": "Hassaniyya", "mez": "Menominee", "mfa": "Pattani Malay", "mfb": "Bangka", "mfc": "Mba", "mfd": "Mendankwe-Nkwen", "mfe": "Morisyen", "mff": "Naki", "mfg": "Mogofin", "mfh": "Matal", "mfi": "Wandala", "mfj": "Mefele", "mfk": "North Mofu", "mfl": "Putai", "mfm": "Marghi South", "mfn": "Cross River Mbembe", "mfo": "Mbe", "mfp": "Makassar Malay", "mfq": "Moba", "mfr": "Marrithiyel", "mfs": "Mexican Sign Language", "mft": "Mokerang", "mfu": "Mbwela", "mfv": "Mandjak", "mfw": "Mulaha", "mfx": "Melo", "mfy": "Mayo", "mfz": "Mabaan", "mg": "Malagasy", "mga": "Middle Irish (900-1200)", "mgb": "Mararit", "mgc": "Morokodo", "mgd": "Moru", "mge": "Mango", "mgf": "Maklew", "mgg": "Mpumpong", "mgh": "Makhuwa-Meetto", "mgi": "Lijili", "mgj": "Abureni", "mgk": "Mawes", "mgl": "Maleu-Kilenge", "mgm": "Mambae", "mgn": "Mbangi", "mgo": "Meta'", "mgp": "Eastern Magar", "mgq": "Malila", "mgr": "Mambwe-Lungu", "mgs": "Manda (Tanzania)", "mgt": "Mongol", "mgu": "Mailu", "mgv": "Matengo", "mgw": "Matumbi", "mgy": "Mbunga", "mgz": "Mbugwe", "mh": "Marshallese", "mha": "Manda (India)", "mhb": "Mahongwe", "mhc": "Mocho", "mhd": "Mbugu", "mhe": "Besisi; Mah Meri", "mhf": "Mamaa", "mhg": "Margu", "mhi": "Ma'di", "mhj": "Mogholi", "mhk": "Mungaka", "mhl": "Mauwake", "mhm": "Makhuwa-Moniga", "mhn": "Mócheno", "mho": "Mashi (Zambia)", "mhp": "Balinese Malay", "mhq": "Mandan", "mhr": "Eastern Mari", "mhs": "Buru (Indonesia)", "mht": "Mandahuaca", "mhu": "Digaro-Mishmi; Darang Deng", "mhw": "Mbukushu", "mhx": "Maru; Lhaovo", "mhy": "Ma'anyan", "mhz": "Mor (Mor Islands)", "mi": "Maori", "mia": "Miami", "mib": "Atatláhuca Mixtec", "mic": "Mi'kmaq; Micmac", "mid": "Mandaic", "mie": "Ocotepec Mixtec", "mif": "Mofu-Gudur", "mig": "San Miguel El Grande Mixtec", "mih": "Chayuco Mixtec", "mii": "Chigmecatitlán Mixtec", "mij": "Abar; Mungbam", "mik": "Mikasuki", "mil": "Peñoles Mixtec", "mim": "Alacatlatzala Mixtec", "min": "Minangkabau", "mio": "Pinotepa Nacional Mixtec", "mip": "Apasco-Apoala Mixtec", "miq": "Mískito", "mir": "Isthmus Mixe", "mit": "Southern Puebla Mixtec", "miu": "Cacaloxtepec Mixtec", "miw": "Akoye", "mix": "Mixtepec Mixtec", "miy": "Ayutla Mixtec", "miz": "Coatzospan Mixtec", "mjb": "Makalero", "mjc": "San Juan Colorado Mixtec", "mjd": "Northwest Maidu", "mje": "Muskum", "mjg": "Tu", "mjh": "Mwera (Nyasa)", "mji": "Kim Mun", "mjj": "Mawak", "mjk": "Matukar", "mjl": "Mandeali", "mjm": "Medebur", "mjn": "Ma (Papua New Guinea)", "mjo": "Malankuravan", "mjp": "Malapandaram", "mjq": "Malaryan", "mjr": "Malavedan", "mjs": "Miship", "mjt": "Sauria Paharia", "mju": "Manna-Dora", "mjv": "Mannan", "mjw": "Karbi", "mjx": "Mahali", "mjy": "Mahican", "mjz": "Majhi", "mk": "Macedonian", "mka": "Mbre", "mkb": "Mal Paharia", "mkc": "Siliput", "mke": "Mawchi", "mkf": "Miya", "mkg": "Mak (China)", "mkh": "Mon-Khmer languages", "mki": "Dhatki", "mkj": "Mokilese", "mkk": "Byep", "mkl": "Mokole", "mkm": "Moklen", "mkn": "Kupang Malay", "mko": "Mingang Doso", "mkp": "Moikodi", "mkq": "Bay Miwok", "mkr": "Malas", "mks": "Silacayoapan Mixtec", "mkt": "Vamale", "mku": "Konyanka Maninka", "mkv": "Mafea", "mkw": "Kituba (Congo)", "mkx": "Kinamiging Manobo", "mky": "East Makian", "mkz": "Makasae", "ml": "Malayalam", "mla": "Malo", "mlb": "Mbule", "mlc": "Cao Lan", "mle": "Manambu", "mlf": "Mal", "mlh": "Mape", "mli": "Malimpung", "mlj": "Miltu", "mlk": "Ilwana; Kiwilwana", "mll": "Malua Bay", "mlm": "Mulam", "mln": "Malango", "mlo": "Mlomp", "mlp": "Bargam", "mlq": "Western Maninkakan", "mlr": "Vame", "mls": "Masalit", "mlu": "To'abaita", "mlv": "Motlav; Mwotlap", "mlw": "Moloko", "mlx": "Malfaxal; Naha'ai", "mlz": "Malaynon", "mma": "Mama", "mmb": "Momina", "mmc": "Michoacán Mazahua", "mmd": "Maonan", "mme": "Mae", "mmf": "Mundat", "mmg": "North Ambrym", "mmh": "Mehináku", "mmi": "Musar", "mmj": "Majhwar", "mmk": "Mukha-Dora", "mml": "Man Met", "mmm": "Maii", "mmn": "Mamanwa", "mmo": "Mangga Buang", "mmp": "Siawi", "mmq": "Musak", "mmr": "Western Xiangxi Miao", "mmt": "Malalamai", "mmu": "Mmaala", "mmv": "Miriti", "mmw": "Emae", "mmx": "Madak", "mmy": "Migaama", "mmz": "Mabaale", "mn": "Mongolian", "mna": "Mbula", "mnb": "Muna", "mnc": "Manchu", "mnd": "Mondé", "mne": "Naba", "mnf": "Mundani", "mng": "Eastern Mnong", "mnh": "Mono (Democratic Republic of Congo)", "mni": "Manipuri", "mnj": "Munji", "mnk": "Mandinka", "mnl": "Tiale", "mnm": "Mapena", "mnn": "Southern Mnong", "mno": "Manobo languages", "mnp": "Min Bei Chinese", "mnq": "Minriq", "mnr": "Mono (USA)", "mns": "Mansi", "mnu": "Mer", "mnv": "Rennell-Bellona", "mnw": "Mon", "mnx": "Manikion", "mny": "Manyawa", "mnz": "Moni", "moa": "Mwan", "moc": "Mocoví", "mod": "Mobilian", "moe": "Innu; Montagnais", "mog": "Mongondow", "moh": "Mohawk", "moi": "Mboi", "moj": "Monzombo", "mok": "Morori", "mom": "Mangue", "moo": "Monom", "mop": "Mopán Maya", "moq": "Mor (Bomberai Peninsula)", "mor": "Moro", "mos": "Mossi", "mot": "Barí", "mou": "Mogum", "mov": "Mohave", "mow": "Moi (Congo)", "mox": "Molima", "moy": "Shekkacho", "moz": "Mukulu; Gergiko", "mpa": "Mpoto", "mpb": "Malak Malak; Mullukmulluk", "mpc": "Mangarrayi", "mpd": "Machinere", "mpe": "Majang", "mpg": "Marba", "mph": "Maung", "mpi": "Mpade", "mpj": "Martu Wangka; Wangkajunga", "mpk": "Mbara (Chad)", "mpl": "Middle Watut", "mpm": "Yosondúa Mixtec", "mpn": "Mindiri", "mpo": "Miu", "mpp": "Migabac", "mpq": "Matís", "mpr": "Vangunu", "mps": "Dadibi", "mpt": "Mian", "mpu": "Makuráp", "mpv": "Mungkip", "mpw": "Mapidian", "mpx": "Misima-Panaeati", "mpy": "Mapia", "mpz": "Mpi", "mqa": "Maba (Indonesia)", "mqb": "Mbuko", "mqc": "Mangole", "mqe": "Matepi", "mqf": "Momuna", "mqg": "Kota Bangun Kutai Malay", "mqh": "Tlazoyaltepec Mixtec", "mqi": "Mariri", "mqj": "Mamasa", "mqk": "Rajah Kabunsuwan Manobo", "mql": "Mbelime", "mqm": "South Marquesan", "mqn": "Moronene", "mqo": "Modole", "mqp": "Manipa", "mqq": "Minokok", "mqr": "Mander", "mqs": "West Makian", "mqt": "Mok", "mqu": "Mandari", "mqv": "Mosimo", "mqw": "Murupi", "mqx": "Mamuju", "mqy": "Manggarai", "mqz": "Pano", "mr": "Marathi", "mra": "Mlabri", "mrb": "Marino", "mrc": "Maricopa", "mrd": "Western Magar", "mre": "Martha's Vineyard Sign Language", "mrf": "Elseng", "mrg": "Mising", "mrh": "Mara Chin", "mrj": "Western Mari", "mrk": "Hmwaveke", "mrl": "Mortlockese", "mrm": "Merlav; Mwerlap", "mrn": "Cheke Holo", "mro": "Mru", "mrp": "Morouas", "mrq": "North Marquesan", "mrr": "Maria (India)", "mrs": "Maragus", "mrt": "Marghi Central", "mru": "Mono (Cameroon)", "mrv": "Mangareva", "mrw": "Maranao", "mrx": "Maremgi; Dineor", "mry": "Mandaya", "mrz": "Marind", "ms": "Malay (macrolanguage)", "msb": "Masbatenyo", "msc": "Sankaran Maninka", "msd": "Yucatec Maya Sign Language", "mse": "Musey", "msf": "Mekwei", "msg": "Moraid", "msh": "Masikoro Malagasy", "msi": "Sabah Malay", "msj": "Ma (Democratic Republic of Congo)", "msk": "Mansaka", "msl": "Molof; Poule", "msm": "Agusan Manobo", "msn": "Vurës", "mso": "Mombum", "msp": "Maritsauá", "msq": "Caac", "msr": "Mongolian Sign Language", "mss": "West Masela", "msu": "Musom", "msv": "Maslam", "msw": "Mansoanka", "msx": "Moresada", "msy": "Aruamu", "msz": "Momare", "mt": "Maltese", "mta": "Cotabato Manobo", "mtb": "Anyin Morofo", "mtc": "Munit", "mtd": "Mualang", "mte": "Mono (Solomon Islands)", "mtf": "Murik (Papua New Guinea)", "mtg": "Una", "mth": "Munggui", "mti": "Maiwa (Papua New Guinea)", "mtj": "Moskona", "mtk": "Mbe'", "mtl": "Montol", "mtm": "Mator", "mtn": "Matagalpa", "mto": "Totontepec Mixe", "mtp": "Wichí Lhamtés Nocten", "mtq": "Muong", "mtr": "Mewari", "mts": "Yora", "mtt": "Mota", "mtu": "Tututepec Mixtec", "mtv": "Asaro'o", "mtw": "Southern Binukidnon", "mtx": "Tidaá Mixtec", "mty": "Nabi", "mua": "Mundang", "mub": "Mubi", "muc": "Ajumbu", "mud": "Mednyj Aleut", "mue": "Media Lengua", "mug": "Musgu", "muh": "Mündü", "mui": "Musi", "muj": "Mabire", "muk": "Mugom", "mum": "Maiwala", "mun": "Munda languages", "muo": "Nyong", "mup": "Malvi", "muq": "Eastern Xiangxi Miao", "mur": "Murle", "mus": "Creek", "mut": "Western Muria", "muu": "Yaaku", "muv": "Muthuvan", "mux": "Bo-Ung", "muy": "Muyang", "muz": "Mursi", "mva": "Manam", "mvb": "Mattole", "mvd": "Mamboru", "mve": "Marwari (Pakistan)", "mvf": "Peripheral Mongolian", "mvg": "Yucuañe Mixtec", "mvh": "Mulgi", "mvi": "Miyako", "mvk": "Mekmek", "mvl": "Mbara (Australia)", "mvn": "Minaveha", "mvo": "Marovo", "mvp": "Duri", "mvq": "Moere", "mvr": "Marau", "mvs": "Massep", "mvt": "Mpotovoro", "mvu": "Marfa", "mvv": "Tagal Murut", "mvw": "Machinga", "mvx": "Meoswar", "mvy": "Indus Kohistani", "mvz": "Mesqan", "mwa": "Mwatebu", "mwb": "Juwal", "mwc": "Are", "mwe": "Mwera (Chimwera)", "mwf": "Murrinh-Patha", "mwg": "Aiklep", "mwh": "Mouk-Aria", "mwi": "Labo; Ninde", "mwk": "Kita Maninkakan", "mwl": "Mirandese", "mwm": "Sar", "mwn": "Nyamwanga", "mwo": "Central Maewo", "mwp": "Kala Lagaw Ya", "mwq": "Mün Chin", "mwr": "Marwari", "mws": "Mwimbi-Muthambi", "mwt": "Moken", "mwu": "Mittu", "mwv": "Mentawai", "mww": "Hmong Daw", "mwz": "Moingi", "mxa": "Northwest Oaxaca Mixtec", "mxb": "Tezoatlán Mixtec", "mxc": "Manyika", "mxd": "Modang", "mxe": "Mele-Fila", "mxf": "Malgbe", "mxg": "Mbangala", "mxh": "Mvuba", "mxi": "Mozarabic", "mxj": "Miju-Mishmi; Geman Deng", "mxk": "Monumbo", "mxl": "Maxi Gbe", "mxm": "Meramera", "mxn": "Moi (Indonesia)", "mxo": "Mbowe", "mxp": "Tlahuitoltepec Mixe", "mxq": "Juquila Mixe", "mxr": "Murik (Malaysia)", "mxs": "Huitepec Mixtec", "mxt": "Jamiltepec Mixtec", "mxu": "Mada (Cameroon)", "mxv": "Metlatónoc Mixtec", "mxw": "Namo", "mxx": "Mahou; Mawukakan", "mxy": "Southeastern Nochixtlán Mixtec", "mxz": "Central Masela", "my": "Burmese", "myb": "Mbay", "myc": "Mayeka", "mye": "Myene", "myf": "Bambassi", "myg": "Manta", "myh": "Makah", "myj": "Mangayat", "myk": "Mamara Senoufo", "myl": "Moma", "mym": "Me'en", "myn": "Mayan languages", "myo": "Anfillo", "myp": "Pirahã", "myr": "Muniche", "mys": "Mesmes", "myu": "Mundurukú", "myv": "Erzya", "myw": "Muyuw", "myx": "Masaaba", "myy": "Macuna", "myz": "Classical Mandaic", "mza": "Santa María Zacatepec Mixtec", "mzb": "Tumzabt", "mzc": "Madagascar Sign Language", "mzd": "Malimba", "mze": "Morawa", "mzg": "Monastic Sign Language", "mzh": "Wichí Lhamtés Güisnay", "mzi": "Ixcatlán Mazatec", "mzj": "Manya", "mzk": "Nigeria Mambila", "mzl": "Mazatlán Mixe", "mzm": "Mumuye", "mzn": "Mazanderani", "mzo": "Matipuhy", "mzp": "Movima", "mzq": "Mori Atas", "mzr": "Marúbo", "mzs": "Macanese", "mzt": "Mintil", "mzu": "Inapang", "mzv": "Manza", "mzw": "Deg", "mzx": "Mawayana", "mzy": "Mozambican Sign Language", "mzz": "Maiadomu", "na": "Nauru", "naa": "Namla", "nab": "Southern Nambikuára", "nac": "Narak", "nae": "Naka'ela", "naf": "Nabak", "nag": "Naga Pidgin", "nah": "Nahuatl languages", "nai": "North American Indian languages", "naj": "Nalu", "nak": "Nakanai", "nal": "Nalik", "nam": "Ngan'gityemerri", "nan": "Min Nan Chinese", "nao": "Naaba", "nap": "Neapolitan", "naq": "Khoekhoe; Nama (Namibia)", "nar": "Iguta", "nas": "Naasioi", "nat": "Ca̱hungwa̱rya̱; Hungworo", "naw": "Nawuri", "nax": "Nakwi", "nay": "Ngarrindjeri", "naz": "Coatepec Nahuatl", "nb": "Norwegian Bokmål", "nba": "Nyemba", "nbb": "Ndoe", "nbc": "Chang Naga", "nbd": "Ngbinda", "nbe": "Konyak Naga", "nbg": "Nagarchal", "nbh": "Ngamo", "nbi": "Mao Naga", "nbj": "Ngarinyman", "nbk": "Nake", "nbm": "Ngbaka Ma'bo", "nbn": "Kuri", "nbo": "Nkukoli", "nbp": "Nnam", "nbq": "Nggem", "nbr": "Numana", "nbs": "Namibian Sign Language", "nbt": "Na", "nbu": "Rongmei Naga", "nbv": "Ngamambo", "nbw": "Southern Ngbandi", "nby": "Ningera", "nca": "Iyo", "ncb": "Central Nicobarese", "ncc": "Ponam", "ncd": "Nachering", "nce": "Yale", "ncf": "Notsi", "ncg": "Nisga'a", "nch": "Central Huasteca Nahuatl", "nci": "Classical Nahuatl", "ncj": "Northern Puebla Nahuatl", "nck": "Na-kara", "ncl": "Michoacán Nahuatl", "ncm": "Nambo", "ncn": "Nauna", "nco": "Sibe", "ncq": "Northern Katang", "ncr": "Ncane", "ncs": "Nicaraguan Sign Language", "nct": "Chothe Naga", "ncu": "Chumburung", "ncx": "Central Puebla Nahuatl", "ncz": "Natchez", "nd": "North Ndebele", "nda": "Ndasa", "ndb": "Kenswei Nsei", "ndc": "Ndau", "ndd": "Nde-Nsele-Nta", "ndf": "Nadruvian", "ndg": "Ndengereko", "ndh": "Ndali", "ndi": "Samba Leko", "ndj": "Ndamba", "ndk": "Ndaka", "ndl": "Ndolo", "ndm": "Ndam", "ndn": "Ngundi", "ndp": "Ndo", "ndq": "Ndombe", "ndr": "Ndoola", "nds": "Low German; Low Saxon", "ndt": "Ndunga", "ndu": "Dugun", "ndv": "Ndut", "ndw": "Ndobo", "ndx": "Nduga", "ndy": "Lutos", "ndz": "Ndogo", "ne": "Nepali (macrolanguage)", "nea": "Eastern Ngad'a", "neb": "Toura (Côte d'Ivoire)", "nec": "Nedebang", "ned": "Nde-Gbite", "nee": "Nêlêmwa-Nixumwak", "nef": "Nefamese", "neg": "Negidal", "neh": "Nyenkha", "nei": "Neo-Hittite", "nej": "Neko", "nek": "Neku", "nem": "Nemi", "nen": "Nengone", "neo": "Ná-Meo", "neq": "North Central Mixe", "ner": "Yahadian", "nes": "Bhoti Kinnauri", "net": "Nete", "neu": "Neo", "nev": "Nyaheun", "new": "Newari; Nepal Bhasa", "nex": "Neme", "ney": "Neyo", "nez": "Nez Perce", "nfa": "Dhao", "nfd": "Ahwai", "nfl": "Ayiwo; Äiwoo", "nfr": "Nafaanra", "nfu": "Mfumte", "ng": "Ndonga", "nga": "Ngbaka", "ngb": "Northern Ngbandi", "ngc": "Ngombe (Democratic Republic of Congo)", "ngd": "Ngando (Central African Republic)", "nge": "Ngemba", "ngf": "Trans-New Guinea languages", "ngg": "Ngbaka Manza", "ngh": "Nǁng", "ngi": "Ngizim", "ngj": "Ngie", "ngk": "Dalabon", "ngl": "Lomwe", "ngm": "Ngatik Men's Creole", "ngn": "Ngwo", "ngp": "Ngulu", "ngq": "Ngurimi; Ngoreme", "ngr": "Engdewu", "ngs": "Gvoko", "ngt": "Kriang; Ngeq", "ngu": "Guerrero Nahuatl", "ngv": "Nagumi", "ngw": "Ngwaba", "ngx": "Nggwahyi", "ngy": "Tibea", "ngz": "Ngungwel", "nha": "Nhanda", "nhb": "Beng", "nhc": "Tabasco Nahuatl", "nhd": "Chiripá; Ava Guaraní", "nhe": "Eastern Huasteca Nahuatl", "nhf": "Nhuwala", "nhg": "Tetelcingo Nahuatl", "nhh": "Nahari", "nhi": "Zacatlán-Ahuacatlán-Tepetzintla Nahuatl", "nhk": "Isthmus-Cosoleacaque Nahuatl", "nhm": "Morelos Nahuatl", "nhn": "Central Nahuatl", "nho": "Takuu", "nhp": "Isthmus-Pajapan Nahuatl", "nhq": "Huaxcaleca Nahuatl", "nhr": "Naro", "nht": "Ometepec Nahuatl", "nhu": "Noone", "nhv": "Temascaltepec Nahuatl", "nhw": "Western Huasteca Nahuatl", "nhx": "Isthmus-Mecayapan Nahuatl", "nhy": "Northern Oaxaca Nahuatl", "nhz": "Santa María La Alta Nahuatl", "nia": "Nias", "nib": "Nakame", "nic": "Niger-Kordofanian languages", "nid": "Ngandi", "nie": "Niellim", "nif": "Nek", "nig": "Ngalakgan", "nih": "Nyiha (Tanzania)", "nii": "Nii", "nij": "Ngaju", "nik": "Southern Nicobarese", "nil": "Nila", "nim": "Nilamba", "nin": "Ninzo", "nio": "Nganasan", "niq": "Nandi", "nir": "Nimboran", "nis": "Nimi", "nit": "Southeastern Kolami", "niu": "Niuean", "niv": "Gilyak", "niw": "Nimo", "nix": "Hema", "niy": "Ngiti", "niz": "Ningil", "nja": "Nzanyi", "njb": "Nocte Naga", "njd": "Ndonde Hamba", "njh": "Lotha Naga", "nji": "Gudanji", "njj": "Njen", "njl": "Njalgulgule", "njm": "Angami Naga", "njn": "Liangmai Naga", "njo": "Ao Naga", "njr": "Njerep", "njs": "Nisa", "njt": "Ndyuka-Trio Pidgin", "nju": "Ngadjunmaya", "njx": "Kunyi", "njy": "Njyem", "njz": "Nyishi", "nka": "Nkoya", "nkb": "Khoibu Naga", "nkc": "Nkongho", "nkd": "Koireng", "nke": "Duke", "nkf": "Inpui Naga", "nkg": "Nekgini", "nkh": "Khezha Naga", "nki": "Thangal Naga", "nkj": "Nakai", "nkk": "Nokuku", "nkm": "Namat", "nkn": "Nkangala", "nko": "Nkonya", "nkp": "Niuatoputapu", "nkq": "Nkami", "nkr": "Nukuoro", "nks": "North Asmat", "nkt": "Nyika (Tanzania)", "nku": "Bouna Kulango", "nkv": "Nyika (Malawi and Zambia)", "nkw": "Nkutu", "nkx": "Nkoroo", "nkz": "Nkari", "nl": "Dutch; Flemish", "nla": "Ngombale", "nlc": "Nalca", "nle": "East Nyala", "nlg": "Gela", "nli": "Grangali", "nlj": "Nyali", "nlk": "Ninia Yali", "nll": "Nihali", "nlm": "Mankiyali", "nlo": "Ngul", "nlq": "Lao Naga", "nlu": "Nchumbulu", "nlv": "Orizaba Nahuatl", "nlw": "Walangama", "nlx": "Nahali", "nly": "Nyamal", "nlz": "Nalögo", "nma": "Maram Naga", "nmb": "Big Nambas; V'ënen Taut", "nmc": "Ngam", "nmd": "Ndumu", "nme": "Mzieme Naga", "nmf": "Tangkhul Naga (India)", "nmg": "Kwasio", "nmh": "Monsang Naga", "nmi": "Nyam", "nmj": "Ngombe (Central African Republic)", "nmk": "Namakura", "nml": "Ndemli", "nmm": "Manangba", "nmn": "ǃXóõ", "nmo": "Moyon Naga", "nmp": "Nimanbur", "nmq": "Nambya", "nmr": "Nimbari", "nms": "Letemboi", "nmt": "Namonuito", "nmu": "Northeast Maidu", "nmv": "Ngamini", "nmw": "Nimoa; Rifao", "nmx": "Nama (Papua New Guinea)", "nmy": "Namuyi", "nmz": "Nawdm", "nn": "Norwegian Nynorsk", "nna": "Nyangumarta", "nnb": "Nande", "nnc": "Nancere", "nnd": "West Ambae", "nne": "Ngandyera", "nnf": "Ngaing", "nng": "Maring Naga", "nnh": "Ngiemboon", "nni": "North Nuaulu", "nnj": "Nyangatom", "nnk": "Nankina", "nnl": "Northern Rengma Naga", "nnm": "Namia", "nnn": "Ngete", "nnp": "Wancho Naga", "nnq": "Ngindo", "nnr": "Narungga", "nnt": "Nanticoke", "nnu": "Dwang", "nnv": "Nugunu (Australia)", "nnw": "Southern Nuni", "nny": "Nyangga", "nnz": "Nda'nda'", "no": "Norwegian", "noa": "Woun Meu", "noc": "Nuk", "nod": "Northern Thai", "noe": "Nimadi", "nof": "Nomane", "nog": "Nogai", "noh": "Nomu", "noi": "Noiri", "noj": "Nonuya", "nok": "Nooksack", "nol": "Nomlaki", "nom": "Nocamán", "non": "Old Norse", "nop": "Numanggang", "noq": "Ngongo", "nos": "Eastern Nisu", "not": "Nomatsiguenga", "nou": "Ewage-Notu", "nov": "Novial", "now": "Nyambo", "noy": "Noy", "noz": "Nayi", "npa": "Nar Phu", "npb": "Nupbikha", "npg": "Ponyo-Gongwang Naga", "nph": "Phom Naga", "npi": "Nepali (individual language)", "npl": "Southeastern Puebla Nahuatl", "npn": "Mondropolon", "npo": "Pochuri Naga", "nps": "Nipsan", "npu": "Puimei Naga", "npx": "Noipx", "npy": "Napu", "nqg": "Southern Nago", "nqk": "Kura Ede Nago", "nql": "Ngendelengo", "nqm": "Ndom", "nqn": "Nen", "nqo": "N'Ko; N’Ko", "nqq": "Kyan-Karyaw Naga", "nqt": "Nteng", "nqy": "Akyaung Ari Naga", "nr": "South Ndebele", "nra": "Ngom", "nrb": "Nara", "nrc": "Noric", "nre": "Southern Rengma Naga", "nrf": "Jèrriais; Guernésiais", "nrg": "Narango", "nri": "Chokri Naga", "nrk": "Ngarla", "nrl": "Ngarluma", "nrm": "Narom", "nrn": "Norn", "nrp": "North Picene", "nrr": "Norra; Nora", "nrt": "Northern Kalapuya", "nru": "Narua", "nrx": "Ngurmbur", "nrz": "Lala", "nsa": "Sangtam Naga", "nsb": "Lower Nossob", "nsc": "Nshi", "nsd": "Southern Nisu", "nse": "Nsenga", "nsf": "Northwestern Nisu", "nsg": "Ngasa", "nsh": "Ngoshie", "nsi": "Nigerian Sign Language", "nsk": "Naskapi", "nsl": "Norwegian Sign Language", "nsm": "Sumi Naga", "nsn": "Nehan", "nso": "Pedi; Northern Sotho; Sepedi", "nsp": "Nepalese Sign Language", "nsq": "Northern Sierra Miwok", "nsr": "Maritime Sign Language", "nss": "Nali", "nst": "Tase Naga", "nsu": "Sierra Negra Nahuatl", "nsv": "Southwestern Nisu", "nsw": "Navut", "nsx": "Nsongo", "nsy": "Nasal", "nsz": "Nisenan", "ntd": "Northern Tidung", "nte": "Nathembo", "ntg": "Ngantangarra", "nti": "Natioro", "ntj": "Ngaanyatjarra", "ntk": "Ikoma-Nata-Isenye", "ntm": "Nateni", "nto": "Ntomba", "ntp": "Northern Tepehuan", "ntr": "Delo", "ntu": "Natügu", "ntw": "Nottoway", "ntx": "Tangkhul Naga (Myanmar)", "nty": "Mantsi", "ntz": "Natanzi", "nua": "Yuanga", "nub": "Nubian languages", "nuc": "Nukuini", "nud": "Ngala", "nue": "Ngundu", "nuf": "Nusu", "nug": "Nungali", "nuh": "Ndunda", "nui": "Ngumbi", "nuj": "Nyole", "nuk": "Nuu-chah-nulth; Nuuchahnulth", "nul": "Nusa Laut", "num": "Niuafo'ou", "nun": "Anong", "nuo": "Nguôn", "nup": "Nupe-Nupe-Tako", "nuq": "Nukumanu", "nur": "Nukuria", "nus": "Nuer", "nut": "Nung (Viet Nam)", "nuu": "Ngbundu", "nuv": "Northern Nuni", "nuw": "Nguluwan", "nux": "Mehek", "nuy": "Nunggubuyu", "nuz": "Tlamacazapa Nahuatl", "nv": "Navajo; Navaho", "nvh": "Nasarian", "nvm": "Namiae", "nvo": "Nyokon", "nwa": "Nawathinehena", "nwb": "Nyabwa", "nwc": "Classical Newari; Classical Nepal Bhasa; Old Newari", "nwe": "Ngwe", "nwg": "Ngayawung", "nwi": "Southwest Tanna", "nwm": "Nyamusa-Molo", "nwo": "Nauo", "nwr": "Nawaru", "nww": "Ndwewe", "nwx": "Middle Newar", "nwy": "Nottoway-Meherrin", "nxa": "Nauete", "nxd": "Ngando (Democratic Republic of Congo)", "nxe": "Nage", "nxg": "Ngad'a", "nxi": "Nindi", "nxk": "Koki Naga", "nxl": "South Nuaulu", "nxm": "Numidian", "nxn": "Ngawun", "nxo": "Ndambomo", "nxq": "Naxi", "nxr": "Ninggerum", "nxx": "Nafri", "ny": "Nyanja; Chewa; Chichewa", "nyb": "Nyangbo", "nyc": "Nyanga-li", "nyd": "Nyore; Olunyole", "nye": "Nyengo", "nyf": "Giryama; Kigiryama", "nyg": "Nyindu", "nyh": "Nyikina", "nyi": "Ama (Sudan)", "nyj": "Nyanga", "nyk": "Nyaneka", "nyl": "Nyeu", "nym": "Nyamwezi", "nyn": "Nyankole", "nyo": "Nyoro", "nyp": "Nyang'i", "nyq": "Nayini", "nyr": "Nyiha (Malawi)", "nys": "Nyungar", "nyt": "Nyawaygi", "nyu": "Nyungwe", "nyv": "Nyulnyul", "nyw": "Nyaw", "nyx": "Nganyaywana", "nyy": "Nyakyusa-Ngonde", "nza": "Tigon Mbembe", "nzb": "Njebi", "nzd": "Nzadi", "nzi": "Nzima", "nzk": "Nzakara", "nzm": "Zeme Naga", "nzs": "New Zealand Sign Language", "nzu": "Teke-Nzikou", "nzy": "Nzakambay", "nzz": "Nanga Dama Dogon", "oaa": "Orok", "oac": "Oroch", "oar": "Old Aramaic (up to 700 BCE); Ancient Aramaic (up to 700 BCE)", "oav": "Old Avar", "obi": "Obispeño", "obk": "Southern Bontok", "obl": "Oblo", "obm": "Moabite", "obo": "Obo Manobo", "obr": "Old Burmese", "obt": "Old Breton", "obu": "Obulom", "oc": "Occitan (post 1500)", "oca": "Ocaina", "och": "Old Chinese", "ocm": "Old Cham", "oco": "Old Cornish", "ocu": "Atzingo Matlatzinca", "oda": "Odut", "odk": "Od", "odt": "Old Dutch", "odu": "Odual", "ofo": "Ofo", "ofs": "Old Frisian", "ofu": "Efutop", "ogb": "Ogbia", "ogc": "Ogbah", "oge": "Old Georgian", "ogg": "Ogbogolo", "ogo": "Khana", "ogu": "Ogbronuagum", "oht": "Old Hittite", "ohu": "Old Hungarian", "oia": "Oirata", "oie": "Okolie", "oin": "Inebu One", "oj": "Ojibwa", "ojb": "Northwestern Ojibwa", "ojc": "Central Ojibwa", "ojg": "Eastern Ojibwa", "ojp": "Old Japanese", "ojs": "Severn Ojibwa", "ojv": "Ontong Java", "ojw": "Western Ojibwa", "oka": "Okanagan", "okb": "Okobo", "okc": "Kobo", "okd": "Okodia", "oke": "Okpe (Southwestern Edo)", "okg": "Koko Babangk", "okh": "Koresh-e Rostam", "oki": "Okiek", "okj": "Oko-Juwoi", "okk": "Kwamtim One", "okl": "Old Kentish Sign Language", "okm": "Middle Korean (10th-16th cent.)", "okn": "Oki-No-Erabu", "oko": "Old Korean (3rd-9th cent.)", "okr": "Kirike", "oks": "Oko-Eni-Osayen", "oku": "Oku", "okv": "Orokaiva", "okx": "Okpe (Northwestern Edo)", "okz": "Old Khmer", "ola": "Walungge", "old": "Mochi", "ole": "Olekha", "olk": "Olkol", "olm": "Oloma", "olo": "Livvi", "olr": "Olrat", "olt": "Old Lithuanian", "olu": "Kuvale", "om": "Oromo", "oma": "Omaha-Ponca", "omb": "East Ambae", "omc": "Mochica", "omg": "Omagua", "omi": "Omi", "omk": "Omok", "oml": "Ombo", "omn": "Minoan", "omo": "Utarmbung", "omp": "Old Manipuri", "omq": "Oto-Manguean languages", "omr": "Old Marathi", "omt": "Omotik", "omu": "Omurano", "omv": "Omotic languages", "omw": "South Tairora", "omx": "Old Mon", "omy": "Old Malay", "ona": "Ona", "onb": "Lingao", "one": "Oneida", "ong": "Olo", "oni": "Onin", "onj": "Onjob", "onk": "Kabore One", "onn": "Onobasulu", "ono": "Onondaga", "onp": "Sartang", "onr": "Northern One", "ons": "Ono", "ont": "Ontenu", "onu": "Unua", "onw": "Old Nubian", "onx": "Onin Based Pidgin", "ood": "Tohono O'odham", "oog": "Ong", "oon": "Önge", "oor": "Oorlams", "oos": "Old Ossetic", "opa": "Okpamheri", "opk": "Kopkaka", "opm": "Oksapmin", "opo": "Opao", "opt": "Opata", "opy": "Ofayé", "or": "Oriya (macrolanguage); Odia (macrolanguage)", "ora": "Oroha", "orc": "Orma", "ore": "Orejón", "org": "Oring", "orh": "Oroqen", "orn": "Orang Kanaq", "oro": "Orokolo", "orr": "Oruma", "ors": "Orang Seletar", "ort": "Adivasi Oriya", "oru": "Ormuri", "orv": "Old Russian", "orw": "Oro Win", "orx": "Oro", "ory": "Odia (individual language); Oriya (individual language)", "orz": "Ormu", "os": "Ossetian; Ossetic", "osa": "Osage", "osc": "Oscan", "osi": "Osing", "osn": "Old Sundanese", "oso": "Ososo", "osp": "Old Spanish", "ost": "Osatu", "osu": "Southern One", "osx": "Old Saxon", "ota": "Ottoman Turkish (1500-1928)", "otb": "Old Tibetan", "otd": "Ot Danum", "ote": "Mezquital Otomi", "oti": "Oti", "otk": "Old Turkish", "otl": "Tilapa Otomi", "otm": "Eastern Highland Otomi", "otn": "Tenango Otomi", "oto": "Otomian languages", "otq": "Querétaro Otomi", "otr": "Otoro", "ots": "Estado de México Otomi", "ott": "Temoaya Otomi", "otu": "Otuke", "otw": "Ottawa", "otx": "Texcatepec Otomi", "oty": "Old Tamil", "otz": "Ixtenco Otomi", "oua": "Tagargrent", "oub": "Glio-Oubi", "oue": "Oune", "oui": "Old Uighur", "oum": "Ouma", "ovd": "Elfdalian; Övdalian", "owi": "Owiniga", "owl": "Old Welsh", "oyb": "Oy", "oyd": "Oyda", "oym": "Wayampi", "oyy": "Oya'oya", "ozm": "Koonzime", "pa": "Panjabi; Punjabi", "paa": "Papuan languages", "pab": "Parecís", "pac": "Pacoh", "pad": "Paumarí", "pae": "Pagibete", "paf": "Paranawát", "pag": "Pangasinan", "pah": "Tenharim", "pai": "Pe", "pak": "Parakanã", "pal": "Pahlavi", "pam": "Pampanga; Kapampangan", "pao": "Northern Paiute", "pap": "Papiamento", "paq": "Parya", "par": "Panamint; Timbisha", "pas": "Papasena", "pau": "Palauan", "pav": "Pakaásnovos", "paw": "Pawnee", "pax": "Pankararé", "pay": "Pech", "paz": "Pankararú", "pbb": "Páez", "pbc": "Patamona", "pbe": "Mezontla Popoloca", "pbf": "Coyotepec Popoloca", "pbg": "Paraujano", "pbh": "E'ñapa Woromaipu", "pbi": "Parkwa", "pbl": "Mak (Nigeria)", "pbm": "Puebla Mazatec", "pbn": "Kpasam", "pbo": "Papel", "pbp": "Badyara", "pbr": "Pangwa", "pbs": "Central Pame", "pbt": "Southern Pashto", "pbu": "Northern Pashto", "pbv": "Pnar", "pby": "Pyu (Papua New Guinea)", "pca": "Santa Inés Ahuatempan Popoloca", "pcb": "Pear", "pcc": "Bouyei", "pcd": "Picard", "pce": "Ruching Palaung", "pcf": "Paliyan", "pcg": "Paniya", "pch": "Pardhan", "pci": "Duruwa", "pcj": "Parenga", "pck": "Paite Chin", "pcl": "Pardhi", "pcm": "Nigerian Pidgin", "pcn": "Piti", "pcp": "Pacahuara", "pcw": "Pyapun", "pda": "Anam", "pdc": "Pennsylvania German", "pdi": "Pa Di", "pdn": "Podena; Fedan", "pdo": "Padoe", "pdt": "Plautdietsch", "pdu": "Kayan", "pea": "Peranakan Indonesian", "peb": "Eastern Pomo", "ped": "Mala (Papua New Guinea)", "pee": "Taje", "pef": "Northeastern Pomo", "peg": "Pengo", "peh": "Bonan", "pei": "Chichimeca-Jonaz", "pej": "Northern Pomo", "pek": "Penchal", "pel": "Pekal", "pem": "Phende", "peo": "Old Persian (ca. 600-400 B.C.)", "pep": "Kunja", "peq": "Southern Pomo", "pes": "Iranian Persian", "pev": "Pémono", "pex": "Petats", "pey": "Petjo", "pez": "Eastern Penan", "pfa": "Pááfang", "pfe": "Pere", "pfl": "Pfaelzisch", "pga": "Sudanese Creole Arabic", "pgd": "Gāndhārī", "pgg": "Pangwali", "pgi": "Pagi", "pgk": "Rerep", "pgl": "Primitive Irish", "pgn": "Paelignian", "pgs": "Pangseng", "pgu": "Pagu", "pgz": "Papua New Guinean Sign Language", "pha": "Pa-Hng", "phd": "Phudagi", "phg": "Phuong", "phh": "Phukha", "phi": "Philippine languages", "phj": "Pahari", "phk": "Phake", "phl": "Phalura; Palula", "phm": "Phimbi", "phn": "Phoenician", "pho": "Phunoi", "phq": "Phana'", "phr": "Pahari-Potwari", "pht": "Phu Thai", "phu": "Phuan", "phv": "Pahlavani", "phw": "Phangduwali", "pi": "Pali", "pia": "Pima Bajo", "pib": "Yine", "pic": "Pinji", "pid": "Piaroa", "pie": "Piro", "pif": "Pingelapese", "pig": "Pisabo", "pih": "Pitcairn-Norfolk", "pij": "Pijao", "pil": "Yom", "pim": "Powhatan", "pin": "Piame", "pio": "Piapoco", "pip": "Pero", "pir": "Piratapuyo", "pis": "Pijin", "pit": "Pitta Pitta", "piu": "Pintupi-Luritja", "piv": "Pileni; Vaeakau-Taumako", "piw": "Pimbwe", "pix": "Piu", "piy": "Piya-Kwonci", "piz": "Pije", "pjt": "Pitjantjatjara", "pka": "Ardhamāgadhī Prākrit", "pkb": "Pokomo; Kipfokomo", "pkc": "Paekche", "pkg": "Pak-Tong", "pkh": "Pankhu", "pkn": "Pakanha", "pko": "Pökoot", "pkp": "Pukapuka", "pkr": "Attapady Kurumba", "pks": "Pakistan Sign Language", "pkt": "Maleng", "pku": "Paku", "pl": "Polish", "pla": "Miani", "plb": "Polonombauk", "plc": "Central Palawano", "pld": "Polari", "ple": "Palu'e", "plf": "Central Malayo-Polynesian languages", "plg": "Pilagá", "plh": "Paulohi", "plj": "Polci", "plk": "Kohistani Shina", "pll": "Shwe Palaung", "pln": "Palenquero", "plo": "Oluta Popoluca", "plq": "Palaic", "plr": "Palaka Senoufo", "pls": "San Marcos Tlacoyalco Popoloca; San Marcos Tlalcoyalco Popoloca", "plt": "Plateau Malagasy", "plu": "Palikúr", "plv": "Southwest Palawano", "plw": "Brooke's Point Palawano", "ply": "Bolyu", "plz": "Paluan", "pma": "Paama", "pmb": "Pambia", "pmd": "Pallanganmiddang", "pme": "Pwaamei", "pmf": "Pamona", "pmh": "Māhārāṣṭri Prākrit", "pmi": "Northern Pumi", "pmj": "Southern Pumi", "pmk": "Pamlico", "pml": "Lingua Franca", "pmm": "Pomo", "pmn": "Pam", "pmo": "Pom", "pmq": "Northern Pame", "pmr": "Paynamar", "pms": "Piemontese", "pmt": "Tuamotuan", "pmw": "Plains Miwok", "pmx": "Poumei Naga", "pmy": "Papuan Malay", "pmz": "Southern Pame", "pna": "Punan Bah-Biau", "pnb": "Western Panjabi", "pnc": "Pannei", "pnd": "Mpinda", "pne": "Western Penan", "png": "Pangu; Pongu", "pnh": "Penrhyn", "pni": "Aoheng", "pnj": "Pinjarup", "pnk": "Paunaka", "pnl": "Paleni", "pnm": "Punan Batu 1", "pnn": "Pinai-Hagahai", "pno": "Panobo", "pnp": "Pancana", "pnq": "Pana (Burkina Faso)", "pnr": "Panim", "pns": "Ponosakan", "pnt": "Pontic", "pnu": "Jiongnai Bunu", "pnv": "Pinigura", "pnw": "Banyjima; Panytyima", "pnx": "Phong-Kniang", "pny": "Pinyin", "pnz": "Pana (Central African Republic)", "poc": "Poqomam", "poe": "San Juan Atzingo Popoloca", "pof": "Poke", "pog": "Potiguára", "poh": "Poqomchi'", "poi": "Highland Popoluca", "pok": "Pokangá", "pom": "Southeastern Pomo", "pon": "Pohnpeian", "poo": "Central Pomo", "pop": "Pwapwâ", "poq": "Texistepec Popoluca", "pos": "Sayula Popoluca", "pot": "Potawatomi", "pov": "Upper Guinea Crioulo", "pow": "San Felipe Otlaltepec Popoloca", "pox": "Polabian", "poy": "Pogolo", "poz": "Malayo-Polynesian languages", "ppe": "Papi", "ppi": "Paipai", "ppk": "Uma", "ppl": "Pipil; Nicarao", "ppm": "Papuma", "ppn": "Papapana", "ppo": "Folopa", "ppp": "Pelende", "ppq": "Pei", "pps": "San Luís Temalacayuca Popoloca", "ppt": "Pare", "ppu": "Papora", "pqa": "Pa'a", "pqe": "Eastern Malayo-Polynesian languages", "pqm": "Malecite-Passamaquoddy", "pqw": "Western Malayo-Polynesian languages", "pra": "Prakrit languages", "prc": "Parachi", "prd": "Parsi-Dari", "pre": "Principense", "prf": "Paranan", "prg": "Prussian", "prh": "Porohanon", "pri": "Paicî", "prk": "Parauk", "prl": "Peruvian Sign Language", "prm": "Kibiri", "prn": "Prasuni", "pro": "Old Provençal (to 1500); Old Occitan (to 1500)", "prp": "Parsi", "prq": "Ashéninka Perené", "prr": "Puri", "prs": "Dari; Afghan Persian", "prt": "Phai", "pru": "Puragi", "prw": "Parawen", "prx": "Purik", "prz": "Providencia Sign Language", "ps": "Pushto; Pashto", "psa": "Asue Awyu", "psc": "Iranian Sign Language; Persian Sign Language", "psd": "Plains Indian Sign Language", "pse": "Central Malay", "psg": "Penang Sign Language", "psh": "Southwest Pashai; Southwest Pashayi", "psi": "Southeast Pashai; Southeast Pashayi", "psl": "Puerto Rican Sign Language", "psm": "Pauserna", "psn": "Panasuan", "pso": "Polish Sign Language", "psp": "Philippine Sign Language", "psq": "Pasi", "psr": "Portuguese Sign Language", "pss": "Kaulong", "pst": "Central Pashto", "psu": "Sauraseni Prākrit", "psw": "Port Sandwich", "psy": "Piscataway", "pt": "Portuguese", "pta": "Pai Tavytera", "pth": "Pataxó Hã-Ha-Hãe", "pti": "Pindiini; Wangkatha", "ptn": "Patani", "pto": "Zo'é", "ptp": "Patep", "ptq": "Pattapu", "ptr": "Piamatsina", "ptt": "Enrekang", "ptu": "Bambam", "ptv": "Port Vato", "ptw": "Pentlatch", "pty": "Pathiya", "pua": "Western Highland Purepecha", "pub": "Purum", "puc": "Punan Merap", "pud": "Punan Aput", "pue": "Puelche", "puf": "Punan Merah", "pug": "Phuie", "pui": "Puinave", "puj": "Punan Tubu", "pum": "Puma", "puo": "Puoc", "pup": "Pulabu", "puq": "Puquina", "pur": "Puruborá", "put": "Putoh", "puu": "Punu", "puw": "Puluwatese", "pux": "Puare", "puy": "Purisimeño", "pwa": "Pawaia", "pwb": "Panawa", "pwg": "Gapapaiwa", "pwi": "Patwin", "pwm": "Molbog", "pwn": "Paiwan", "pwo": "Pwo Western Karen", "pwr": "Powari", "pww": "Pwo Northern Karen", "pxm": "Quetzaltepec Mixe", "pye": "Pye Krumen", "pym": "Fyam", "pyn": "Poyanáwa", "pys": "Paraguayan Sign Language; Lengua de Señas del Paraguay", "pyu": "Puyuma", "pyx": "Pyu (Myanmar)", "pyy": "Pyen", "pzh": "Pazeh", "pzn": "Jejara Naga; Para Naga", "qu": "Quechua", "qua": "Quapaw", "qub": "Huallaga Huánuco Quechua", "quc": "K'iche'; Quiché", "qud": "Calderón Highland Quichua", "quf": "Lambayeque Quechua", "qug": "Chimborazo Highland Quichua", "quh": "South Bolivian Quechua", "qui": "Quileute", "quk": "Chachapoyas Quechua", "qul": "North Bolivian Quechua", "qum": "Sipacapense", "qun": "Quinault", "qup": "Southern Pastaza Quechua", "quq": "Quinqui", "qur": "Yanahuanca Pasco Quechua", "qus": "Santiago del Estero Quichua", "quv": "Sacapulteco", "quw": "Tena Lowland Quichua", "qux": "Yauyos Quechua", "quy": "Ayacucho Quechua", "quz": "Cusco Quechua", "qva": "Ambo-Pasco Quechua", "qvc": "Cajamarca Quechua", "qve": "Eastern Apurímac Quechua", "qvh": "Huamalíes-Dos de Mayo Huánuco Quechua", "qvi": "Imbabura Highland Quichua", "qvj": "Loja Highland Quichua", "qvl": "Cajatambo North Lima Quechua", "qvm": "Margos-Yarowilca-Lauricocha Quechua", "qvn": "North Junín Quechua", "qvo": "Napo Lowland Quechua", "qvp": "Pacaraos Quechua", "qvs": "San Martín Quechua", "qvw": "Huaylla Wanca Quechua", "qvy": "Queyu", "qvz": "Northern Pastaza Quichua", "qwa": "Corongo Ancash Quechua", "qwc": "Classical Quechua", "qwe": "Quechuan (family)", "qwh": "Huaylas Ancash Quechua", "qwm": "Kuman (Russia)", "qws": "Sihuas Ancash Quechua", "qwt": "Kwalhioqua-Tlatskanai", "qxa": "Chiquián Ancash Quechua", "qxc": "Chincha Quechua", "qxh": "Panao Huánuco Quechua", "qxl": "Salasaca Highland Quichua", "qxn": "Northern Conchucos Ancash Quechua", "qxo": "Southern Conchucos Ancash Quechua", "qxp": "Puno Quechua", "qxq": "Qashqa'i", "qxr": "Cañar Highland Quichua", "qxs": "Southern Qiang", "qxt": "Santa Ana de Tusi Pasco Quechua", "qxu": "Arequipa-La Unión Quechua", "qxw": "Jauja Wanca Quechua", "qya": "Quenya", "qyp": "Quiripi", "raa": "Dungmali", "rab": "Camling", "rac": "Rasawa", "rad": "Rade", "raf": "Western Meohang", "rag": "Logooli; Lulogooli", "rah": "Rabha", "rai": "Ramoaaina", "raj": "Rajasthani", "rak": "Tulu-Bohuai", "ral": "Ralte", "ram": "Canela", "ran": "Riantana", "rao": "Rao", "rap": "Rapanui", "raq": "Saam", "rar": "Rarotongan; Cook Islands Maori", "ras": "Tegali", "rat": "Razajerdi", "rau": "Raute", "rav": "Sampang", "raw": "Rawang", "rax": "Rang", "ray": "Rapa", "raz": "Rahambuu", "rbb": "Rumai Palaung", "rbk": "Northern Bontok", "rbl": "Miraya Bikol", "rbp": "Barababaraba", "rcf": "Réunion Creole French", "rdb": "Rudbari", "rea": "Rerau", "reb": "Rembong", "ree": "Rejang Kayan", "reg": "Kara (Tanzania)", "rei": "Reli", "rej": "Rejang", "rel": "Rendille", "rem": "Remo", "ren": "Rengao", "rer": "Rer Bare", "res": "Reshe", "ret": "Retta", "rey": "Reyesano", "rga": "Roria", "rge": "Romano-Greek", "rgk": "Rangkas", "rgn": "Romagnol", "rgr": "Resígaro", "rgs": "Southern Roglai", "rgu": "Ringgou", "rhg": "Rohingya", "rhp": "Yahang", "ria": "Riang (India)", "rib": "Bribri Sign Language", "rif": "Tarifit", "ril": "Riang Lang; Riang (Myanmar)", "rim": "Nyaturu", "rin": "Nungu", "rir": "Ribun", "rit": "Ritharrngu", "riu": "Riung", "rjg": "Rajong", "rji": "Raji", "rjs": "Rajbanshi", "rka": "Kraol", "rkb": "Rikbaktsa", "rkh": "Rakahanga-Manihiki", "rki": "Rakhine", "rkm": "Marka", "rkt": "Rangpuri; Kamta", "rkw": "Arakwal", "rm": "Romansh", "rma": "Rama", "rmb": "Rembarrnga", "rmc": "Carpathian Romani", "rmd": "Traveller Danish", "rme": "Angloromani", "rmf": "Kalo Finnish Romani", "rmg": "Traveller Norwegian", "rmh": "Murkim", "rmi": "Lomavren", "rmk": "Romkun", "rml": "Baltic Romani", "rmm": "Roma", "rmn": "Balkan Romani", "rmo": "Sinte Romani", "rmp": "Rempi", "rmq": "Caló", "rms": "Romanian Sign Language", "rmt": "Domari", "rmu": "Tavringer Romani", "rmv": "Romanova", "rmw": "Welsh Romani", "rmx": "Romam", "rmy": "Vlax Romani", "rmz": "Marma", "rn": "Rundi", "rnb": "Brunca Sign Language", "rnd": "Ruund", "rng": "Ronga", "rnl": "Ranglong", "rnn": "Roon", "rnp": "Rongpo", "rnr": "Nari Nari", "rnw": "Rungwa", "ro": "Romanian; Moldavian; Moldovan", "roa": "Romance languages", "rob": "Tae'", "roc": "Cacgia Roglai", "rod": "Rogo", "roe": "Ronji", "rof": "Rombo", "rog": "Northern Roglai", "rol": "Romblomanon", "rom": "Romany", "roo": "Rotokas", "rop": "Kriol", "ror": "Rongga", "rou": "Runga", "row": "Dela-Oenale", "rpn": "Repanbitip", "rpt": "Rapting", "rri": "Ririo", "rro": "Waima", "rrt": "Arritinngithigh", "rsb": "Romano-Serbian", "rsk": "Ruthenian; Rusyn", "rsl": "Russian Sign Language", "rsm": "Miriwoong Sign Language", "rsn": "Rwandan Sign Language", "rtc": "Rungtu Chin", "rth": "Ratahan", "rtm": "Rotuman", "rts": "Yurats", "rtw": "Rathawi", "ru": "Russian", "rub": "Gungu", "ruc": "Ruuli", "rue": "Rusyn", "ruf": "Luguru", "rug": "Roviana", "ruh": "Ruga", "rui": "Rufiji", "ruk": "Che", "ruo": "Istro Romanian", "rup": "Macedo-Romanian; Aromanian; Arumanian", "ruq": "Megleno Romanian", "rut": "Rutul", "ruu": "Lanas Lobu", "ruy": "Mala (Nigeria)", "ruz": "Ruma", "rw": "Kinyarwanda", "rwa": "Rawo", "rwk": "Rwa", "rwl": "Ruwila", "rwm": "Amba (Uganda)", "rwo": "Rawa", "rwr": "Marwari (India)", "rxd": "Ngardi", "rxw": "Karuwali; Garuwali", "ryn": "Northern Amami-Oshima", "rys": "Yaeyama", "ryu": "Central Okinawan", "rzh": "Rāziḥī", "sa": "Sanskrit", "saa": "Saba", "sab": "Buglere", "sac": "Meskwaki", "sad": "Sandawe", "sae": "Sabanê", "saf": "Safaliba", "sah": "Yakut", "sai": "South American Indian languages", "saj": "Sahu", "sak": "Sake", "sal": "Salishan languages", "sam": "Samaritan Aramaic", "sao": "Sause", "saq": "Samburu", "sar": "Saraveca", "sas": "Sasak", "sat": "Santali", "sau": "Saleman", "sav": "Saafi-Saafi", "saw": "Sawi", "sax": "Sa", "say": "Saya", "saz": "Saurashtra", "sba": "Ngambay", "sbb": "Simbo", "sbc": "Kele (Papua New Guinea)", "sbd": "Southern Samo", "sbe": "Saliba", "sbf": "Chabu; Shabo", "sbg": "Seget", "sbh": "Sori-Harengan", "sbi": "Seti", "sbj": "Surbakhal", "sbk": "Safwa", "sbl": "Botolan Sambal", "sbm": "Sagala", "sbn": "Sindhi Bhil", "sbo": "Sabüm", "sbp": "Sangu (Tanzania)", "sbq": "Sileibi", "sbr": "Sembakung Murut", "sbs": "Subiya", "sbt": "Kimki", "sbu": "Stod Bhoti", "sbv": "Sabine", "sbw": "Simba", "sbx": "Seberuang", "sby": "Soli", "sbz": "Sara Kaba", "sc": "Sardinian", "scb": "Chut", "sce": "Dongxiang", "scf": "San Miguel Creole French", "scg": "Sanggau", "sch": "Sakachep", "sci": "Sri Lankan Creole Malay", "sck": "Sadri", "scl": "Shina", "scn": "Sicilian", "sco": "Scots", "scp": "Hyolmo; Helambu Sherpa", "scq": "Sa'och", "scs": "North Slavey", "sct": "Southern Katang", "scu": "Shumcho", "scv": "Sheni", "scw": "Sha", "scx": "Sicel", "sd": "Sindhi", "sda": "Toraja-Sa'dan", "sdb": "Shabak", "sdc": "Sassarese Sardinian", "sde": "Surubu", "sdf": "Sarli", "sdg": "Savi", "sdh": "Southern Kurdish", "sdj": "Suundi", "sdk": "Sos Kundi", "sdl": "Saudi Arabian Sign Language", "sdn": "Gallurese Sardinian", "sdo": "Bukar-Sadung Bidayuh", "sdp": "Sherdukpen", "sdq": "Semandang", "sdr": "Oraon Sadri", "sds": "Sened", "sdt": "Shuadit", "sdu": "Sarudu", "sdv": "Eastern Sudanic languages", "sdx": "Sibu Melanau", "sdz": "Sallands", "se": "Northern Sami", "sea": "Semai", "seb": "Shempire Senoufo", "sec": "Sechelt", "sed": "Sedang", "see": "Seneca", "sef": "Cebaara Senoufo", "seg": "Segeju", "seh": "Sena", "sei": "Seri", "sej": "Sene", "sek": "Sekani", "sel": "Selkup", "sem": "Semitic languages", "sen": "Nanerigé Sénoufo", "seo": "Suarmin", "sep": "Sìcìté Sénoufo", "seq": "Senara Sénoufo", "ser": "Serrano", "ses": "Koyraboro Senni Songhai", "set": "Sentani", "seu": "Serui-Laut", "sev": "Nyarafolo Senoufo", "sew": "Sewa Bay", "sey": "Secoya", "sez": "Senthang Chin", "sfb": "Langue des signes de Belgique Francophone; French Belgian Sign Language", "sfe": "Eastern Subanen", "sfm": "Small Flowery Miao", "sfs": "South African Sign Language", "sfw": "Sehwi", "sg": "Sango", "sga": "Old Irish (to 900)", "sgb": "Mag-antsi Ayta", "sgc": "Kipsigis", "sgd": "Surigaonon", "sge": "Segai", "sgg": "Swiss-German Sign Language", "sgh": "Shughni", "sgi": "Suga", "sgj": "Surgujia", "sgk": "Sangkong", "sgm": "Singa", "sgn": "Sign languages", "sgp": "Singpho", "sgr": "Sangisari", "sgs": "Samogitian", "sgt": "Brokpake", "sgu": "Salas", "sgw": "Sebat Bet Gurage", "sgx": "Sierra Leone Sign Language", "sgy": "Sanglechi", "sgz": "Sursurunga", "sh": "Serbo-Croatian", "sha": "Shall-Zwall", "shb": "Ninam", "shc": "Sonde", "shd": "Kundal Shahi", "she": "Sheko", "shg": "Shua", "shh": "Shoshoni", "shi": "Tachelhit", "shj": "Shatt", "shk": "Shilluk", "shl": "Shendu", "shm": "Shahrudi", "shn": "Shan", "sho": "Shanga", "shp": "Shipibo-Conibo", "shq": "Sala", "shr": "Shi", "shs": "Shuswap", "sht": "Shasta", "shu": "Chadian Arabic", "shv": "Shehri", "shw": "Shwai", "shx": "She", "shy": "Tachawit", "shz": "Syenara Senoufo", "si": "Sinhala; Sinhalese", "sia": "Akkala Sami", "sib": "Sebop", "sid": "Sidamo", "sie": "Simaa", "sif": "Siamou", "sig": "Paasaal", "sih": "Zire; Sîshëë", "sii": "Shom Peng", "sij": "Numbami", "sik": "Sikiana", "sil": "Tumulung Sisaala", "sim": "Mende (Papua New Guinea)", "sio": "Siouan languages", "sip": "Sikkimese", "siq": "Sonia", "sir": "Siri", "sis": "Siuslaw", "sit": "Sino-Tibetan languages", "siu": "Sinagen", "siv": "Sumariup", "siw": "Siwai", "six": "Sumau", "siy": "Sivandi", "siz": "Siwi", "sja": "Epena", "sjb": "Sajau Basap", "sjd": "Kildin Sami", "sje": "Pite Sami", "sjg": "Assangori", "sjk": "Kemi Sami", "sjl": "Sajalong; Miji", "sjm": "Mapun", "sjn": "Sindarin", "sjo": "Xibe", "sjp": "Surjapuri", "sjr": "Siar-Lak", "sjs": "Senhaja De Srair", "sjt": "Ter Sami", "sju": "Ume Sami", "sjw": "Shawnee", "sk": "Slovak", "ska": "Skagit", "skb": "Saek", "skc": "Ma Manda", "skd": "Southern Sierra Miwok", "ske": "Seke (Vanuatu)", "skf": "Sakirabiá", "skg": "Sakalava Malagasy", "skh": "Sikule", "ski": "Sika", "skj": "Seke (Nepal)", "skm": "Kutong", "skn": "Kolibugan Subanon", "sko": "Seko Tengah", "skp": "Sekapan", "skq": "Sininkere", "skr": "Saraiki; Seraiki", "sks": "Maia", "skt": "Sakata", "sku": "Sakao", "skv": "Skou", "skw": "Skepi Creole Dutch", "skx": "Seko Padang", "sky": "Sikaiana", "skz": "Sekar", "sl": "Slovenian", "sla": "Slavic languages", "slc": "Sáliba", "sld": "Sissala", "sle": "Sholaga", "slf": "Swiss-Italian Sign Language", "slg": "Selungai Murut", "slh": "Southern Puget Sound Salish", "sli": "Lower Silesian", "slj": "Salumá", "sll": "Salt-Yui", "slm": "Pangutaran Sama", "sln": "Salinan", "slp": "Lamaholot", "slq": "Salchuq", "slr": "Salar", "sls": "Singapore Sign Language", "slt": "Sila", "slu": "Selaru", "slw": "Sialum", "slx": "Salampasu", "sly": "Selayar", "slz": "Ma'ya", "sm": "Samoan", "sma": "Southern Sami", "smb": "Simbari", "smc": "Som", "smf": "Auwe", "smg": "Simbali", "smh": "Samei", "smi": "Sami languages", "smj": "Lule Sami", "smk": "Bolinao", "sml": "Central Sama", "smm": "Musasa", "smn": "Inari Sami", "smp": "Samaritan", "smq": "Samo", "smr": "Simeulue", "sms": "Skolt Sami", "smt": "Simte", "smu": "Somray", "smv": "Samvedi", "smw": "Sumbawa", "smx": "Samba", "smy": "Semnani", "smz": "Simeku", "sn": "Shona", "snc": "Sinaugoro", "sne": "Bau Bidayuh", "snf": "Noon", "sng": "Sanga (Democratic Republic of Congo)", "sni": "Sensi", "snj": "Riverain Sango", "snk": "Soninke", "snl": "Sangil", "snm": "Southern Ma'di", "snn": "Siona", "sno": "Snohomish", "snp": "Siane", "snq": "Sangu (Gabon)", "snr": "Sihan", "sns": "South West Bay; Nahavaq", "snu": "Senggi; Viid", "snv": "Sa'ban", "snw": "Selee", "snx": "Sam", "sny": "Saniyo-Hiyewe", "snz": "Kou", "so": "Somali", "soa": "Thai Song", "sob": "Sobei", "soc": "So (Democratic Republic of Congo)", "sod": "Songoora", "soe": "Songomeno", "sog": "Sogdian", "soh": "Aka", "soi": "Sonha", "soj": "Soi", "sok": "Sokoro", "sol": "Solos", "son": "Songhai languages", "soo": "Songo", "sop": "Songe", "soq": "Kanasi", "sor": "Somrai", "sos": "Seeku", "sou": "Southern Thai", "sov": "Sonsorol", "sow": "Sowanda", "sox": "Swo", "soy": "Miyobe", "soz": "Temi", "spb": "Sepa (Indonesia)", "spc": "Sapé", "spd": "Saep", "spe": "Sepa (Papua New Guinea)", "spg": "Sian", "spi": "Saponi", "spk": "Sengo", "spl": "Selepet", "spm": "Akukem", "spn": "Sanapaná", "spo": "Spokane", "spp": "Supyire Senoufo", "spq": "Loreto-Ucayali Spanish", "spr": "Saparua", "sps": "Saposa", "spt": "Spiti Bhoti", "spu": "Sapuan", "spv": "Sambalpuri; Kosli", "spx": "South Picene", "spy": "Sabaot", "sq": "Albanian", "sqa": "Shama-Sambuga", "sqh": "Shau", "sqj": "Albanian languages", "sqk": "Albanian Sign Language", "sqm": "Suma", "sqn": "Susquehannock", "sqo": "Sorkhei", "sqq": "Sou", "sqr": "Siculo Arabic", "sqs": "Sri Lankan Sign Language", "sqt": "Soqotri", "squ": "Squamish", "sqx": "Kufr Qassem Sign Language (KQSL)", "sr": "Serbian", "sra": "Saruga", "srb": "Sora", "src": "Logudorese Sardinian", "sre": "Sara", "srf": "Nafi", "srg": "Sulod", "srh": "Sarikoli", "sri": "Siriano", "srk": "Serudung Murut", "srl": "Isirawa", "srm": "Saramaccan", "srn": "Sranan Tongo", "sro": "Campidanese Sardinian", "srq": "Sirionó", "srr": "Serer", "srs": "Sarsi", "srt": "Sauri", "sru": "Suruí", "srv": "Southern Sorsoganon", "srw": "Serua", "srx": "Sirmauri", "sry": "Sera", "srz": "Shahmirzadi", "ss": "Swati", "ssa": "Nilo-Saharan languages", "ssb": "Southern Sama", "ssc": "Suba-Simbiti", "ssd": "Siroi", "sse": "Balangingi; Bangingih Sama", "ssf": "Thao", "ssg": "Seimat", "ssh": "Shihhi Arabic", "ssi": "Sansi", "ssj": "Sausi", "ssk": "Sunam", "ssl": "Western Sisaala", "ssm": "Semnam", "ssn": "Waata", "sso": "Sissano", "ssp": "Spanish Sign Language", "ssq": "So'a", "ssr": "Swiss-French Sign Language", "sss": "Sô", "sst": "Sinasina", "ssu": "Susuami", "ssv": "Shark Bay", "ssx": "Samberigi", "ssy": "Saho", "ssz": "Sengseng", "st": "Southern Sotho", "sta": "Settla", "stb": "Northern Subanen", "std": "Sentinel", "ste": "Liana-Seti", "stf": "Seta", "stg": "Trieng", "sth": "Shelta", "sti": "Bulo Stieng", "stj": "Matya Samo", "stk": "Arammba", "stl": "Stellingwerfs", "stm": "Setaman", "stn": "Owa", "sto": "Stoney", "stp": "Southeastern Tepehuan", "stq": "Saterfriesisch", "str": "Straits Salish", "sts": "Shumashti", "stt": "Budeh Stieng", "stu": "Samtao", "stv": "Silt'e", "stw": "Satawalese", "sty": "Siberian Tatar", "su": "Sundanese", "sua": "Sulka", "sub": "Suku", "suc": "Western Subanon", "sue": "Suena", "sug": "Suganga", "sui": "Suki", "suj": "Shubi", "suk": "Sukuma", "suo": "Bouni", "suq": "Tirmaga-Chai Suri; Suri", "sur": "Mwaghavul", "sus": "Susu", "sut": "Subtiaba", "suv": "Puroik", "suw": "Sumbwa", "sux": "Sumerian", "suy": "Suyá", "suz": "Sunwar", "sv": "Swedish", "sva": "Svan", "svb": "Ulau-Suain", "svc": "Vincentian Creole English", "sve": "Serili", "svk": "Slovakian Sign Language", "svm": "Slavomolisano", "svs": "Savosavo", "svx": "Skalvian", "sw": "Swahili (macrolanguage)", "swb": "Maore Comorian", "swc": "Congo Swahili", "swf": "Sere", "swg": "Swabian", "swh": "Swahili (individual language); Kiswahili", "swi": "Sui", "swj": "Sira", "swk": "Malawi Sena", "swl": "Swedish Sign Language", "swm": "Samosa", "swn": "Sawknah", "swo": "Shanenawa", "swp": "Suau", "swq": "Sharwa", "swr": "Saweru", "sws": "Seluwasan", "swt": "Sawila", "swu": "Suwawa", "swv": "Shekhawati", "sww": "Sowa", "swx": "Suruahá", "swy": "Sarua", "sxb": "Suba", "sxc": "Sicanian", "sxe": "Sighu", "sxg": "Shuhi; Shixing", "sxk": "Southern Kalapuya", "sxl": "Selian", "sxm": "Samre", "sxn": "Sangir", "sxo": "Sorothaptic", "sxr": "Saaroa", "sxs": "Sasaru", "sxu": "Upper Saxon", "sxw": "Saxwe Gbe", "sya": "Siang", "syb": "Central Subanen", "syc": "Classical Syriac", "syd": "Samoyedic languages", "syi": "Seki", "syk": "Sukur", "syl": "Sylheti", "sym": "Maya Samo", "syn": "Senaya", "syo": "Suoy", "syr": "Syriac", "sys": "Sinyar", "syw": "Kagate", "syx": "Samay", "syy": "Al-Sayyid Bedouin Sign Language", "sza": "Semelai", "szb": "Ngalum", "szc": "Semaq Beri", "szd": "Seru", "sze": "Seze", "szg": "Sengele", "szl": "Silesian", "szn": "Sula", "szp": "Suabo", "szs": "Solomon Islands Sign Language", "szv": "Isu (Fako Division)", "szw": "Sawai", "szy": "Sakizaya", "ta": "Tamil", "taa": "Lower Tanana", "tab": "Tabassaran", "tac": "Lowland Tarahumara", "tad": "Tause", "tae": "Tariana", "taf": "Tapirapé", "tag": "Tagoi", "tai": "Tai languages", "taj": "Eastern Tamang", "tak": "Tala", "tal": "Tal", "tan": "Tangale", "tao": "Yami", "tap": "Taabwa", "taq": "Tamasheq", "tar": "Central Tarahumara", "tas": "Tay Boi", "tau": "Upper Tanana", "tav": "Tatuyo", "taw": "Tai", "tax": "Tamki", "tay": "Atayal", "taz": "Tocho", "tba": "Aikanã", "tbc": "Takia", "tbd": "Kaki Ae", "tbe": "Tanimbili", "tbf": "Mandara", "tbg": "North Tairora", "tbh": "Dharawal; Thurawal", "tbi": "Gaam", "tbj": "Tiang", "tbk": "Calamian Tagbanwa", "tbl": "Tboli", "tbm": "Tagbu", "tbn": "Barro Negro Tunebo", "tbo": "Tawala", "tbp": "Taworta; Diebroud", "tbq": "Tibeto-Burman languages", "tbr": "Tumtum", "tbs": "Tanguat", "tbt": "Tembo (Kitembo)", "tbu": "Tubar", "tbv": "Tobo", "tbw": "Tagbanwa", "tbx": "Kapin", "tby": "Tabaru", "tbz": "Ditammari", "tca": "Ticuna", "tcb": "Tanacross", "tcc": "Datooga", "tcd": "Tafi", "tce": "Southern Tutchone", "tcf": "Malinaltepec Me'phaa; Malinaltepec Tlapanec", "tcg": "Tamagario", "tch": "Turks And Caicos Creole English", "tci": "Wára", "tck": "Tchitchege", "tcl": "Taman (Myanmar)", "tcm": "Tanahmerah", "tcn": "Tichurong", "tco": "Taungyo", "tcp": "Tawr Chin", "tcq": "Kaiy", "tcs": "Torres Strait Creole; Yumplatok", "tct": "T'en", "tcu": "Southeastern Tarahumara", "tcw": "Tecpatlán Totonac", "tcx": "Toda", "tcy": "Tulu", "tcz": "Thado Chin", "tda": "Tagdal", "tdb": "Panchpargania", "tdc": "Emberá-Tadó", "tdd": "Tai Nüa", "tde": "Tiranige Diga Dogon", "tdf": "Talieng", "tdg": "Western Tamang", "tdh": "Thulung", "tdi": "Tomadino", "tdj": "Tajio", "tdk": "Tambas", "tdl": "Sur", "tdm": "Taruma", "tdn": "Tondano", "tdo": "Teme", "tdq": "Tita", "tdr": "Todrah", "tds": "Doutai", "tdt": "Tetun Dili", "tdv": "Toro", "tdx": "Tandroy-Mahafaly Malagasy", "tdy": "Tadyawan", "te": "Telugu", "tea": "Temiar", "teb": "Tetete", "tec": "Terik", "ted": "Tepo Krumen", "tee": "Huehuetla Tepehua", "tef": "Teressa", "teg": "Teke-Tege", "teh": "Tehuelche", "tei": "Torricelli", "tek": "Ibali Teke", "tem": "Timne", "ten": "Tama (Colombia)", "teo": "Teso", "tep": "Tepecano", "teq": "Temein", "ter": "Tereno", "tes": "Tengger", "tet": "Tetum", "teu": "Soo", "tev": "Teor", "tew": "Tewa (USA)", "tex": "Tennet", "tey": "Tulishi", "tez": "Tetserret", "tfi": "Tofin Gbe", "tfn": "Tanaina", "tfo": "Tefaro", "tfr": "Teribe", "tft": "Ternate", "tg": "Tajik", "tga": "Sagalla", "tgb": "Tobilung", "tgc": "Tigak", "tgd": "Ciwogai", "tge": "Eastern Gorkha Tamang", "tgf": "Chalikha", "tgh": "Tobagonian Creole English", "tgi": "Lawunuia", "tgj": "Tagin", "tgn": "Tandaganon", "tgo": "Sudest", "tgp": "Tangoa", "tgq": "Tring", "tgr": "Tareng", "tgs": "Nume", "tgt": "Central Tagbanwa", "tgu": "Tanggu", "tgv": "Tingui-Boto", "tgw": "Tagwana Senoufo", "tgx": "Tagish", "tgy": "Togoyo", "tgz": "Tagalaka", "th": "Thai", "thd": "Kuuk Thaayorre; Thayore", "the": "Chitwania Tharu", "thf": "Thangmi", "thh": "Northern Tarahumara", "thi": "Tai Long", "thk": "Tharaka; Kitharaka", "thl": "Dangaura Tharu", "thm": "Aheu", "thn": "Thachanadan", "thp": "Thompson", "thq": "Kochila Tharu", "thr": "Rana Tharu", "ths": "Thakali", "tht": "Tahltan", "thu": "Thuri", "thv": "Tahaggart Tamahaq", "thy": "Tha", "thz": "Tayart Tamajeq", "ti": "Tigrinya", "tia": "Tidikelt Tamazight", "tic": "Tira", "tif": "Tifal", "tig": "Tigre", "tih": "Timugon Murut", "tii": "Tiene", "tij": "Tilung", "tik": "Tikar", "til": "Tillamook", "tim": "Timbe", "tin": "Tindi", "tio": "Teop", "tip": "Trimuris", "tiq": "Tiéfo", "tis": "Masadiit Itneg", "tit": "Tinigua", "tiu": "Adasen", "tiv": "Tiv", "tiw": "Tiwi", "tix": "Southern Tiwa", "tiy": "Tiruray", "tiz": "Tai Hongjin", "tja": "Tajuasohn", "tjg": "Tunjung", "tji": "Northern Tujia", "tjj": "Tjungundji", "tjl": "Tai Laing", "tjm": "Timucua", "tjn": "Tonjon", "tjo": "Temacine Tamazight", "tjp": "Tjupany", "tjs": "Southern Tujia", "tju": "Tjurruru", "tjw": "Djabwurrung", "tk": "Turkmen", "tka": "Truká", "tkb": "Buksa", "tkd": "Tukudede", "tke": "Takwane", "tkf": "Tukumanféd", "tkg": "Tesaka Malagasy", "tkl": "Tokelau", "tkm": "Takelma", "tkn": "Toku-No-Shima", "tkp": "Tikopia", "tkq": "Tee", "tkr": "Tsakhur", "tks": "Takestani", "tkt": "Kathoriya Tharu", "tku": "Upper Necaxa Totonac", "tkv": "Mur Pano", "tkw": "Teanu", "tkx": "Tangko", "tkz": "Takua", "tl": "Tagalog", "tla": "Southwestern Tepehuan", "tlb": "Tobelo", "tlc": "Yecuatla Totonac", "tld": "Talaud", "tlf": "Telefol", "tlg": "Tofanma", "tlh": "Klingon; tlhIngan Hol", "tli": "Tlingit", "tlj": "Talinga-Bwisi", "tlk": "Taloki", "tll": "Tetela", "tlm": "Tolomako", "tln": "Talondo'", "tlo": "Talodi", "tlp": "Filomena Mata-Coahuitlán Totonac", "tlq": "Tai Loi", "tlr": "Talise", "tls": "Tambotalo", "tlt": "Sou Nama; Teluti", "tlu": "Tulehu", "tlv": "Taliabu", "tlx": "Khehek", "tly": "Talysh", "tma": "Tama (Chad)", "tmb": "Katbol; Avava", "tmc": "Tumak", "tmd": "Haruai", "tme": "Tremembé", "tmf": "Toba-Maskoy", "tmg": "Ternateño", "tmh": "Tamashek", "tmi": "Tutuba", "tmj": "Samarokena", "tmk": "Northwestern Tamang", "tml": "Tamnim Citak", "tmm": "Tai Thanh", "tmn": "Taman (Indonesia)", "tmo": "Temoq", "tmq": "Tumleo", "tmr": "Jewish Babylonian Aramaic (ca. 200-1200 CE)", "tms": "Tima", "tmt": "Tasmate", "tmu": "Iau", "tmv": "Tembo (Motembo)", "tmw": "Temuan", "tmy": "Tami", "tmz": "Tamanaku", "tn": "Tswana", "tna": "Tacana", "tnb": "Western Tunebo", "tnc": "Tanimuca-Retuarã", "tnd": "Angosturas Tunebo", "tng": "Tobanga", "tnh": "Maiani", "tni": "Tandia", "tnk": "Kwamera", "tnl": "Lenakel", "tnm": "Tabla", "tnn": "North Tanna", "tno": "Toromono", "tnp": "Whitesands", "tnq": "Taino", "tnr": "Ménik", "tns": "Tenis", "tnt": "Tontemboan", "tnu": "Tay Khang", "tnv": "Tangchangya", "tnw": "Tonsawang", "tnx": "Tanema", "tny": "Tongwe", "tnz": "Ten'edn", "to": "Tonga (Tonga Islands)", "tob": "Toba", "toc": "Coyutla Totonac", "tod": "Toma", "tof": "Gizrra", "tog": "Tonga (Nyasa)", "toh": "Gitonga", "toi": "Tonga (Zambia)", "toj": "Tojolabal", "tok": "Toki Pona", "tol": "Tolowa", "tom": "Tombulu", "too": "Xicotepec De Juárez Totonac", "top": "Papantla Totonac", "toq": "Toposa", "tor": "Togbo-Vara Banda", "tos": "Highland Totonac", "tou": "Tho", "tov": "Upper Taromi", "tow": "Jemez", "tox": "Tobian", "toy": "Topoiyo", "toz": "To", "tpa": "Taupota", "tpc": "Azoyú Me'phaa; Azoyú Tlapanec", "tpe": "Tippera", "tpf": "Tarpia", "tpg": "Kula", "tpi": "Tok Pisin", "tpj": "Tapieté", "tpk": "Tupinikin", "tpl": "Tlacoapa Me'phaa; Tlacoapa Tlapanec", "tpm": "Tampulma", "tpn": "Tupinambá", "tpo": "Tai Pao", "tpp": "Pisaflores Tepehua", "tpq": "Tukpa", "tpr": "Tuparí", "tpt": "Tlachichilco Tepehua", "tpu": "Tampuan", "tpv": "Tanapag", "tpw": "Tupí", "tpx": "Acatepec Me'phaa; Acatepec Tlapanec", "tpy": "Trumai", "tpz": "Tinputz", "tqb": "Tembé", "tql": "Lehali", "tqm": "Turumsa", "tqn": "Tenino", "tqo": "Toaripi", "tqp": "Tomoip", "tqq": "Tunni", "tqr": "Torona", "tqt": "Western Totonac", "tqu": "Touo", "tqw": "Tonkawa", "tr": "Turkish", "tra": "Tirahi", "trb": "Terebu", "trc": "Copala Triqui", "trd": "Turi", "tre": "East Tarangan", "trf": "Trinidadian Creole English", "trg": "Lishán Didán", "trh": "Turaka", "tri": "Trió", "trj": "Toram", "trk": "Turkic languages", "trl": "Traveller Scottish", "trm": "Tregami", "trn": "Trinitario", "tro": "Tarao Naga", "trp": "Kok Borok", "trq": "San Martín Itunyoso Triqui", "trr": "Taushiro", "trs": "Chicahuaxtla Triqui", "trt": "Tunggare", "tru": "Turoyo; Surayt", "trv": "Sediq; Seediq; Taroko", "trw": "Torwali", "trx": "Tringgus-Sembaan Bidayuh", "try": "Turung", "trz": "Torá", "ts": "Tsonga", "tsa": "Tsaangi", "tsb": "Tsamai", "tsc": "Tswa", "tsd": "Tsakonian", "tse": "Tunisian Sign Language", "tsg": "Tausug", "tsh": "Tsuvan", "tsi": "Tsimshian", "tsj": "Tshangla", "tsk": "Tseku", "tsl": "Ts'ün-Lao", "tsm": "Turkish Sign Language; Türk İşaret Dili", "tsp": "Northern Toussian", "tsq": "Thai Sign Language", "tsr": "Akei", "tss": "Taiwan Sign Language", "tst": "Tondi Songway Kiini", "tsu": "Tsou", "tsv": "Tsogo", "tsw": "Tsishingini", "tsx": "Mubami", "tsy": "Tebul Sign Language", "tsz": "Purepecha", "tt": "Tatar", "tta": "Tutelo", "ttb": "Gaa", "ttc": "Tektiteko", "ttd": "Tauade", "tte": "Bwanabwana", "ttf": "Tuotomb", "ttg": "Tutong", "tth": "Upper Ta'oih", "tti": "Tobati", "ttj": "Tooro", "ttk": "Totoro", "ttl": "Totela", "ttm": "Northern Tutchone", "ttn": "Towei", "tto": "Lower Ta'oih", "ttp": "Tombelala", "ttq": "Tawallammat Tamajaq", "ttr": "Tera", "tts": "Northeastern Thai", "ttt": "Muslim Tat", "ttu": "Torau", "ttv": "Titan", "ttw": "Long Wat", "tty": "Sikaritai", "ttz": "Tsum", "tua": "Wiarumus", "tub": "Tübatulabal", "tuc": "Mutu", "tud": "Tuxá", "tue": "Tuyuca", "tuf": "Central Tunebo", "tug": "Tunia", "tuh": "Taulil", "tui": "Tupuri", "tuj": "Tugutil", "tul": "Tula", "tum": "Tumbuka", "tun": "Tunica", "tuo": "Tucano", "tup": "Tupi languages", "tuq": "Tedaga", "tus": "Tuscarora", "tut": "Altaic languages", "tuu": "Tututni", "tuv": "Turkana", "tuw": "Tungus languages", "tux": "Tuxináwa", "tuy": "Tugen", "tuz": "Turka", "tva": "Vaghua", "tvd": "Tsuvadi", "tve": "Te'un", "tvk": "Southeast Ambrym", "tvl": "Tuvalu", "tvm": "Tela-Masbuar", "tvn": "Tavoyan", "tvo": "Tidore", "tvs": "Taveta", "tvt": "Tutsa Naga", "tvu": "Tunen", "tvw": "Sedoa", "tvx": "Taivoan", "tvy": "Timor Pidgin", "tw": "Twi", "twa": "Twana", "twb": "Western Tawbuid", "twc": "Teshenawa", "twd": "Twents", "twe": "Tewa (Indonesia)", "twf": "Northern Tiwa", "twg": "Tereweng", "twh": "Tai Dón", "twl": "Tawara", "twm": "Tawang Monpa", "twn": "Twendi", "two": "Tswapong", "twp": "Ere", "twq": "Tasawaq", "twr": "Southwestern Tarahumara", "twt": "Turiwára", "twu": "Termanu", "tww": "Tuwari", "twx": "Tewe", "twy": "Tawoyan", "txa": "Tombonuo", "txb": "Tokharian B", "txc": "Tsetsaut", "txe": "Totoli", "txg": "Tangut", "txh": "Thracian", "txi": "Ikpeng", "txj": "Tarjumo", "txm": "Tomini", "txn": "West Tarangan", "txo": "Toto", "txq": "Tii", "txr": "Tartessian", "txs": "Tonsea", "txt": "Citak", "txu": "Kayapó", "txx": "Tatana", "txy": "Tanosy Malagasy", "ty": "Tahitian", "tya": "Tauya", "tye": "Kyanga", "tyh": "O'du", "tyi": "Teke-Tsaayi", "tyj": "Tai Do; Tai Yo", "tyl": "Thu Lao", "tyn": "Kombai", "typ": "Thaypan", "tyr": "Tai Daeng", "tys": "Tày Sa Pa", "tyt": "Tày Tac", "tyu": "Kua", "tyv": "Tuvinian", "tyx": "Teke-Tyee", "tyy": "Tiyaa", "tyz": "Tày", "tza": "Tanzanian Sign Language", "tzh": "Tzeltal", "tzj": "Tz'utujil", "tzl": "Talossan", "tzm": "Central Atlas Tamazight", "tzn": "Tugun", "tzo": "Tzotzil", "tzx": "Tabriak", "uam": "Uamué", "uan": "Kuan", "uar": "Tairuma", "uba": "Ubang", "ubi": "Ubi", "ubl": "Buhi'non Bikol", "ubr": "Ubir", "ubu": "Umbu-Ungu", "uby": "Ubykh", "uda": "Uda", "ude": "Udihe", "udg": "Muduga", "udi": "Udi", "udj": "Ujir", "udl": "Wuzlam", "udm": "Udmurt", "udu": "Uduk", "ues": "Kioko", "ufi": "Ufim", "ug": "Uighur; Uyghur", "uga": "Ugaritic", "ugb": "Kuku-Ugbanh", "uge": "Ughele", "ugh": "Kubachi", "ugn": "Ugandan Sign Language", "ugo": "Ugong", "ugy": "Uruguayan Sign Language", "uha": "Uhami", "uhn": "Damal", "uis": "Uisai", "uiv": "Iyive", "uji": "Tanjijili", "uk": "Ukrainian", "uka": "Kaburi", "ukg": "Ukuriguma", "ukh": "Ukhwejo", "uki": "Kui (India)", "ukk": "Muak Sa-aak", "ukl": "Ukrainian Sign Language", "ukp": "Ukpe-Bayobiri", "ukq": "Ukwa", "uks": "Urubú-Kaapor Sign Language; Kaapor Sign Language", "uku": "Ukue", "ukv": "Kuku", "ukw": "Ukwuani-Aboh-Ndoni", "uky": "Kuuk-Yak", "ula": "Fungwa", "ulb": "Ulukwumi", "ulc": "Ulch", "ule": "Lule", "ulf": "Usku; Afra", "uli": "Ulithian", "ulk": "Meriam Mir", "ull": "Ullatan", "ulm": "Ulumanda'", "uln": "Unserdeutsch", "ulu": "Uma' Lung", "ulw": "Ulwa", "uma": "Umatilla", "umb": "Umbundu", "umc": "Marrucinian", "umd": "Umbindhamu", "umg": "Morrobalama; Umbuygamu", "umi": "Ukit", "umm": "Umon", "umn": "Makyan Naga", "umo": "Umotína", "ump": "Umpila", "umr": "Umbugarla", "ums": "Pendau", "umu": "Munsee", "una": "North Watut", "und": "Undetermined", "une": "Uneme", "ung": "Ngarinyin", "uni": "Uni", "unk": "Enawené-Nawé", "unm": "Unami", "unn": "Kurnai", "unr": "Mundari", "unu": "Unubahe", "unx": "Munda", "unz": "Unde Kaili", "uon": "Kulon", "upi": "Umeda", "upv": "Uripiv-Wala-Rano-Atchin", "ur": "Urdu", "ura": "Urarina", "urb": "Urubú-Kaapor; Kaapor", "urc": "Urningangg", "ure": "Uru", "urf": "Uradhi", "urg": "Urigina", "urh": "Urhobo", "uri": "Urim", "urj": "Uralic languages", "urk": "Urak Lawoi'", "url": "Urali", "urm": "Urapmin", "urn": "Uruangnirin", "uro": "Ura (Papua New Guinea)", "urp": "Uru-Pa-In", "urr": "Lehalurup; Löyöp", "urt": "Urat", "uru": "Urumi", "urv": "Uruava", "urw": "Sop", "urx": "Urimo", "ury": "Orya", "urz": "Uru-Eu-Wau-Wau", "usa": "Usarufa", "ush": "Ushojo", "usi": "Usui", "usk": "Usaghade", "usp": "Uspanteco", "uss": "us-Saare", "usu": "Uya", "uta": "Otank", "ute": "Ute-Southern Paiute", "uth": "ut-Hun", "utp": "Amba (Solomon Islands)", "utr": "Etulo", "utu": "Utu", "uum": "Urum", "uur": "Ura (Vanuatu)", "uuu": "U", "uve": "West Uvean; Fagauvea", "uvh": "Uri", "uvl": "Lote", "uwa": "Kuku-Uwanh", "uya": "Doko-Uyanga", "uz": "Uzbek", "uzn": "Northern Uzbek", "uzs": "Southern Uzbek", "vaa": "Vaagri Booli", "vae": "Vale", "vaf": "Vafsi", "vag": "Vagla", "vah": "Varhadi-Nagpuri", "vai": "Vai", "vaj": "Sekele; Northwestern ǃKung; Vasekele", "val": "Vehes", "vam": "Vanimo", "van": "Valman", "vao": "Vao", "vap": "Vaiphei", "var": "Huarijio", "vas": "Vasavi", "vau": "Vanuma", "vav": "Varli", "vay": "Wayu", "vbb": "Southeast Babar", "vbk": "Southwestern Bontok", "ve": "Venda", "vec": "Venetian", "ved": "Veddah", "vel": "Veluws", "vem": "Vemgo-Mabas", "veo": "Ventureño", "vep": "Veps", "ver": "Mom Jango", "vgr": "Vaghri", "vgt": "Vlaamse Gebarentaal; Flemish Sign Language", "vi": "Vietnamese", "vic": "Virgin Islands Creole English", "vid": "Vidunda", "vif": "Vili", "vig": "Viemo", "vil": "Vilela", "vin": "Vinza", "vis": "Vishavan", "vit": "Viti", "viv": "Iduna", "vka": "Kariyarra", "vkj": "Kujarge", "vkk": "Kaur", "vkl": "Kulisusu", "vkm": "Kamakan", "vkn": "Koro Nulu", "vko": "Kodeoha", "vkp": "Korlai Creole Portuguese", "vkt": "Tenggarong Kutai Malay", "vku": "Kurrama", "vkz": "Koro Zuba", "vlp": "Valpei", "vls": "Vlaams", "vma": "Martuyhunira", "vmb": "Barbaram", "vmc": "Juxtlahuaca Mixtec", "vmd": "Mudu Koraga", "vme": "East Masela", "vmf": "Mainfränkisch", "vmg": "Lungalunga", "vmh": "Maraghei", "vmi": "Miwa", "vmj": "Ixtayutla Mixtec", "vmk": "Makhuwa-Shirima", "vml": "Malgana", "vmm": "Mitlatongo Mixtec", "vmp": "Soyaltepec Mazatec", "vmq": "Soyaltepec Mixtec", "vmr": "Marenje", "vms": "Moksela", "vmu": "Muluridyi", "vmv": "Valley Maidu", "vmw": "Makhuwa", "vmx": "Tamazola Mixtec", "vmy": "Ayautla Mazatec", "vmz": "Mazatlán Mazatec", "vnk": "Vano; Lovono", "vnm": "Vinmavis; Neve'ei", "vnp": "Vunapu", "vo": "Volapük", "vor": "Voro", "vot": "Votic", "vra": "Vera'a", "vro": "Võro", "vrs": "Varisi", "vrt": "Burmbar; Banam Bay", "vsi": "Moldova Sign Language", "vsl": "Venezuelan Sign Language", "vsv": "Valencian Sign Language; Llengua de signes valenciana", "vto": "Vitou", "vum": "Vumbu", "vun": "Vunjo", "vut": "Vute", "vwa": "Awa (China)", "wa": "Walloon", "waa": "Walla Walla", "wab": "Wab", "wac": "Wasco-Wishram", "wad": "Wamesa; Wondama", "wae": "Walser", "waf": "Wakoná", "wag": "Wa'ema", "wah": "Watubela", "wai": "Wares", "waj": "Waffa", "wak": "Wakashan languages", "wal": "Wolaytta; Wolaitta", "wam": "Wampanoag", "wan": "Wan", "wao": "Wappo", "wap": "Wapishana", "waq": "Wagiman", "war": "Waray (Philippines)", "was": "Washo", "wat": "Kaninuwa", "wau": "Waurá", "wav": "Waka", "waw": "Waiwai", "wax": "Watam; Marangis", "way": "Wayana", "waz": "Wampur", "wba": "Warao", "wbb": "Wabo", "wbe": "Waritai", "wbf": "Wara", "wbh": "Wanda", "wbi": "Vwanji", "wbj": "Alagwa", "wbk": "Waigali", "wbl": "Wakhi", "wbm": "Wa", "wbp": "Warlpiri", "wbq": "Waddar", "wbr": "Wagdi", "wbs": "West Bengal Sign Language", "wbt": "Warnman", "wbv": "Wajarri", "wbw": "Woi", "wca": "Yanomámi", "wci": "Waci Gbe", "wdd": "Wandji", "wdg": "Wadaginam", "wdj": "Wadjiginy", "wdk": "Wadikali", "wdt": "Wendat", "wdu": "Wadjigu", "wdy": "Wadjabangayi", "wea": "Wewaw", "wec": "Wè Western", "wed": "Wedau", "weg": "Wergaia", "weh": "Weh", "wei": "Kiunum", "wem": "Weme Gbe", "wen": "Sorbian languages", "weo": "Wemale", "wep": "Westphalien", "wer": "Weri", "wes": "Cameroon Pidgin", "wet": "Perai", "weu": "Rawngtu Chin", "wew": "Wejewa", "wfg": "Yafi; Zorop", "wga": "Wagaya", "wgb": "Wagawaga", "wgg": "Wangkangurru; Wangganguru", "wgi": "Wahgi", "wgo": "Waigeo", "wgu": "Wirangu", "wgy": "Warrgamay", "wha": "Sou Upaa; Manusela", "whg": "North Wahgi", "whk": "Wahau Kenyah", "whu": "Wahau Kayan", "wib": "Southern Toussian", "wic": "Wichita", "wie": "Wik-Epa", "wif": "Wik-Keyangan", "wig": "Wik Ngathan", "wih": "Wik-Me'anha", "wii": "Minidien", "wij": "Wik-Iiyanh", "wik": "Wikalkan", "wil": "Wilawila", "wim": "Wik-Mungkan", "win": "Ho-Chunk", "wir": "Wiraféd", "wiu": "Wiru", "wiv": "Vitu", "wiy": "Wiyot", "wja": "Waja", "wji": "Warji", "wka": "Kw'adza", "wkb": "Kumbaran", "wkd": "Wakde; Mo", "wkl": "Kalanadi", "wkr": "Keerray-Woorroong", "wku": "Kunduvadi", "wkw": "Wakawaka", "wky": "Wangkayutyuru", "wla": "Walio", "wlc": "Mwali Comorian", "wle": "Wolane", "wlg": "Kunbarlang", "wlh": "Welaun", "wli": "Waioli", "wlk": "Wailaki", "wll": "Wali (Sudan)", "wlm": "Middle Welsh", "wlo": "Wolio", "wlr": "Wailapa", "wls": "Wallisian", "wlu": "Wuliwuli", "wlv": "Wichí Lhamtés Vejoz", "wlw": "Walak", "wlx": "Wali (Ghana)", "wly": "Waling", "wma": "Mawa (Nigeria)", "wmb": "Wambaya", "wmc": "Wamas", "wmd": "Mamaindé", "wme": "Wambule", "wmg": "Western Minyag", "wmh": "Waima'a", "wmi": "Wamin", "wmm": "Maiwa (Indonesia)", "wmn": "Waamwang", "wmo": "Wom (Papua New Guinea)", "wms": "Wambon", "wmt": "Walmajarri", "wmw": "Mwani", "wmx": "Womo", "wnb": "Wanambre", "wnc": "Wantoat", "wnd": "Wandarang", "wne": "Waneci", "wng": "Wanggom", "wni": "Ndzwani Comorian", "wnk": "Wanukaka", "wnm": "Wanggamala", "wnn": "Wunumara", "wno": "Wano", "wnp": "Wanap", "wnu": "Usan", "wnw": "Wintu", "wny": "Wanyi; Waanyi", "wo": "Wolof", "woa": "Kuwema; Tyaraity", "wob": "Wè Northern", "woc": "Wogeo", "wod": "Wolani", "woe": "Woleaian", "wof": "Gambian Wolof", "wog": "Wogamusin", "woi": "Kamang", "wok": "Longto", "wom": "Wom (Nigeria)", "won": "Wongo", "woo": "Manombai", "wor": "Woria", "wos": "Hanga Hundi", "wow": "Wawonii", "woy": "Weyto", "wpc": "Maco", "wrb": "Waluwarra; Warluwara", "wrg": "Warungu; Gudjal", "wrh": "Wiradjuri", "wri": "Wariyangga", "wrk": "Garrwa", "wrl": "Warlmanpa", "wrm": "Warumungu", "wrn": "Warnang", "wro": "Worrorra", "wrp": "Waropen", "wrr": "Wardaman", "wrs": "Waris", "wru": "Waru", "wrv": "Waruna", "wrw": "Gugu Warra", "wrx": "Wae Rana", "wry": "Merwari", "wrz": "Waray (Australia)", "wsa": "Warembori", "wsg": "Adilabad Gondi", "wsi": "Wusi", "wsk": "Waskia", "wsr": "Owenia", "wss": "Wasa", "wsu": "Wasu", "wsv": "Wotapuri-Katarqalai", "wtf": "Watiwa", "wth": "Wathawurrung", "wti": "Berta", "wtk": "Watakataui", "wtm": "Mewati", "wtw": "Wotu", "wua": "Wikngenchera", "wub": "Wunambal", "wud": "Wudu", "wuh": "Wutunhua", "wul": "Silimo", "wum": "Wumbvu", "wun": "Bungu", "wur": "Wurrugu", "wut": "Wutung", "wuu": "Wu Chinese", "wuv": "Wuvulu-Aua", "wux": "Wulna", "wuy": "Wauyai", "wwa": "Waama", "wwb": "Wakabunga", "wwo": "Wetamut; Dorig", "wwr": "Warrwa", "www": "Wawa", "wxa": "Waxianghua", "wxw": "Wardandi", "wyb": "Wangaaybuwan-Ngiyambaa", "wyi": "Woiwurrung", "wym": "Wymysorys", "wyn": "Wyandot", "wyr": "Wayoró", "wyy": "Western Fijian", "xaa": "Andalusian Arabic", "xab": "Sambe", "xac": "Kachari", "xad": "Adai", "xae": "Aequian", "xag": "Aghwan", "xai": "Kaimbé", "xaj": "Ararandewára", "xak": "Máku", "xal": "Kalmyk; Oirat", "xam": "ǀXam", "xan": "Xamtanga", "xao": "Khao", "xap": "Apalachee", "xaq": "Aquitanian", "xar": "Karami", "xas": "Kamas", "xat": "Katawixi", "xau": "Kauwera", "xav": "Xavánte", "xaw": "Kawaiisu", "xay": "Kayan Mahakam", "xbb": "Lower Burdekin", "xbc": "Bactrian", "xbd": "Bindal", "xbe": "Bigambal", "xbg": "Bunganditj", "xbi": "Kombio", "xbj": "Birrpayi", "xbm": "Middle Breton", "xbn": "Kenaboi", "xbo": "Bolgarian", "xbp": "Bibbulman", "xbr": "Kambera", "xbw": "Kambiwá", "xby": "Batjala; Batyala", "xcb": "Cumbric", "xcc": "Camunic", "xce": "Celtiberian", "xcg": "Cisalpine Gaulish", "xch": "Chemakum; Chimakum", "xcl": "Classical Armenian", "xcm": "Comecrudo", "xcn": "Cotoname", "xco": "Chorasmian", "xcr": "Carian", "xct": "Classical Tibetan", "xcu": "Curonian", "xcv": "Chuvantsy", "xcw": "Coahuilteco", "xcy": "Cayuse", "xda": "Darkinyung", "xdc": "Dacian", "xdk": "Dharuk", "xdm": "Edomite", "xdo": "Kwandu", "xdq": "Kaitag", "xdy": "Malayic Dayak", "xeb": "Eblan", "xed": "Hdi", "xeg": "ǁXegwi", "xel": "Kelo", "xem": "Kembayan", "xep": "Epi-Olmec", "xer": "Xerénte", "xes": "Kesawai", "xet": "Xetá", "xeu": "Keoru-Ahia", "xfa": "Faliscan", "xga": "Galatian", "xgb": "Gbin", "xgd": "Gudang", "xgf": "Gabrielino-Fernandeño", "xgg": "Goreng", "xgi": "Garingbal", "xgl": "Galindan", "xgm": "Dharumbal; Guwinmal", "xgn": "Mongolian languages", "xgr": "Garza", "xgu": "Unggumi", "xgw": "Guwa", "xh": "Xhosa", "xha": "Harami", "xhc": "Hunnic", "xhd": "Hadrami", "xhe": "Khetrani", "xhm": "Middle Khmer (1400 to 1850 CE)", "xhr": "Hernican", "xht": "Hattic", "xhu": "Hurrian", "xhv": "Khua", "xib": "Iberian", "xii": "Xiri", "xil": "Illyrian", "xin": "Xinca", "xir": "Xiriâna", "xis": "Kisan", "xiv": "Indus Valley Language", "xiy": "Xipaya", "xjb": "Minjungbal", "xjt": "Jaitmatang", "xka": "Kalkoti", "xkb": "Northern Nago", "xkc": "Kho'ini", "xkd": "Mendalam Kayan", "xke": "Kereho", "xkf": "Khengkha", "xkg": "Kagoro", "xki": "Kenyan Sign Language", "xkj": "Kajali", "xkk": "Kachok; Kaco'", "xkl": "Mainstream Kenyah", "xkn": "Kayan River Kayan", "xko": "Kiorr", "xkp": "Kabatei", "xkq": "Koroni", "xkr": "Xakriabá", "xks": "Kumbewaha", "xkt": "Kantosi", "xku": "Kaamba", "xkv": "Kgalagadi", "xkw": "Kembra", "xkx": "Karore", "xky": "Uma' Lasan", "xkz": "Kurtokha", "xla": "Kamula", "xlb": "Loup B", "xlc": "Lycian", "xld": "Lydian", "xle": "Lemnian", "xlg": "Ligurian (Ancient)", "xli": "Liburnian", "xln": "Alanic", "xlo": "Loup A", "xlp": "Lepontic", "xls": "Lusitanian", "xlu": "Cuneiform Luwian", "xly": "Elymian", "xma": "Mushungulu", "xmb": "Mbonga", "xmc": "Makhuwa-Marrevone", "xmd": "Mbudum", "xme": "Median", "xmf": "Mingrelian", "xmg": "Mengaka", "xmh": "Kugu-Muminh", "xmj": "Majera", "xmk": "Ancient Macedonian", "xml": "Malaysian Sign Language", "xmm": "Manado Malay", "xmn": "Manichaean Middle Persian", "xmo": "Morerebi", "xmp": "Kuku-Mu'inh", "xmq": "Kuku-Mangk", "xmr": "Meroitic", "xms": "Moroccan Sign Language", "xmt": "Matbat", "xmu": "Kamu", "xmv": "Antankarana Malagasy; Tankarana Malagasy", "xmw": "Tsimihety Malagasy", "xmx": "Salawati; Maden", "xmy": "Mayaguduna", "xmz": "Mori Bawah", "xna": "Ancient North Arabian", "xnb": "Kanakanabu", "xnd": "Na-Dene languages", "xng": "Middle Mongolian", "xnh": "Kuanhua", "xni": "Ngarigu", "xnj": "Ngoni (Tanzania)", "xnk": "Nganakarti", "xnm": "Ngumbarl", "xnn": "Northern Kankanay", "xno": "Anglo-Norman", "xnq": "Ngoni (Mozambique)", "xnr": "Kangri", "xns": "Kanashi", "xnt": "Narragansett", "xnu": "Nukunul", "xny": "Nyiyaparli", "xnz": "Kenzi; Mattoki", "xoc": "O'chi'chi'", "xod": "Kokoda", "xog": "Soga", "xoi": "Kominimung", "xok": "Xokleng", "xom": "Komo (Sudan)", "xon": "Konkomba", "xoo": "Xukurú", "xop": "Kopar", "xor": "Korubo", "xow": "Kowaki", "xpa": "Pirriya", "xpb": "Northeastern Tasmanian; Pyemmairrener", "xpc": "Pecheneg", "xpd": "Oyster Bay Tasmanian", "xpe": "Liberia Kpelle", "xpf": "Southeast Tasmanian; Nuenonne", "xpg": "Phrygian", "xph": "North Midlands Tasmanian; Tyerrenoterpanner", "xpi": "Pictish", "xpj": "Mpalitjanh", "xpk": "Kulina Pano", "xpl": "Port Sorell Tasmanian", "xpm": "Pumpokol", "xpn": "Kapinawá", "xpo": "Pochutec", "xpp": "Puyo-Paekche", "xpq": "Mohegan-Pequot", "xpr": "Parthian", "xps": "Pisidian", "xpt": "Punthamara", "xpu": "Punic", "xpv": "Northern Tasmanian; Tommeginne", "xpw": "Northwestern Tasmanian; Peerapper", "xpx": "Southwestern Tasmanian; Toogee", "xpy": "Puyo", "xpz": "Bruny Island Tasmanian", "xqa": "Karakhanid", "xqt": "Qatabanian", "xra": "Krahô", "xrb": "Eastern Karaboro", "xrd": "Gundungurra", "xre": "Kreye", "xrg": "Minang", "xri": "Krikati-Timbira", "xrm": "Armazic", "xrn": "Arin", "xrr": "Raetic", "xrt": "Aranama-Tamique", "xru": "Marriammu", "xrw": "Karawa", "xsa": "Sabaean", "xsb": "Sambal", "xsc": "Scythian", "xsd": "Sidetic", "xse": "Sempan", "xsh": "Shamang", "xsi": "Sio", "xsj": "Subi", "xsl": "South Slavey", "xsm": "Kasem", "xsn": "Sanga (Nigeria)", "xso": "Solano", "xsp": "Silopi", "xsq": "Makhuwa-Saka", "xsr": "Sherpa", "xss": "Assan", "xsu": "Sanumá", "xsv": "Sudovian", "xsy": "Saisiyat", "xta": "Alcozauca Mixtec", "xtb": "Chazumba Mixtec", "xtc": "Katcha-Kadugli-Miri", "xtd": "Diuxi-Tilantongo Mixtec", "xte": "Ketengban", "xtg": "Transalpine Gaulish", "xth": "Yitha Yitha", "xti": "Sinicahua Mixtec", "xtj": "San Juan Teita Mixtec", "xtl": "Tijaltepec Mixtec", "xtm": "Magdalena Peñasco Mixtec", "xtn": "Northern Tlaxiaco Mixtec", "xto": "Tokharian A", "xtp": "San Miguel Piedras Mixtec", "xtq": "Tumshuqese", "xtr": "Early Tripuri", "xts": "Sindihui Mixtec", "xtt": "Tacahua Mixtec", "xtu": "Cuyamecalco Mixtec", "xtv": "Thawa", "xtw": "Tawandê", "xty": "Yoloxochitl Mixtec", "xua": "Alu Kurumba", "xub": "Betta Kurumba", "xud": "Umiida", "xug": "Kunigami", "xuj": "Jennu Kurumba", "xul": "Ngunawal; Nunukul", "xum": "Umbrian", "xun": "Unggaranggu", "xuo": "Kuo", "xup": "Upper Umpqua", "xur": "Urartian", "xut": "Kuthant", "xuu": "Kxoe; Khwedam", "xve": "Venetic", "xvi": "Kamviri", "xvn": "Vandalic", "xvo": "Volscian", "xvs": "Vestinian", "xwa": "Kwaza", "xwc": "Woccon", "xwd": "Wadi Wadi", "xwe": "Xwela Gbe", "xwg": "Kwegu", "xwj": "Wajuk", "xwk": "Wangkumara", "xwl": "Western Xwla Gbe", "xwo": "Written Oirat", "xwr": "Kwerba Mamberamo", "xwt": "Wotjobaluk", "xww": "Wemba Wemba", "xxb": "Boro (Ghana)", "xxk": "Ke'o", "xxm": "Minkin", "xxr": "Koropó", "xxt": "Tambora", "xya": "Yaygir", "xyb": "Yandjibara", "xyj": "Mayi-Yapi", "xyk": "Mayi-Kulan", "xyl": "Yalakalore", "xyt": "Mayi-Thakurti", "xyy": "Yorta Yorta", "xzh": "Zhang-Zhung", "xzm": "Zemgalian", "xzp": "Ancient Zapotec", "yaa": "Yaminahua", "yab": "Yuhup", "yac": "Pass Valley Yali", "yad": "Yagua", "yae": "Pumé", "yaf": "Yaka (Democratic Republic of Congo)", "yag": "Yámana", "yah": "Yazgulyam", "yai": "Yagnobi", "yaj": "Banda-Yangere", "yak": "Yakama", "yal": "Yalunka", "yam": "Yamba", "yan": "Mayangna", "yao": "Yao", "yap": "Yapese", "yaq": "Yaqui", "yar": "Yabarana", "yas": "Nugunu (Cameroon)", "yat": "Yambeta", "yau": "Yuwana", "yav": "Yangben", "yaw": "Yawalapití", "yax": "Yauma", "yay": "Agwagwune", "yaz": "Lokaa", "yba": "Yala", "ybb": "Yemba", "ybe": "West Yugur", "ybh": "Yakha", "ybi": "Yamphu", "ybj": "Hasha", "ybk": "Bokha", "ybl": "Yukuben", "ybm": "Yaben", "ybn": "Yabaâna", "ybo": "Yabong", "ybx": "Yawiyo", "yby": "Yaweyuha", "ych": "Chesu", "ycl": "Lolopo", "ycn": "Yucuna", "ycp": "Chepya", "yda": "Yanda", "ydd": "Eastern Yiddish", "yde": "Yangum Dey", "ydg": "Yidgha", "ydk": "Yoidik", "yea": "Ravula", "yec": "Yeniche", "yee": "Yimas", "yei": "Yeni", "yej": "Yevanic", "yel": "Yela", "yer": "Tarok", "yes": "Nyankpa", "yet": "Yetfa", "yeu": "Yerukula", "yev": "Yapunda", "yey": "Yeyi", "yga": "Malyangapa", "ygi": "Yiningayi", "ygl": "Yangum Gel", "ygm": "Yagomi", "ygp": "Gepo", "ygr": "Yagaria", "ygs": "Yolŋu Sign Language", "ygu": "Yugul", "ygw": "Yagwoia", "yha": "Baha Buyang", "yhd": "Judeo-Iraqi Arabic", "yhl": "Hlepho Phowa", "yhs": "Yan-nhaŋu Sign Language", "yi": "Yiddish", "yia": "Yinggarda", "yif": "Ache", "yig": "Wusa Nasu", "yih": "Western Yiddish", "yii": "Yidiny", "yij": "Yindjibarndi", "yik": "Dongshanba Lalo", "yil": "Yindjilandji", "yim": "Yimchungru Naga", "yin": "Riang Lai; Yinchia", "yip": "Pholo", "yiq": "Miqie", "yir": "North Awyu", "yis": "Yis", "yit": "Eastern Lalu", "yiu": "Awu", "yiv": "Northern Nisu", "yix": "Axi Yi", "yiz": "Azhe", "yka": "Yakan", "ykg": "Northern Yukaghir", "yki": "Yoke", "ykk": "Yakaikeke", "ykl": "Khlula", "ykm": "Kap", "ykn": "Kua-nsi", "yko": "Yasa", "ykr": "Yekora", "ykt": "Kathu", "yku": "Kuamasi", "yky": "Yakoma", "yla": "Yaul", "ylb": "Yaleba", "yle": "Yele", "ylg": "Yelogu", "yli": "Angguruk Yali", "yll": "Yil", "ylm": "Limi", "yln": "Langnian Buyang", "ylo": "Naluo Yi", "ylr": "Yalarnnga", "ylu": "Aribwaung", "yly": "Nyâlayu; Nyelâyu", "ymb": "Yambes", "ymc": "Southern Muji", "ymd": "Muda", "yme": "Yameo", "ymg": "Yamongeri", "ymh": "Mili", "ymi": "Moji", "ymk": "Makwe", "yml": "Iamalele", "ymm": "Maay", "ymn": "Yamna; Sunum", "ymo": "Yangum Mon", "ymp": "Yamap", "ymq": "Qila Muji", "ymr": "Malasar", "yms": "Mysian", "ymx": "Northern Muji", "ymz": "Muzi", "yna": "Aluo", "ynd": "Yandruwandha", "yne": "Lang'e", "yng": "Yango", "ynk": "Naukan Yupik", "ynl": "Yangulam", "ynn": "Yana", "yno": "Yong", "ynq": "Yendang", "yns": "Yansi", "ynu": "Yahuna", "yo": "Yoruba", "yob": "Yoba", "yog": "Yogad", "yoi": "Yonaguni", "yok": "Yokuts", "yol": "Yola", "yom": "Yombe", "yon": "Yongkom", "yot": "Yotti", "yox": "Yoron", "yoy": "Yoy", "ypa": "Phala", "ypb": "Labo Phowa", "ypg": "Phola", "yph": "Phupha", "ypk": "Yupik languages", "ypm": "Phuma", "ypn": "Ani Phowa", "ypo": "Alo Phola", "ypp": "Phupa", "ypz": "Phuza", "yra": "Yerakai", "yrb": "Yareba", "yre": "Yaouré", "yrk": "Nenets", "yrl": "Nhengatu", "yrm": "Yirrk-Mel", "yrn": "Yerong", "yro": "Yaroamë", "yrs": "Yarsun", "yrw": "Yarawata", "yry": "Yarluyandi", "ysc": "Yassic", "ysd": "Samatao", "ysg": "Sonaga", "ysl": "Yugoslavian Sign Language", "ysm": "Myanmar Sign Language", "ysn": "Sani", "yso": "Nisi (China)", "ysp": "Southern Lolopo", "ysr": "Sirenik Yupik", "yss": "Yessan-Mayo", "ysy": "Sanie", "yta": "Talu", "ytl": "Tanglang", "ytp": "Thopho", "ytw": "Yout Wam", "yty": "Yatay", "yua": "Yucateco; Yucatec Maya", "yub": "Yugambal", "yuc": "Yuchi", "yud": "Judeo-Tripolitanian Arabic", "yue": "Yue Chinese; Cantonese", "yuf": "Havasupai-Walapai-Yavapai", "yug": "Yug", "yui": "Yurutí", "yuj": "Karkar-Yuri", "yuk": "Yuki", "yul": "Yulu", "yum": "Quechan", "yun": "Bena (Nigeria)", "yup": "Yukpa", "yuq": "Yuqui", "yur": "Yurok", "yut": "Yopno", "yuw": "Yau (Morobe Province)", "yux": "Southern Yukaghir", "yuy": "East Yugur", "yuz": "Yuracare", "yva": "Yawa", "yvt": "Yavitero", "ywa": "Kalou", "ywg": "Yinhawangka", "ywl": "Western Lalu", "ywn": "Yawanawa", "ywq": "Wuding-Luquan Yi", "ywr": "Yawuru", "ywt": "Xishanba Lalo; Central Lalo", "ywu": "Wumeng Nasu", "yww": "Yawarawarga", "yxa": "Mayawali", "yxg": "Yagara", "yxl": "Yardliyawarra", "yxm": "Yinwum", "yxu": "Yuyu", "yxy": "Yabula Yabula", "yyr": "Yir Yoront", "yyu": "Yau (Sandaun Province)", "yyz": "Ayizi", "yzg": "E'ma Buyang", "yzk": "Zokhuo", "za": "Zhuang; Chuang", "zaa": "Sierra de Juárez Zapotec", "zab": "Western Tlacolula Valley Zapotec; San Juan Guelavía Zapotec", "zac": "Ocotlán Zapotec", "zad": "Cajonos Zapotec", "zae": "Yareni Zapotec", "zaf": "Ayoquesco Zapotec", "zag": "Zaghawa", "zah": "Zangwal", "zai": "Isthmus Zapotec", "zaj": "Zaramo", "zak": "Zanaki", "zal": "Zauzou", "zam": "Miahuatlán Zapotec", "zao": "Ozolotepec Zapotec", "zap": "Zapotec", "zaq": "Aloápam Zapotec", "zar": "Rincón Zapotec", "zas": "Santo Domingo Albarradas Zapotec", "zat": "Tabaa Zapotec", "zau": "Zangskari", "zav": "Yatzachi Zapotec", "zaw": "Mitla Zapotec", "zax": "Xadani Zapotec", "zay": "Zayse-Zergulla; Zaysete", "zaz": "Zari", "zba": "Balaibalan", "zbc": "Central Berawan", "zbe": "East Berawan", "zbl": "Blissymbols; Bliss; Blissymbolics", "zbt": "Batui", "zbu": "Bu (Bauchi State)", "zbw": "West Berawan", "zca": "Coatecas Altas Zapotec", "zcd": "Las Delicias Zapotec", "zch": "Central Hongshuihe Zhuang", "zdj": "Ngazidja Comorian", "zea": "Zeeuws", "zeg": "Zenag", "zeh": "Eastern Hongshuihe Zhuang", "zen": "Zenaga", "zga": "Kinga", "zgb": "Guibei Zhuang", "zgh": "Standard Moroccan Tamazight", "zgm": "Minz Zhuang", "zgn": "Guibian Zhuang", "zgr": "Magori", "zh": "Chinese", "zhb": "Zhaba", "zhd": "Dai Zhuang", "zhi": "Zhire", "zhn": "Nong Zhuang", "zhw": "Zhoa", "zhx": "Chinese (family)", "zia": "Zia", "zib": "Zimbabwe Sign Language", "zik": "Zimakani", "zil": "Zialo", "zim": "Mesme", "zin": "Zinza", "ziw": "Zigula", "ziz": "Zizilivakan", "zka": "Kaimbulawa", "zkb": "Koibal", "zkd": "Kadu", "zkg": "Koguryo", "zkh": "Khorezmian", "zkk": "Karankawa", "zkn": "Kanan", "zko": "Kott", "zkp": "São Paulo Kaingáng", "zkr": "Zakhring", "zkt": "Kitan", "zku": "Kaurna", "zkv": "Krevinian", "zkz": "Khazar", "zla": "Zula", "zle": "East Slavic languages", "zlj": "Liujiang Zhuang", "zlm": "Malay (individual language)", "zln": "Lianshan Zhuang", "zlq": "Liuqian Zhuang", "zls": "South Slavic languages", "zlw": "West Slavic languages", "zma": "Manda (Australia)", "zmb": "Zimba", "zmc": "Margany", "zmd": "Maridan", "zme": "Mangerr", "zmf": "Mfinu", "zmg": "Marti Ke", "zmh": "Makolkol", "zmi": "Negeri Sembilan Malay", "zmj": "Maridjabin", "zmk": "Mandandanyi", "zml": "Matngala", "zmm": "Marimanindji; Marramaninyshi", "zmn": "Mbangwe", "zmo": "Molo", "zmp": "Mpuono", "zmq": "Mituku", "zmr": "Maranunggu", "zms": "Mbesa", "zmt": "Maringarr", "zmu": "Muruwari", "zmv": "Mbariman-Gudhinma", "zmw": "Mbo (Democratic Republic of Congo)", "zmx": "Bomitaba", "zmy": "Mariyedi", "zmz": "Mbandja", "zna": "Zan Gula", "znd": "Zande languages", "zne": "Zande (individual language)", "zng": "Mang", "znk": "Manangkari", "zns": "Mangas", "zoc": "Copainalá Zoque", "zoh": "Chimalapa Zoque", "zom": "Zou", "zoo": "Asunción Mixtepec Zapotec", "zoq": "Tabasco Zoque", "zor": "Rayón Zoque", "zos": "Francisco León Zoque", "zpa": "Lachiguiri Zapotec", "zpb": "Yautepec Zapotec", "zpc": "Choapan Zapotec", "zpd": "Southeastern Ixtlán Zapotec", "zpe": "Petapa Zapotec", "zpf": "San Pedro Quiatoni Zapotec", "zpg": "Guevea De Humboldt Zapotec", "zph": "Totomachapan Zapotec", "zpi": "Santa María Quiegolani Zapotec", "zpj": "Quiavicuzas Zapotec", "zpk": "Tlacolulita Zapotec", "zpl": "Lachixío Zapotec", "zpm": "Mixtepec Zapotec", "zpn": "Santa Inés Yatzechi Zapotec", "zpo": "Amatlán Zapotec", "zpp": "El Alto Zapotec", "zpq": "Zoogocho Zapotec", "zpr": "Santiago Xanica Zapotec", "zps": "Coatlán Zapotec", "zpt": "San Vicente Coatlán Zapotec", "zpu": "Yalálag Zapotec", "zpv": "Chichicapan Zapotec", "zpw": "Zaniza Zapotec", "zpx": "San Baltazar Loxicha Zapotec", "zpy": "Mazaltepec Zapotec", "zpz": "Texmelucan Zapotec", "zqe": "Qiubei Zhuang", "zra": "Kara (Korea)", "zrg": "Mirgan", "zrn": "Zerenkel", "zro": "Záparo", "zrp": "Zarphatic", "zrs": "Mairasi", "zsa": "Sarasira", "zsk": "Kaskean", "zsl": "Zambian Sign Language", "zsm": "Standard Malay", "zsr": "Southern Rincon Zapotec", "zsu": "Sukurum", "zte": "Elotepec Zapotec", "ztg": "Xanaguía Zapotec", "ztl": "Lapaguía-Guivini Zapotec", "ztm": "San Agustín Mixtepec Zapotec", "ztn": "Santa Catarina Albarradas Zapotec", "ztp": "Loxicha Zapotec", "ztq": "Quioquitani-Quierí Zapotec", "zts": "Tilquiapan Zapotec", "ztt": "Tejalapan Zapotec", "ztu": "Güilá Zapotec", "ztx": "Zaachila Zapotec", "zty": "Yatee Zapotec", "zu": "Zulu", "zua": "Zeem", "zuh": "Tokano", "zum": "Kumzari", "zun": "Zuni", "zuy": "Zumaya", "zwa": "Zay", "zyb": "Yongbei Zhuang", "zyg": "Yang Zhuang", "zyj": "Youjiang Zhuang", "zyn": "Yongnan Zhuang", "zyp": "Zyphe Chin", "zza": "Zaza; Dimili; Dimli (macrolanguage); Kirdki; Kirmanjki (macrolanguage); Zazaki", "zzj": "Zuojiang Zhuang" }
0
hf_public_repos/datasets/src/datasets/utils
hf_public_repos/datasets/src/datasets/utils/resources/multilingualities.json
{ "monolingual": "contains a single language", "multilingual": "contains multiple languages", "translation": "contains translated or aligned text", "other": "other type of language distribution" }
0
hf_public_repos/datasets/src/datasets/utils
hf_public_repos/datasets/src/datasets/utils/resources/readme_structure.yaml
name: "" # Filename comes here allow_empty: false allow_empty_text: true subsections: - name: "Dataset Card for X" # First-level markdown heading allow_empty: false allow_empty_text: true subsections: - name: "Table of Contents" allow_empty: false allow_empty_text: false subsections: null # meaning it should not be checked. - name: "Dataset Description" allow_empty: false allow_empty_text: false subsections: - name: "Dataset Summary" allow_empty: false allow_empty_text: false subsections: null - name: "Supported Tasks and Leaderboards" allow_empty: true allow_empty_text: true subsections: null - name: Languages allow_empty: true allow_empty_text: true subsections: null - name: "Dataset Structure" allow_empty: false allow_empty_text: true subsections: - name: "Data Instances" allow_empty: false allow_empty_text: true subsections: null - name: "Data Fields" allow_empty: false allow_empty_text: true subsections: null - name: "Data Splits" allow_empty: false allow_empty_text: true subsections: null - name: "Dataset Creation" allow_empty: false allow_empty_text: true subsections: - name: "Curation Rationale" allow_empty: true allow_empty_text: true subsections: null - name: "Source Data" allow_empty: false allow_empty_text: true subsections: - name: "Initial Data Collection and Normalization" allow_empty: true allow_empty_text: true subsections: null - name: "Who are the source language producers?" allow_empty: true allow_empty_text: true subsections: null - name: "Annotations" allow_empty: false allow_empty_text: true subsections: - name: "Annotation process" allow_empty: true allow_empty_text: true subsections: null - name: "Who are the annotators?" allow_empty: true allow_empty_text: true subsections: null - name: "Personal and Sensitive Information" allow_empty: true allow_empty_text: true subsections: null - name: "Considerations for Using the Data" allow_empty: true allow_empty_text: true subsections: - name: "Social Impact of Dataset" allow_empty: true allow_empty_text: true subsections: null - name: "Discussion of Biases" allow_empty: true allow_empty_text: true subsections: null - name: "Other Known Limitations" allow_empty: true allow_empty_text: true subsections: null - name: "Additional Information" allow_empty: true allow_empty_text: true subsections: - name: "Dataset Curators" allow_empty: true allow_empty_text: true subsections: null - name: "Licensing Information" allow_empty: true allow_empty_text: true subsections: null - name: "Citation Information" allow_empty: false allow_empty_text: true subsections: null - name: "Contributions" allow_empty: false allow_empty_text: false subsections: null
0
hf_public_repos/datasets/src/datasets/utils
hf_public_repos/datasets/src/datasets/utils/resources/size_categories.json
[ "unknown", "n<1K", "1K<n<10K", "10K<n<100K", "100K<n<1M", "1M<n<10M", "10M<n<100M", "100M<n<1B", "1B<n<10B", "10B<n<100B", "100B<n<1T", "n>1T" ]
0
hf_public_repos/datasets
hf_public_repos/datasets/templates/README.md
--- TODO: Add YAML tags here. Copy-paste the tags obtained with the online tagging app: https://huggingface.co/spaces/huggingface/datasets-tagging --- # Dataset Card for [Dataset Name] ## Table of Contents - [Table of Contents](#table-of-contents) - [Dataset Description](#dataset-description) - [Dataset Summary](#dataset-summary) - [Supported Tasks and Leaderboards](#supported-tasks-and-leaderboards) - [Languages](#languages) - [Dataset Structure](#dataset-structure) - [Data Instances](#data-instances) - [Data Fields](#data-fields) - [Data Splits](#data-splits) - [Dataset Creation](#dataset-creation) - [Curation Rationale](#curation-rationale) - [Source Data](#source-data) - [Annotations](#annotations) - [Personal and Sensitive Information](#personal-and-sensitive-information) - [Considerations for Using the Data](#considerations-for-using-the-data) - [Social Impact of Dataset](#social-impact-of-dataset) - [Discussion of Biases](#discussion-of-biases) - [Other Known Limitations](#other-known-limitations) - [Additional Information](#additional-information) - [Dataset Curators](#dataset-curators) - [Licensing Information](#licensing-information) - [Citation Information](#citation-information) - [Contributions](#contributions) ## Dataset Description - **Homepage:** - **Repository:** - **Paper:** - **Leaderboard:** - **Point of Contact:** ### Dataset Summary [More Information Needed] ### Supported Tasks and Leaderboards [More Information Needed] ### Languages [More Information Needed] ## Dataset Structure ### Data Instances [More Information Needed] ### Data Fields [More Information Needed] ### Data Splits [More Information Needed] ## Dataset Creation ### Curation Rationale [More Information Needed] ### Source Data #### Initial Data Collection and Normalization [More Information Needed] #### Who are the source language producers? [More Information Needed] ### Annotations #### Annotation process [More Information Needed] #### Who are the annotators? [More Information Needed] ### Personal and Sensitive Information [More Information Needed] ## Considerations for Using the Data ### Social Impact of Dataset [More Information Needed] ### Discussion of Biases [More Information Needed] ### Other Known Limitations [More Information Needed] ## Additional Information ### Dataset Curators [More Information Needed] ### Licensing Information [More Information Needed] ### Citation Information [More Information Needed] ### Contributions Thanks to [@github-username](https://github.com/<github-username>) for adding this dataset.
0
hf_public_repos/datasets
hf_public_repos/datasets/templates/README_guide.md
--- YAML tags (full spec here: https://github.com/huggingface/hub-docs/blob/main/datasetcard.md?plain=1): - copy-paste the tags obtained with the online tagging app: https://huggingface.co/spaces/huggingface/datasets-tagging --- # Dataset Card Creation Guide ## Table of Contents - [Dataset Card Creation Guide](#dataset-card-creation-guide) - [Table of Contents](#table-of-contents) - [Dataset Description](#dataset-description) - [Dataset Summary](#dataset-summary) - [Supported Tasks and Leaderboards](#supported-tasks-and-leaderboards) - [Languages](#languages) - [Dataset Structure](#dataset-structure) - [Data Instances](#data-instances) - [Data Fields](#data-fields) - [Data Splits](#data-splits) - [Dataset Creation](#dataset-creation) - [Curation Rationale](#curation-rationale) - [Source Data](#source-data) - [Initial Data Collection and Normalization](#initial-data-collection-and-normalization) - [Who are the source language producers?](#who-are-the-source-language-producers) - [Annotations](#annotations) - [Annotation process](#annotation-process) - [Who are the annotators?](#who-are-the-annotators) - [Personal and Sensitive Information](#personal-and-sensitive-information) - [Considerations for Using the Data](#considerations-for-using-the-data) - [Social Impact of Dataset](#social-impact-of-dataset) - [Discussion of Biases](#discussion-of-biases) - [Other Known Limitations](#other-known-limitations) - [Additional Information](#additional-information) - [Dataset Curators](#dataset-curators) - [Licensing Information](#licensing-information) - [Citation Information](#citation-information) - [Contributions](#contributions) ## Dataset Description - **Homepage:** [Add homepage URL here if available (unless it's a GitHub repository)]() - **Repository:** [If the dataset is hosted on github or has a github homepage, add URL here]() - **Paper:** [If the dataset was introduced by a paper or there was a paper written describing the dataset, add URL here (landing page for Arxiv paper preferred)]() - **Leaderboard:** [If the dataset supports an active leaderboard, add link here]() - **Point of Contact:** [If known, name and email of at least one person the reader can contact for questions about the dataset.]() ### Dataset Summary Briefly summarize the dataset, its intended use and the supported tasks. Give an overview of how and why the dataset was created. The summary should explicitly mention the languages present in the dataset (possibly in broad terms, e.g. *translations between several pairs of European languages*), and describe the domain, topic, or genre covered. ### Supported Tasks and Leaderboards For each of the tasks tagged for this dataset, give a brief description of the tag, metrics, and suggested models (with a link to their HuggingFace implementation if available). Give a similar description of tasks that were not covered by the structured tag set (repace the `task-category-tag` with an appropriate `other:other-task-name`). - `task-category-tag`: The dataset can be used to train a model for [TASK NAME], which consists in [TASK DESCRIPTION]. Success on this task is typically measured by achieving a *high/low* [metric name](https://huggingface.co/metrics/metric_name). The ([model name](https://huggingface.co/model_name) or [model class](https://huggingface.co/transformers/model_doc/model_class.html)) model currently achieves the following score. *[IF A LEADERBOARD IS AVAILABLE]:* This task has an active leaderboard which can be found at [leaderboard url]() and ranks models based on [metric name](https://huggingface.co/metrics/metric_name) while also reporting [other metric name](https://huggingface.co/metrics/other_metric_name). ### Languages Provide a brief overview of the languages represented in the dataset. Describe relevant details about specifics of the language such as whether it is social media text, African American English,... When relevant, please provide [BCP-47 codes](https://tools.ietf.org/html/bcp47), which consist of a [primary language subtag](https://tools.ietf.org/html/bcp47#section-2.2.1), with a [script subtag](https://tools.ietf.org/html/bcp47#section-2.2.3) and/or [region subtag](https://tools.ietf.org/html/bcp47#section-2.2.4) if available. ## Dataset Structure ### Data Instances Provide an JSON-formatted example and brief description of a typical instance in the dataset. If available, provide a link to further examples. ``` { 'example_field': ..., ... } ``` Provide any additional information that is not covered in the other sections about the data here. In particular describe any relationships between data points and if these relationships are made explicit. ### Data Fields List and describe the fields present in the dataset. Mention their data type, and whether they are used as input or output in any of the tasks the dataset currently supports. If the data has span indices, describe their attributes, such as whether they are at the character level or word level, whether they are contiguous or not, etc. If the datasets contains example IDs, state whether they have an inherent meaning, such as a mapping to other datasets or pointing to relationships between data points. - `example_field`: description of `example_field` Note that the descriptions can be initialized with the **Show Markdown Data Fields** output of the [Datasets Tagging app](https://huggingface.co/spaces/huggingface/datasets-tagging), you will then only need to refine the generated descriptions. ### Data Splits Describe and name the splits in the dataset if there are more than one. Describe any criteria for splitting the data, if used. If there are differences between the splits (e.g. if the training annotations are machine-generated and the dev and test ones are created by humans, or if different numbers of annotators contributed to each example), describe them here. Provide the sizes of each split. As appropriate, provide any descriptive statistics for the features, such as average length. For example: | | train | validation | test | |-------------------------|------:|-----------:|-----:| | Input Sentences | | | | | Average Sentence Length | | | | ## Dataset Creation ### Curation Rationale What need motivated the creation of this dataset? What are some of the reasons underlying the major choices involved in putting it together? ### Source Data This section describes the source data (e.g. news text and headlines, social media posts, translated sentences,...) #### Initial Data Collection and Normalization Describe the data collection process. Describe any criteria for data selection or filtering. List any key words or search terms used. If possible, include runtime information for the collection process. If data was collected from other pre-existing datasets, link to source here and to their [Hugging Face version](https://huggingface.co/datasets/dataset_name). If the data was modified or normalized after being collected (e.g. if the data is word-tokenized), describe the process and the tools used. #### Who are the source language producers? State whether the data was produced by humans or machine generated. Describe the people or systems who originally created the data. If available, include self-reported demographic or identity information for the source data creators, but avoid inferring this information. Instead state that this information is unknown. See [Larson 2017](https://www.aclweb.org/anthology/W17-1601.pdf) for using identity categories as a variables, particularly gender. Describe the conditions under which the data was created (for example, if the producers were crowdworkers, state what platform was used, or if the data was found, what website the data was found on). If compensation was provided, include that information here. Describe other people represented or mentioned in the data. Where possible, link to references for the information. ### Annotations If the dataset contains annotations which are not part of the initial data collection, describe them in the following paragraphs. #### Annotation process If applicable, describe the annotation process and any tools used, or state otherwise. Describe the amount of data annotated, if not all. Describe or reference annotation guidelines provided to the annotators. If available, provide interannotator statistics. Describe any annotation validation processes. #### Who are the annotators? If annotations were collected for the source data (such as class labels or syntactic parses), state whether the annotations were produced by humans or machine generated. Describe the people or systems who originally created the annotations and their selection criteria if applicable. If available, include self-reported demographic or identity information for the annotators, but avoid inferring this information. Instead state that this information is unknown. See [Larson 2017](https://www.aclweb.org/anthology/W17-1601.pdf) for using identity categories as a variables, particularly gender. Describe the conditions under which the data was annotated (for example, if the annotators were crowdworkers, state what platform was used, or if the data was found, what website the data was found on). If compensation was provided, include that information here. ### Personal and Sensitive Information State whether the dataset uses identity categories and, if so, how the information is used. Describe where this information comes from (i.e. self-reporting, collecting from profiles, inferring, etc.). See [Larson 2017](https://www.aclweb.org/anthology/W17-1601.pdf) for using identity categories as a variables, particularly gender. State whether the data is linked to individuals and whether those individuals can be identified in the dataset, either directly or indirectly (i.e., in combination with other data). State whether the dataset contains other data that might be considered sensitive (e.g., data that reveals racial or ethnic origins, sexual orientations, religious beliefs, political opinions or union memberships, or locations; financial or health data; biometric or genetic data; forms of government identification, such as social security numbers; criminal history). If efforts were made to anonymize the data, describe the anonymization process. ## Considerations for Using the Data ### Social Impact of Dataset Please discuss some of the ways you believe the use of this dataset will impact society. The statement should include both positive outlooks, such as outlining how technologies developed through its use may improve people's lives, and discuss the accompanying risks. These risks may range from making important decisions more opaque to people who are affected by the technology, to reinforcing existing harmful biases (whose specifics should be discussed in the next section), among other considerations. Also describe in this section if the proposed dataset contains a low-resource or under-represented language. If this is the case or if this task has any impact on underserved communities, please elaborate here. ### Discussion of Biases Provide descriptions of specific biases that are likely to be reflected in the data, and state whether any steps were taken to reduce their impact. For Wikipedia text, see for example [Dinan et al 2020 on biases in Wikipedia (esp. Table 1)](https://arxiv.org/abs/2005.00614), or [Blodgett et al 2020](https://www.aclweb.org/anthology/2020.acl-main.485/) for a more general discussion of the topic. If analyses have been run quantifying these biases, please add brief summaries and links to the studies here. ### Other Known Limitations If studies of the datasets have outlined other limitations of the dataset, such as annotation artifacts, please outline and cite them here. ## Additional Information ### Dataset Curators List the people involved in collecting the dataset and their affiliation(s). If funding information is known, include it here. ### Licensing Information Provide the license and link to the license webpage if available. ### Citation Information Provide the [BibTex](http://www.bibtex.org/)-formatted reference for the dataset. For example: ``` @article{article_id, author = {Author List}, title = {Dataset Paper Title}, journal = {Publication Venue}, year = {2525} } ``` If the dataset has a [DOI](https://www.doi.org/), please provide it here. ### Contributions Thanks to [@github-username](https://github.com/<github-username>) for adding this dataset.
0
hf_public_repos/datasets
hf_public_repos/datasets/templates/metric_card_template.md
# Metric Card for *Current Metric* ***Metric Card Instructions:*** *Copy this file into the relevant metric folder, then fill it out and save it as README.md. Feel free to take a look at existing metric cards if you'd like examples.* ## Metric Description *Give a brief overview of this metric.* ## How to Use *Give general statement of how to use the metric* *Provide simplest possible example for using the metric* ### Inputs *List all input arguments in the format below* - **input_field** *(type): Definition of input, with explanation if necessary. State any default value(s).* ### Output Values *Explain what this metric outputs (e.g. a single score, a list of scores)* *Give an example of what the metric output looks like.* *State the range of possible values that the metric's output can take, as well as what in that range is considered good. For example: "This metric can take on any value between 0 and 100, inclusive. Higher scores are better."* #### Values from Popular Papers *Give examples, preferrably with links, to papers that have reported this metric, along with the values they have reported.* ### Examples *Give code examples of the metric being used. Try to include examples that clear up any potential ambiguity left from the metric description above. If possible, provide a range of examples that show both typical and atypical results, as well as examples where a variety of input parameters are passed.* ## Limitations and Bias *Note any known limitations or biases that the metric has, with links and references if possible.* ## Citation *Cite the source where this metric was introduced.* ## Further References *Add any useful further references.*
0
hf_public_repos/datasets
hf_public_repos/datasets/templates/new_dataset_script.py
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor. # # 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. # TODO: Address all TODOs and remove all explanatory comments """TODO: Add a description here.""" import csv import json import os import datasets # TODO: Add BibTeX citation # Find for instance the citation on arxiv or on the dataset repo/website _CITATION = """\ @InProceedings{huggingface:dataset, title = {A great new dataset}, author={huggingface, Inc. }, year={2020} } """ # TODO: Add description of the dataset here # You can copy an official description _DESCRIPTION = """\ This new dataset is designed to solve this great NLP task and is crafted with a lot of care. """ # TODO: Add a link to an official homepage for the dataset here _HOMEPAGE = "" # TODO: Add the licence for the dataset here if you can find it _LICENSE = "" # TODO: Add link to the official dataset URLs here # The HuggingFace Datasets library doesn't host the datasets but only points to the original files. # This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method) _URLS = { "first_domain": "https://huggingface.co/great-new-dataset-first_domain.zip", "second_domain": "https://huggingface.co/great-new-dataset-second_domain.zip", } # TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case class NewDataset(datasets.GeneratorBasedBuilder): """TODO: Short description of my dataset.""" VERSION = datasets.Version("1.1.0") # This is an example of a dataset with multiple configurations. # If you don't want/need to define several sub-sets in your dataset, # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes. # If you need to make complex sub-parts in the datasets with configurable options # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig # BUILDER_CONFIG_CLASS = MyBuilderConfig # You will be able to load one or the other configurations in the following list with # data = datasets.load_dataset('my_dataset', 'first_domain') # data = datasets.load_dataset('my_dataset', 'second_domain') BUILDER_CONFIGS = [ datasets.BuilderConfig(name="first_domain", version=VERSION, description="This part of my dataset covers a first domain"), datasets.BuilderConfig(name="second_domain", version=VERSION, description="This part of my dataset covers a second domain"), ] DEFAULT_CONFIG_NAME = "first_domain" # It's not mandatory to have a default configuration. Just use one if it make sense. def _info(self): # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset if self.config.name == "first_domain": # This is the name of the configuration selected in BUILDER_CONFIGS above features = datasets.Features( { "sentence": datasets.Value("string"), "option1": datasets.Value("string"), "answer": datasets.Value("string") # These are the features of your dataset like images, labels ... } ) else: # This is an example to show how to have different features for "first_domain" and "second_domain" features = datasets.Features( { "sentence": datasets.Value("string"), "option2": datasets.Value("string"), "second_domain_answer": datasets.Value("string") # These are the features of your dataset like images, labels ... } ) return datasets.DatasetInfo( # This is the description that will appear on the datasets page. description=_DESCRIPTION, # This defines the different columns of the dataset and their types features=features, # Here we define them above because they are different between the two configurations # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and # specify them. They'll be used if as_supervised=True in builder.as_dataset. # supervised_keys=("sentence", "label"), # Homepage of the dataset for documentation homepage=_HOMEPAGE, # License for the dataset if available license=_LICENSE, # Citation for the dataset citation=_CITATION, ) def _split_generators(self, dl_manager): # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files. # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive urls = _URLS[self.config.name] data_dir = dl_manager.download_and_extract(urls) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, # These kwargs will be passed to _generate_examples gen_kwargs={ "filepath": os.path.join(data_dir, "train.jsonl"), "split": "train", }, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, # These kwargs will be passed to _generate_examples gen_kwargs={ "filepath": os.path.join(data_dir, "dev.jsonl"), "split": "dev", }, ), datasets.SplitGenerator( name=datasets.Split.TEST, # These kwargs will be passed to _generate_examples gen_kwargs={ "filepath": os.path.join(data_dir, "test.jsonl"), "split": "test" }, ), ] # method parameters are unpacked from `gen_kwargs` as given in `_split_generators` def _generate_examples(self, filepath, split): # TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset. # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example. with open(filepath, encoding="utf-8") as f: for key, row in enumerate(f): data = json.loads(row) if self.config.name == "first_domain": # Yields examples as (key, example) tuples yield key, { "sentence": data["sentence"], "option1": data["option1"], "answer": "" if split == "test" else data["answer"], } else: yield key, { "sentence": data["sentence"], "option2": data["option2"], "second_domain_answer": "" if split == "test" else data["second_domain_answer"], }
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/README.md
## Add Dummy data test **Important** In order to pass the `load_dataset_<dataset_name>` test, dummy data is required for all possible config names. First we distinguish between datasets scripts that - A) have no config class and - B) have a config class For A) the dummy data folder structure, will always look as follows: - ``dummy/<version>/dummy_data.zip``, *e.g.* ``cosmos_qa/dummy/0.1.0/dummy_data.zip``. For B) the dummy data folder structure, will always look as follows: - ``dummy/<config_name>/<version>/dummy_data.zip``, *e.g.* ``squad/dummy/plain-text/1.0.0/dummy_data.zip``. Now the difficult part is to create the correct `dummy_data.zip` file. **Important** When checking the dummy folder structure of already added datasets, always unzip ``dummy_data.zip``. If a folder ``dummy_data`` is found next to ``dummy_data.zip``, it is probably an old version and should be deleted. The tests only take the ``dummy_data.zip`` file into account. Here we have to pay close attention to the ``_split_generators(self, dl_manager)`` function of the dataset script in question. There are three general possibilties: 1) The ``dl_manager.download_and_extract()`` is given a **single path variable** of type `str` as its argument. In this case the file `dummy_data.zip` should unzip to the following structure: ``os.path.join("dummy_data", <additional-paths-as-defined-in-split-generations>)`` *e.g.* for ``sentiment140``, the unzipped ``dummy_data.zip`` has the following dir structure ``dummy_data/testdata.manual.2009.06.14.csv`` and ``dummy_data/training.1600000.processed.noemoticon.csv``. **Note** if there are no ``<additional-paths-as-defined-in-split-generations>``, then ``dummy_data`` should be the name of the single file. An example for this is the ``crime-and-punishment`` dataset script. 2) The ``dl_manager.download_and_extract()`` is given a **dictionary of paths** of type `str` as its argument. In this case the file `dummy_data.zip` should unzip to the following structure: ``os.path.join("dummy_data", <value_of_dict>.split('/')[-1], <additional-paths-as-defined-in-split-generations>)`` *e.g.* for ``squad``, the unzipped ``dummy_data.zip`` has the following dir structure ``dummy_data/dev-v1.1.json``, etc... **Note** if ``<value_of_dict>`` is a zipped file then the dummy data folder structure should contain the exact name of the zipped file and the following extracted folder structure. The file `dummy_data.zip` should **never** itself contain a zipped file since the dummy data is not unzipped by the ``MockDownloadManager`` during testing. *E.g.* check the dummy folder structure of ``hansards`` where the folders have to be named ``*.tar`` or the structure of ``wiki_split`` where the folders have to be named ``*.zip``. 3) The ``dl_manager.download_and_extract()`` is given a **dictionary of lists of paths** of type `str` as its argument. This is a very special case and has been seen only for the dataset ``ensli``. In this case the values are simply flattened and the dummy folder structure is the same as in 2).
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/_test_patching.py
# isort: skip_file # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: F401 - this is just for tests import os as renamed_os # noqa: F401 - this is just for tests from os import path # noqa: F401 - this is just for tests from os import path as renamed_path # noqa: F401 - this is just for tests from os.path import join # noqa: F401 - this is just for tests from os.path import join as renamed_join # noqa: F401 - this is just for tests open = open # noqa we just need to have a builtin inside this module to test it properly
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/conftest.py
import pytest import datasets # Import fixture modules as plugins pytest_plugins = ["tests.fixtures.files", "tests.fixtures.hub", "tests.fixtures.fsspec"] def pytest_collection_modifyitems(config, items): # Mark tests as "unit" by default if not marked as "integration" (or already marked as "unit") for item in items: if any(marker in item.keywords for marker in ["integration", "unit"]): continue item.add_marker(pytest.mark.unit) def pytest_configure(config): config.addinivalue_line("markers", "torchaudio_latest: mark test to run with torchaudio>=0.12") @pytest.fixture(autouse=True) def set_test_cache_config(tmp_path_factory, monkeypatch): # test_hf_cache_home = tmp_path_factory.mktemp("cache") # TODO: why a cache dir per test function does not work? test_hf_cache_home = tmp_path_factory.getbasetemp() / "cache" test_hf_datasets_cache = test_hf_cache_home / "datasets" test_hf_metrics_cache = test_hf_cache_home / "metrics" test_hf_modules_cache = test_hf_cache_home / "modules" monkeypatch.setattr("datasets.config.HF_DATASETS_CACHE", str(test_hf_datasets_cache)) monkeypatch.setattr("datasets.config.HF_METRICS_CACHE", str(test_hf_metrics_cache)) monkeypatch.setattr("datasets.config.HF_MODULES_CACHE", str(test_hf_modules_cache)) test_downloaded_datasets_path = test_hf_datasets_cache / "downloads" monkeypatch.setattr("datasets.config.DOWNLOADED_DATASETS_PATH", str(test_downloaded_datasets_path)) test_extracted_datasets_path = test_hf_datasets_cache / "downloads" / "extracted" monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH", str(test_extracted_datasets_path)) @pytest.fixture(autouse=True, scope="session") def disable_tqdm_output(): datasets.disable_progress_bar() @pytest.fixture(autouse=True) def set_update_download_counts_to_false(monkeypatch): # don't take tests into account when counting downloads monkeypatch.setattr("datasets.config.HF_UPDATE_DOWNLOAD_COUNTS", False) @pytest.fixture def set_sqlalchemy_silence_uber_warning(monkeypatch): # Required to suppress RemovedIn20Warning when feature(s) are not compatible with SQLAlchemy 2.0 # To be removed once SQLAlchemy 2.0 supported monkeypatch.setattr("sqlalchemy.util.deprecations.SILENCE_UBER_WARNING", True)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_arrow_dataset.py
import contextlib import copy import itertools import json import os import pickle import re import sys import tempfile from functools import partial from pathlib import Path from unittest import TestCase from unittest.mock import MagicMock, patch import numpy as np import numpy.testing as npt import pandas as pd import pyarrow as pa import pytest from absl.testing import parameterized from packaging import version import datasets.arrow_dataset from datasets import concatenate_datasets, interleave_datasets, load_from_disk from datasets.arrow_dataset import Dataset, transmit_format, update_metadata_with_features from datasets.dataset_dict import DatasetDict from datasets.features import ( Array2D, Array3D, Audio, ClassLabel, Features, Image, Sequence, Translation, TranslationVariableLanguages, Value, ) from datasets.filesystems import extract_path_from_uri from datasets.info import DatasetInfo from datasets.iterable_dataset import IterableDataset from datasets.splits import NamedSplit from datasets.table import ConcatenationTable, InMemoryTable, MemoryMappedTable from datasets.tasks import ( AutomaticSpeechRecognition, LanguageModeling, QuestionAnsweringExtractive, Summarization, TextClassification, ) from datasets.utils.logging import INFO, get_logger from datasets.utils.py_utils import temp_seed from .utils import ( assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_dill_gt_0_3_2, require_jax, require_not_windows, require_pil, require_pyspark, require_sqlalchemy, require_tf, require_torch, require_transformers, set_current_working_directory_to_temp_dir, ) class PickableMagicMock(MagicMock): def __reduce__(self): return MagicMock, () class Unpicklable: def __getstate__(self): raise pickle.PicklingError() def picklable_map_function(x): return {"id": int(x["filename"].split("_")[-1])} def picklable_map_function_with_indices(x, i): return {"id": i} def picklable_map_function_with_rank(x, r): return {"rank": r} def picklable_map_function_with_indices_and_rank(x, i, r): return {"id": i, "rank": r} def picklable_filter_function(x): return int(x["filename"].split("_")[-1]) < 10 def assert_arrow_metadata_are_synced_with_dataset_features(dataset: Dataset): assert dataset.data.schema.metadata is not None assert b"huggingface" in dataset.data.schema.metadata metadata = json.loads(dataset.data.schema.metadata[b"huggingface"].decode()) assert "info" in metadata features = DatasetInfo.from_dict(metadata["info"]).features assert features is not None assert features == dataset.features assert features == Features.from_arrow_schema(dataset.data.schema) assert list(features) == dataset.data.column_names assert list(features) == list(dataset.features) IN_MEMORY_PARAMETERS = [ {"testcase_name": name, "in_memory": im} for im, name in [(True, "in_memory"), (False, "on_disk")] ] @parameterized.named_parameters(IN_MEMORY_PARAMETERS) class BaseDatasetTest(TestCase): @pytest.fixture(autouse=True) def inject_fixtures(self, caplog, set_sqlalchemy_silence_uber_warning): self._caplog = caplog def _create_dummy_dataset( self, in_memory: bool, tmp_dir: str, multiple_columns=False, array_features=False, nested_features=False ) -> Dataset: assert int(multiple_columns) + int(array_features) + int(nested_features) < 2 if multiple_columns: data = {"col_1": [3, 2, 1, 0], "col_2": ["a", "b", "c", "d"], "col_3": [False, True, False, True]} dset = Dataset.from_dict(data) elif array_features: data = { "col_1": [[[True, False], [False, True]]] * 4, # 2D "col_2": [[[["a", "b"], ["c", "d"]], [["e", "f"], ["g", "h"]]]] * 4, # 3D array "col_3": [[3, 2, 1, 0]] * 4, # Sequence } features = Features( { "col_1": Array2D(shape=(2, 2), dtype="bool"), "col_2": Array3D(shape=(2, 2, 2), dtype="string"), "col_3": Sequence(feature=Value("int64")), } ) dset = Dataset.from_dict(data, features=features) elif nested_features: data = {"nested": [{"a": i, "x": i * 10, "c": i * 100} for i in range(1, 11)]} features = Features({"nested": {"a": Value("int64"), "x": Value("int64"), "c": Value("int64")}}) dset = Dataset.from_dict(data, features=features) else: dset = Dataset.from_dict({"filename": ["my_name-train" + "_" + str(x) for x in np.arange(30).tolist()]}) if not in_memory: dset = self._to(in_memory, tmp_dir, dset) return dset def _to(self, in_memory, tmp_dir, *datasets): if in_memory: datasets = [dataset.map(keep_in_memory=True) for dataset in datasets] else: start = 0 while os.path.isfile(os.path.join(tmp_dir, f"dataset{start}.arrow")): start += 1 datasets = [ dataset.map(cache_file_name=os.path.join(tmp_dir, f"dataset{start + i}.arrow")) for i, dataset in enumerate(datasets) ] return datasets if len(datasets) > 1 else datasets[0] def test_dummy_dataset(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertEqual(dset[0]["filename"], "my_name-train_0") self.assertEqual(dset["filename"][0], "my_name-train_0") with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: self.assertDictEqual( dset.features, Features({"col_1": Value("int64"), "col_2": Value("string"), "col_3": Value("bool")}), ) self.assertEqual(dset[0]["col_1"], 3) self.assertEqual(dset["col_1"][0], 3) with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, array_features=True) as dset: self.assertDictEqual( dset.features, Features( { "col_1": Array2D(shape=(2, 2), dtype="bool"), "col_2": Array3D(shape=(2, 2, 2), dtype="string"), "col_3": Sequence(feature=Value("int64")), } ), ) self.assertEqual(dset[0]["col_2"], [[["a", "b"], ["c", "d"]], [["e", "f"], ["g", "h"]]]) self.assertEqual(dset["col_2"][0], [[["a", "b"], ["c", "d"]], [["e", "f"], ["g", "h"]]]) def test_dataset_getitem(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: self.assertEqual(dset[0]["filename"], "my_name-train_0") self.assertEqual(dset["filename"][0], "my_name-train_0") self.assertEqual(dset[-1]["filename"], "my_name-train_29") self.assertEqual(dset["filename"][-1], "my_name-train_29") self.assertListEqual(dset[:2]["filename"], ["my_name-train_0", "my_name-train_1"]) self.assertListEqual(dset["filename"][:2], ["my_name-train_0", "my_name-train_1"]) self.assertEqual(dset[:-1]["filename"][-1], "my_name-train_28") self.assertEqual(dset["filename"][:-1][-1], "my_name-train_28") self.assertListEqual(dset[[0, -1]]["filename"], ["my_name-train_0", "my_name-train_29"]) self.assertListEqual(dset[range(0, -2, -1)]["filename"], ["my_name-train_0", "my_name-train_29"]) self.assertListEqual(dset[np.array([0, -1])]["filename"], ["my_name-train_0", "my_name-train_29"]) self.assertListEqual(dset[pd.Series([0, -1])]["filename"], ["my_name-train_0", "my_name-train_29"]) with dset.select(range(2)) as dset_subset: self.assertListEqual(dset_subset[-1:]["filename"], ["my_name-train_1"]) self.assertListEqual(dset_subset["filename"][-1:], ["my_name-train_1"]) def test_dummy_dataset_deepcopy(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir).select(range(10)) as dset: with assert_arrow_memory_doesnt_increase(): dset2 = copy.deepcopy(dset) # don't copy the underlying arrow data using memory self.assertEqual(len(dset2), 10) self.assertDictEqual(dset2.features, Features({"filename": Value("string")})) self.assertEqual(dset2[0]["filename"], "my_name-train_0") self.assertEqual(dset2["filename"][0], "my_name-train_0") del dset2 def test_dummy_dataset_pickle(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: tmp_file = os.path.join(tmp_dir, "dset.pt") with self._create_dummy_dataset(in_memory, tmp_dir).select(range(0, 10, 2)) as dset: with open(tmp_file, "wb") as f: pickle.dump(dset, f) with open(tmp_file, "rb") as f: with pickle.load(f) as dset: self.assertEqual(len(dset), 5) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertEqual(dset[0]["filename"], "my_name-train_0") self.assertEqual(dset["filename"][0], "my_name-train_0") with self._create_dummy_dataset(in_memory, tmp_dir).select( range(0, 10, 2), indices_cache_file_name=os.path.join(tmp_dir, "ind.arrow") ) as dset: if not in_memory: dset._data.table = Unpicklable() dset._indices.table = Unpicklable() with open(tmp_file, "wb") as f: pickle.dump(dset, f) with open(tmp_file, "rb") as f: with pickle.load(f) as dset: self.assertEqual(len(dset), 5) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertEqual(dset[0]["filename"], "my_name-train_0") self.assertEqual(dset["filename"][0], "my_name-train_0") def test_dummy_dataset_serialize(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with set_current_working_directory_to_temp_dir(): with self._create_dummy_dataset(in_memory, tmp_dir).select(range(10)) as dset: dataset_path = "my_dataset" # rel path dset.save_to_disk(dataset_path) with Dataset.load_from_disk(dataset_path) as dset: self.assertEqual(len(dset), 10) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertEqual(dset[0]["filename"], "my_name-train_0") self.assertEqual(dset["filename"][0], "my_name-train_0") expected = dset.to_dict() with self._create_dummy_dataset(in_memory, tmp_dir).select(range(10)) as dset: dataset_path = os.path.join(tmp_dir, "my_dataset") # abs path dset.save_to_disk(dataset_path) with Dataset.load_from_disk(dataset_path) as dset: self.assertEqual(len(dset), 10) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertEqual(dset[0]["filename"], "my_name-train_0") self.assertEqual(dset["filename"][0], "my_name-train_0") with self._create_dummy_dataset(in_memory, tmp_dir).select( range(10), indices_cache_file_name=os.path.join(tmp_dir, "ind.arrow") ) as dset: with assert_arrow_memory_doesnt_increase(): dset.save_to_disk(dataset_path) with Dataset.load_from_disk(dataset_path) as dset: self.assertEqual(len(dset), 10) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertEqual(dset[0]["filename"], "my_name-train_0") self.assertEqual(dset["filename"][0], "my_name-train_0") with self._create_dummy_dataset(in_memory, tmp_dir, nested_features=True) as dset: with assert_arrow_memory_doesnt_increase(): dset.save_to_disk(dataset_path) with Dataset.load_from_disk(dataset_path) as dset: self.assertEqual(len(dset), 10) self.assertDictEqual( dset.features, Features({"nested": {"a": Value("int64"), "x": Value("int64"), "c": Value("int64")}}), ) self.assertDictEqual(dset[0]["nested"], {"a": 1, "c": 100, "x": 10}) self.assertDictEqual(dset["nested"][0], {"a": 1, "c": 100, "x": 10}) with self._create_dummy_dataset(in_memory, tmp_dir).select(range(10)) as dset: with assert_arrow_memory_doesnt_increase(): dset.save_to_disk(dataset_path, num_shards=4) with Dataset.load_from_disk(dataset_path) as dset: self.assertEqual(len(dset), 10) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset.to_dict(), expected) self.assertEqual(len(dset.cache_files), 4) with self._create_dummy_dataset(in_memory, tmp_dir).select(range(10)) as dset: with assert_arrow_memory_doesnt_increase(): dset.save_to_disk(dataset_path, num_proc=2) with Dataset.load_from_disk(dataset_path) as dset: self.assertEqual(len(dset), 10) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset.to_dict(), expected) self.assertEqual(len(dset.cache_files), 2) with self._create_dummy_dataset(in_memory, tmp_dir).select(range(10)) as dset: with assert_arrow_memory_doesnt_increase(): dset.save_to_disk(dataset_path, num_shards=7, num_proc=2) with Dataset.load_from_disk(dataset_path) as dset: self.assertEqual(len(dset), 10) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset.to_dict(), expected) self.assertEqual(len(dset.cache_files), 7) with self._create_dummy_dataset(in_memory, tmp_dir).select(range(10)) as dset: with assert_arrow_memory_doesnt_increase(): max_shard_size = dset._estimate_nbytes() // 2 + 1 dset.save_to_disk(dataset_path, max_shard_size=max_shard_size) with Dataset.load_from_disk(dataset_path) as dset: self.assertEqual(len(dset), 10) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset.to_dict(), expected) self.assertEqual(len(dset.cache_files), 2) def test_dummy_dataset_load_from_disk(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir).select(range(10)) as dset: dataset_path = os.path.join(tmp_dir, "my_dataset") dset.save_to_disk(dataset_path) with load_from_disk(dataset_path) as dset: self.assertEqual(len(dset), 10) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertEqual(dset[0]["filename"], "my_name-train_0") self.assertEqual(dset["filename"][0], "my_name-train_0") def test_restore_saved_format(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: dset.set_format(type="numpy", columns=["col_1"], output_all_columns=True) dataset_path = os.path.join(tmp_dir, "my_dataset") dset.save_to_disk(dataset_path) with load_from_disk(dataset_path) as loaded_dset: self.assertEqual(dset.format, loaded_dset.format) def test_set_format_numpy_multiple_columns(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: fingerprint = dset._fingerprint dset.set_format(type="numpy", columns=["col_1"]) self.assertEqual(len(dset[0]), 1) self.assertIsInstance(dset[0]["col_1"], np.int64) self.assertEqual(dset[0]["col_1"].item(), 3) self.assertIsInstance(dset["col_1"], np.ndarray) self.assertListEqual(list(dset["col_1"].shape), [4]) np.testing.assert_array_equal(dset["col_1"], np.array([3, 2, 1, 0])) self.assertNotEqual(dset._fingerprint, fingerprint) dset.reset_format() with dset.formatted_as(type="numpy", columns=["col_1"]): self.assertEqual(len(dset[0]), 1) self.assertIsInstance(dset[0]["col_1"], np.int64) self.assertEqual(dset[0]["col_1"].item(), 3) self.assertIsInstance(dset["col_1"], np.ndarray) self.assertListEqual(list(dset["col_1"].shape), [4]) np.testing.assert_array_equal(dset["col_1"], np.array([3, 2, 1, 0])) self.assertEqual(dset.format["type"], None) self.assertEqual(dset.format["format_kwargs"], {}) self.assertEqual(dset.format["columns"], dset.column_names) self.assertEqual(dset.format["output_all_columns"], False) dset.set_format(type="numpy", columns=["col_1"], output_all_columns=True) self.assertEqual(len(dset[0]), 3) self.assertIsInstance(dset[0]["col_2"], str) self.assertEqual(dset[0]["col_2"], "a") dset.set_format(type="numpy", columns=["col_1", "col_2"]) self.assertEqual(len(dset[0]), 2) self.assertIsInstance(dset[0]["col_2"], np.str_) self.assertEqual(dset[0]["col_2"].item(), "a") @require_torch def test_set_format_torch(self, in_memory): import torch with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: dset.set_format(type="torch", columns=["col_1"]) self.assertEqual(len(dset[0]), 1) self.assertIsInstance(dset[0]["col_1"], torch.Tensor) self.assertIsInstance(dset["col_1"], torch.Tensor) self.assertListEqual(list(dset[0]["col_1"].shape), []) self.assertEqual(dset[0]["col_1"].item(), 3) dset.set_format(type="torch", columns=["col_1"], output_all_columns=True) self.assertEqual(len(dset[0]), 3) self.assertIsInstance(dset[0]["col_2"], str) self.assertEqual(dset[0]["col_2"], "a") dset.set_format(type="torch") self.assertEqual(len(dset[0]), 3) self.assertIsInstance(dset[0]["col_1"], torch.Tensor) self.assertIsInstance(dset["col_1"], torch.Tensor) self.assertListEqual(list(dset[0]["col_1"].shape), []) self.assertEqual(dset[0]["col_1"].item(), 3) self.assertIsInstance(dset[0]["col_2"], str) self.assertEqual(dset[0]["col_2"], "a") self.assertIsInstance(dset[0]["col_3"], torch.Tensor) self.assertIsInstance(dset["col_3"], torch.Tensor) self.assertListEqual(list(dset[0]["col_3"].shape), []) @require_tf def test_set_format_tf(self, in_memory): import tensorflow as tf with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: dset.set_format(type="tensorflow", columns=["col_1"]) self.assertEqual(len(dset[0]), 1) self.assertIsInstance(dset[0]["col_1"], tf.Tensor) self.assertListEqual(list(dset[0]["col_1"].shape), []) self.assertEqual(dset[0]["col_1"].numpy().item(), 3) dset.set_format(type="tensorflow", columns=["col_1"], output_all_columns=True) self.assertEqual(len(dset[0]), 3) self.assertIsInstance(dset[0]["col_2"], str) self.assertEqual(dset[0]["col_2"], "a") dset.set_format(type="tensorflow", columns=["col_1", "col_2"]) self.assertEqual(len(dset[0]), 2) self.assertEqual(dset[0]["col_2"].numpy().decode("utf-8"), "a") def test_set_format_pandas(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: dset.set_format(type="pandas", columns=["col_1"]) self.assertEqual(len(dset[0].columns), 1) self.assertIsInstance(dset[0], pd.DataFrame) self.assertListEqual(list(dset[0].shape), [1, 1]) self.assertEqual(dset[0]["col_1"].item(), 3) dset.set_format(type="pandas", columns=["col_1", "col_2"]) self.assertEqual(len(dset[0].columns), 2) self.assertEqual(dset[0]["col_2"].item(), "a") def test_set_transform(self, in_memory): def transform(batch): return {k: [str(i).upper() for i in v] for k, v in batch.items()} with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: dset.set_transform(transform=transform, columns=["col_1"]) self.assertEqual(dset.format["type"], "custom") self.assertEqual(len(dset[0].keys()), 1) self.assertEqual(dset[0]["col_1"], "3") self.assertEqual(dset[:2]["col_1"], ["3", "2"]) self.assertEqual(dset["col_1"][:2], ["3", "2"]) prev_format = dset.format dset.set_format(**dset.format) self.assertEqual(prev_format, dset.format) dset.set_transform(transform=transform, columns=["col_1", "col_2"]) self.assertEqual(len(dset[0].keys()), 2) self.assertEqual(dset[0]["col_2"], "A") def test_transmit_format(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: transform = datasets.arrow_dataset.transmit_format(lambda x: x) # make sure identity transform doesn't apply unnecessary format self.assertEqual(dset._fingerprint, transform(dset)._fingerprint) dset.set_format(**dset.format) self.assertEqual(dset._fingerprint, transform(dset)._fingerprint) # check lists comparisons dset.set_format(columns=["col_1"]) self.assertEqual(dset._fingerprint, transform(dset)._fingerprint) dset.set_format(columns=["col_1", "col_2"]) self.assertEqual(dset._fingerprint, transform(dset)._fingerprint) dset.set_format("numpy", columns=["col_1", "col_2"]) self.assertEqual(dset._fingerprint, transform(dset)._fingerprint) def test_cast(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: features = dset.features features["col_1"] = Value("float64") features = Features({k: features[k] for k in list(features)[::-1]}) fingerprint = dset._fingerprint # TODO: with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase(): with dset.cast(features) as casted_dset: self.assertEqual(casted_dset.num_columns, 3) self.assertEqual(casted_dset.features["col_1"], Value("float64")) self.assertIsInstance(casted_dset[0]["col_1"], float) self.assertNotEqual(casted_dset._fingerprint, fingerprint) self.assertNotEqual(casted_dset, dset) assert_arrow_metadata_are_synced_with_dataset_features(casted_dset) def test_class_encode_column(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: with self.assertRaises(ValueError): dset.class_encode_column(column="does not exist") with dset.class_encode_column("col_1") as casted_dset: self.assertIsInstance(casted_dset.features["col_1"], ClassLabel) self.assertListEqual(casted_dset.features["col_1"].names, ["0", "1", "2", "3"]) self.assertListEqual(casted_dset["col_1"], [3, 2, 1, 0]) self.assertNotEqual(casted_dset._fingerprint, dset._fingerprint) self.assertNotEqual(casted_dset, dset) assert_arrow_metadata_are_synced_with_dataset_features(casted_dset) with dset.class_encode_column("col_2") as casted_dset: self.assertIsInstance(casted_dset.features["col_2"], ClassLabel) self.assertListEqual(casted_dset.features["col_2"].names, ["a", "b", "c", "d"]) self.assertListEqual(casted_dset["col_2"], [0, 1, 2, 3]) self.assertNotEqual(casted_dset._fingerprint, dset._fingerprint) self.assertNotEqual(casted_dset, dset) assert_arrow_metadata_are_synced_with_dataset_features(casted_dset) with dset.class_encode_column("col_3") as casted_dset: self.assertIsInstance(casted_dset.features["col_3"], ClassLabel) self.assertListEqual(casted_dset.features["col_3"].names, ["False", "True"]) self.assertListEqual(casted_dset["col_3"], [0, 1, 0, 1]) self.assertNotEqual(casted_dset._fingerprint, dset._fingerprint) self.assertNotEqual(casted_dset, dset) assert_arrow_metadata_are_synced_with_dataset_features(casted_dset) # Test raises if feature is an array / sequence with self._create_dummy_dataset(in_memory, tmp_dir, array_features=True) as dset: for column in dset.column_names: with self.assertRaises(ValueError): dset.class_encode_column(column) def test_remove_columns(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: fingerprint = dset._fingerprint with dset.remove_columns(column_names="col_1") as new_dset: self.assertEqual(new_dset.num_columns, 2) self.assertListEqual(list(new_dset.column_names), ["col_2", "col_3"]) self.assertNotEqual(new_dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(new_dset) with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: with dset.remove_columns(column_names=["col_1", "col_2", "col_3"]) as new_dset: self.assertEqual(new_dset.num_columns, 0) self.assertNotEqual(new_dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(new_dset) with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: dset._format_columns = ["col_1", "col_2", "col_3"] with dset.remove_columns(column_names=["col_1"]) as new_dset: self.assertListEqual(new_dset._format_columns, ["col_2", "col_3"]) self.assertEqual(new_dset.num_columns, 2) self.assertListEqual(list(new_dset.column_names), ["col_2", "col_3"]) self.assertNotEqual(new_dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(new_dset) def test_rename_column(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: fingerprint = dset._fingerprint with dset.rename_column(original_column_name="col_1", new_column_name="new_name") as new_dset: self.assertEqual(new_dset.num_columns, 3) self.assertListEqual(list(new_dset.column_names), ["new_name", "col_2", "col_3"]) self.assertListEqual(list(dset.column_names), ["col_1", "col_2", "col_3"]) self.assertNotEqual(new_dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(new_dset) def test_rename_columns(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: fingerprint = dset._fingerprint with dset.rename_columns({"col_1": "new_name"}) as new_dset: self.assertEqual(new_dset.num_columns, 3) self.assertListEqual(list(new_dset.column_names), ["new_name", "col_2", "col_3"]) self.assertListEqual(list(dset.column_names), ["col_1", "col_2", "col_3"]) self.assertNotEqual(new_dset._fingerprint, fingerprint) with dset.rename_columns({"col_1": "new_name", "col_2": "new_name2"}) as new_dset: self.assertEqual(new_dset.num_columns, 3) self.assertListEqual(list(new_dset.column_names), ["new_name", "new_name2", "col_3"]) self.assertListEqual(list(dset.column_names), ["col_1", "col_2", "col_3"]) self.assertNotEqual(new_dset._fingerprint, fingerprint) # Original column not in dataset with self.assertRaises(ValueError): dset.rename_columns({"not_there": "new_name"}) # Empty new name with self.assertRaises(ValueError): dset.rename_columns({"col_1": ""}) # Duplicates with self.assertRaises(ValueError): dset.rename_columns({"col_1": "new_name", "col_2": "new_name"}) def test_select_columns(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: fingerprint = dset._fingerprint with dset.select_columns(column_names=[]) as new_dset: self.assertEqual(new_dset.num_columns, 0) self.assertListEqual(list(new_dset.column_names), []) self.assertNotEqual(new_dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(new_dset) with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: fingerprint = dset._fingerprint with dset.select_columns(column_names="col_1") as new_dset: self.assertEqual(new_dset.num_columns, 1) self.assertListEqual(list(new_dset.column_names), ["col_1"]) self.assertNotEqual(new_dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(new_dset) with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: with dset.select_columns(column_names=["col_1", "col_2", "col_3"]) as new_dset: self.assertEqual(new_dset.num_columns, 3) self.assertListEqual(list(new_dset.column_names), ["col_1", "col_2", "col_3"]) self.assertNotEqual(new_dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(new_dset) with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: with dset.select_columns(column_names=["col_3", "col_2", "col_1"]) as new_dset: self.assertEqual(new_dset.num_columns, 3) self.assertListEqual(list(new_dset.column_names), ["col_3", "col_2", "col_1"]) self.assertNotEqual(new_dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(new_dset) with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: dset._format_columns = ["col_1", "col_2", "col_3"] with dset.select_columns(column_names=["col_1"]) as new_dset: self.assertListEqual(new_dset._format_columns, ["col_1"]) self.assertEqual(new_dset.num_columns, 1) self.assertListEqual(list(new_dset.column_names), ["col_1"]) self.assertNotEqual(new_dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(new_dset) def test_concatenate(self, in_memory): data1, data2, data3 = {"id": [0, 1, 2]}, {"id": [3, 4, 5]}, {"id": [6, 7]} info1 = DatasetInfo(description="Dataset1") info2 = DatasetInfo(description="Dataset2") with tempfile.TemporaryDirectory() as tmp_dir: dset1, dset2, dset3 = ( Dataset.from_dict(data1, info=info1), Dataset.from_dict(data2, info=info2), Dataset.from_dict(data3), ) dset1, dset2, dset3 = self._to(in_memory, tmp_dir, dset1, dset2, dset3) with concatenate_datasets([dset1, dset2, dset3]) as dset_concat: self.assertTupleEqual((len(dset1), len(dset2), len(dset3)), (3, 3, 2)) self.assertEqual(len(dset_concat), len(dset1) + len(dset2) + len(dset3)) self.assertListEqual(dset_concat["id"], [0, 1, 2, 3, 4, 5, 6, 7]) self.assertEqual(len(dset_concat.cache_files), 0 if in_memory else 3) self.assertEqual(dset_concat.info.description, "Dataset1\n\nDataset2") del dset1, dset2, dset3 def test_concatenate_formatted(self, in_memory): data1, data2, data3 = {"id": [0, 1, 2]}, {"id": [3, 4, 5]}, {"id": [6, 7]} info1 = DatasetInfo(description="Dataset1") info2 = DatasetInfo(description="Dataset2") with tempfile.TemporaryDirectory() as tmp_dir: dset1, dset2, dset3 = ( Dataset.from_dict(data1, info=info1), Dataset.from_dict(data2, info=info2), Dataset.from_dict(data3), ) dset1, dset2, dset3 = self._to(in_memory, tmp_dir, dset1, dset2, dset3) dset1.set_format("numpy") with concatenate_datasets([dset1, dset2, dset3]) as dset_concat: self.assertEqual(dset_concat.format["type"], None) dset2.set_format("numpy") dset3.set_format("numpy") with concatenate_datasets([dset1, dset2, dset3]) as dset_concat: self.assertEqual(dset_concat.format["type"], "numpy") del dset1, dset2, dset3 def test_concatenate_with_indices(self, in_memory): data1, data2, data3 = {"id": [0, 1, 2] * 2}, {"id": [3, 4, 5] * 2}, {"id": [6, 7, 8]} info1 = DatasetInfo(description="Dataset1") info2 = DatasetInfo(description="Dataset2") with tempfile.TemporaryDirectory() as tmp_dir: dset1, dset2, dset3 = ( Dataset.from_dict(data1, info=info1), Dataset.from_dict(data2, info=info2), Dataset.from_dict(data3), ) dset1, dset2, dset3 = self._to(in_memory, tmp_dir, dset1, dset2, dset3) dset1, dset2, dset3 = dset1.select([2, 1, 0]), dset2.select([2, 1, 0]), dset3 with concatenate_datasets([dset3, dset2, dset1]) as dset_concat: self.assertTupleEqual((len(dset1), len(dset2), len(dset3)), (3, 3, 3)) self.assertEqual(len(dset_concat), len(dset1) + len(dset2) + len(dset3)) self.assertListEqual(dset_concat["id"], [6, 7, 8, 5, 4, 3, 2, 1, 0]) # in_memory = False: # 3 cache files for the dset_concat._data table # no cache file for the indices because it's in memory # in_memory = True: # no cache files since both dset_concat._data and dset_concat._indices are in memory self.assertEqual(len(dset_concat.cache_files), 0 if in_memory else 3) self.assertEqual(dset_concat.info.description, "Dataset2\n\nDataset1") dset1 = dset1.rename_columns({"id": "id1"}) dset2 = dset2.rename_columns({"id": "id2"}) dset3 = dset3.rename_columns({"id": "id3"}) with concatenate_datasets([dset1, dset2, dset3], axis=1) as dset_concat: self.assertTupleEqual((len(dset1), len(dset2), len(dset3)), (3, 3, 3)) self.assertEqual(len(dset_concat), len(dset1)) self.assertListEqual(dset_concat["id1"], [2, 1, 0]) self.assertListEqual(dset_concat["id2"], [5, 4, 3]) self.assertListEqual(dset_concat["id3"], [6, 7, 8]) # in_memory = False: # 3 cache files for the dset_concat._data table # no cache file for the indices because it's None # in_memory = True: # no cache files since dset_concat._data is in memory and dset_concat._indices is None self.assertEqual(len(dset_concat.cache_files), 0 if in_memory else 3) self.assertIsNone(dset_concat._indices) self.assertEqual(dset_concat.info.description, "Dataset1\n\nDataset2") with concatenate_datasets([dset1], axis=1) as dset_concat: self.assertEqual(len(dset_concat), len(dset1)) self.assertListEqual(dset_concat["id1"], [2, 1, 0]) # in_memory = False: # 1 cache file for the dset_concat._data table # no cache file for the indices because it's in memory # in_memory = True: # no cache files since both dset_concat._data and dset_concat._indices are in memory self.assertEqual(len(dset_concat.cache_files), 0 if in_memory else 1) self.assertTrue(dset_concat._indices == dset1._indices) self.assertEqual(dset_concat.info.description, "Dataset1") del dset1, dset2, dset3 def test_concatenate_with_indices_from_disk(self, in_memory): data1, data2, data3 = {"id": [0, 1, 2] * 2}, {"id": [3, 4, 5] * 2}, {"id": [6, 7]} info1 = DatasetInfo(description="Dataset1") info2 = DatasetInfo(description="Dataset2") with tempfile.TemporaryDirectory() as tmp_dir: dset1, dset2, dset3 = ( Dataset.from_dict(data1, info=info1), Dataset.from_dict(data2, info=info2), Dataset.from_dict(data3), ) dset1, dset2, dset3 = self._to(in_memory, tmp_dir, dset1, dset2, dset3) dset1, dset2, dset3 = ( dset1.select([2, 1, 0], indices_cache_file_name=os.path.join(tmp_dir, "i1.arrow")), dset2.select([2, 1, 0], indices_cache_file_name=os.path.join(tmp_dir, "i2.arrow")), dset3.select([1, 0], indices_cache_file_name=os.path.join(tmp_dir, "i3.arrow")), ) with concatenate_datasets([dset3, dset2, dset1]) as dset_concat: self.assertTupleEqual((len(dset1), len(dset2), len(dset3)), (3, 3, 2)) self.assertEqual(len(dset_concat), len(dset1) + len(dset2) + len(dset3)) self.assertListEqual(dset_concat["id"], [7, 6, 5, 4, 3, 2, 1, 0]) # in_memory = False: # 3 cache files for the dset_concat._data table, and 1 for the dset_concat._indices_table # There is only 1 for the indices tables (i1.arrow) # Indeed, the others are brought to memory since an offset is applied to them. # in_memory = True: # 1 cache file for i1.arrow since both dset_concat._data and dset_concat._indices are in memory self.assertEqual(len(dset_concat.cache_files), 1 if in_memory else 3 + 1) self.assertEqual(dset_concat.info.description, "Dataset2\n\nDataset1") del dset1, dset2, dset3 def test_concatenate_pickle(self, in_memory): data1, data2, data3 = {"id": [0, 1, 2] * 2}, {"id": [3, 4, 5] * 2}, {"id": [6, 7], "foo": ["bar", "bar"]} info1 = DatasetInfo(description="Dataset1") info2 = DatasetInfo(description="Dataset2") with tempfile.TemporaryDirectory() as tmp_dir: dset1, dset2, dset3 = ( Dataset.from_dict(data1, info=info1), Dataset.from_dict(data2, info=info2), Dataset.from_dict(data3), ) # mix from in-memory and on-disk datasets dset1, dset2 = self._to(in_memory, tmp_dir, dset1, dset2) dset3 = self._to(not in_memory, tmp_dir, dset3) dset1, dset2, dset3 = ( dset1.select( [2, 1, 0], keep_in_memory=in_memory, indices_cache_file_name=os.path.join(tmp_dir, "i1.arrow") if not in_memory else None, ), dset2.select( [2, 1, 0], keep_in_memory=in_memory, indices_cache_file_name=os.path.join(tmp_dir, "i2.arrow") if not in_memory else None, ), dset3.select( [1, 0], keep_in_memory=in_memory, indices_cache_file_name=os.path.join(tmp_dir, "i3.arrow") if not in_memory else None, ), ) dset3 = dset3.rename_column("foo", "new_foo") dset3 = dset3.remove_columns("new_foo") if in_memory: dset3._data.table = Unpicklable() else: dset1._data.table, dset2._data.table = Unpicklable(), Unpicklable() dset1, dset2, dset3 = (pickle.loads(pickle.dumps(d)) for d in (dset1, dset2, dset3)) with concatenate_datasets([dset3, dset2, dset1]) as dset_concat: if not in_memory: dset_concat._data.table = Unpicklable() with pickle.loads(pickle.dumps(dset_concat)) as dset_concat: self.assertTupleEqual((len(dset1), len(dset2), len(dset3)), (3, 3, 2)) self.assertEqual(len(dset_concat), len(dset1) + len(dset2) + len(dset3)) self.assertListEqual(dset_concat["id"], [7, 6, 5, 4, 3, 2, 1, 0]) # in_memory = True: 1 cache file for dset3 # in_memory = False: 2 caches files for dset1 and dset2, and 1 cache file for i1.arrow self.assertEqual(len(dset_concat.cache_files), 1 if in_memory else 2 + 1) self.assertEqual(dset_concat.info.description, "Dataset2\n\nDataset1") del dset1, dset2, dset3 def test_flatten(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict( {"a": [{"b": {"c": ["text"]}}] * 10, "foo": [1] * 10}, features=Features({"a": {"b": Sequence({"c": Value("string")})}, "foo": Value("int64")}), ) as dset: with self._to(in_memory, tmp_dir, dset) as dset: fingerprint = dset._fingerprint with dset.flatten() as dset: self.assertListEqual(sorted(dset.column_names), ["a.b.c", "foo"]) self.assertListEqual(sorted(dset.features.keys()), ["a.b.c", "foo"]) self.assertDictEqual( dset.features, Features({"a.b.c": Sequence(Value("string")), "foo": Value("int64")}) ) self.assertNotEqual(dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset) with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict( {"a": [{"en": "Thank you", "fr": "Merci"}] * 10, "foo": [1] * 10}, features=Features({"a": Translation(languages=["en", "fr"]), "foo": Value("int64")}), ) as dset: with self._to(in_memory, tmp_dir, dset) as dset: fingerprint = dset._fingerprint with dset.flatten() as dset: self.assertListEqual(sorted(dset.column_names), ["a.en", "a.fr", "foo"]) self.assertListEqual(sorted(dset.features.keys()), ["a.en", "a.fr", "foo"]) self.assertDictEqual( dset.features, Features({"a.en": Value("string"), "a.fr": Value("string"), "foo": Value("int64")}), ) self.assertNotEqual(dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset) with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict( {"a": [{"en": "the cat", "fr": ["le chat", "la chatte"], "de": "die katze"}] * 10, "foo": [1] * 10}, features=Features( {"a": TranslationVariableLanguages(languages=["en", "fr", "de"]), "foo": Value("int64")} ), ) as dset: with self._to(in_memory, tmp_dir, dset) as dset: fingerprint = dset._fingerprint with dset.flatten() as dset: self.assertListEqual(sorted(dset.column_names), ["a.language", "a.translation", "foo"]) self.assertListEqual(sorted(dset.features.keys()), ["a.language", "a.translation", "foo"]) self.assertDictEqual( dset.features, Features( { "a.language": Sequence(Value("string")), "a.translation": Sequence(Value("string")), "foo": Value("int64"), } ), ) self.assertNotEqual(dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset) @require_pil def test_flatten_complex_image(self, in_memory): # decoding turned on with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict( {"a": [np.arange(4 * 4 * 3, dtype=np.uint8).reshape(4, 4, 3)] * 10, "foo": [1] * 10}, features=Features({"a": Image(), "foo": Value("int64")}), ) as dset: with self._to(in_memory, tmp_dir, dset) as dset: fingerprint = dset._fingerprint with dset.flatten() as dset: self.assertListEqual(sorted(dset.column_names), ["a", "foo"]) self.assertListEqual(sorted(dset.features.keys()), ["a", "foo"]) self.assertDictEqual(dset.features, Features({"a": Image(), "foo": Value("int64")})) self.assertNotEqual(dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset) # decoding turned on + nesting with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict( {"a": [{"b": np.arange(4 * 4 * 3, dtype=np.uint8).reshape(4, 4, 3)}] * 10, "foo": [1] * 10}, features=Features({"a": {"b": Image()}, "foo": Value("int64")}), ) as dset: with self._to(in_memory, tmp_dir, dset) as dset: fingerprint = dset._fingerprint with dset.flatten() as dset: self.assertListEqual(sorted(dset.column_names), ["a.b", "foo"]) self.assertListEqual(sorted(dset.features.keys()), ["a.b", "foo"]) self.assertDictEqual(dset.features, Features({"a.b": Image(), "foo": Value("int64")})) self.assertNotEqual(dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset) # decoding turned off with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict( {"a": [np.arange(4 * 4 * 3, dtype=np.uint8).reshape(4, 4, 3)] * 10, "foo": [1] * 10}, features=Features({"a": Image(decode=False), "foo": Value("int64")}), ) as dset: with self._to(in_memory, tmp_dir, dset) as dset: fingerprint = dset._fingerprint with dset.flatten() as dset: self.assertListEqual(sorted(dset.column_names), ["a.bytes", "a.path", "foo"]) self.assertListEqual(sorted(dset.features.keys()), ["a.bytes", "a.path", "foo"]) self.assertDictEqual( dset.features, Features({"a.bytes": Value("binary"), "a.path": Value("string"), "foo": Value("int64")}), ) self.assertNotEqual(dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset) # decoding turned off + nesting with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict( {"a": [{"b": np.arange(4 * 4 * 3, dtype=np.uint8).reshape(4, 4, 3)}] * 10, "foo": [1] * 10}, features=Features({"a": {"b": Image(decode=False)}, "foo": Value("int64")}), ) as dset: with self._to(in_memory, tmp_dir, dset) as dset: fingerprint = dset._fingerprint with dset.flatten() as dset: self.assertListEqual(sorted(dset.column_names), ["a.b.bytes", "a.b.path", "foo"]) self.assertListEqual(sorted(dset.features.keys()), ["a.b.bytes", "a.b.path", "foo"]) self.assertDictEqual( dset.features, Features( {"a.b.bytes": Value("binary"), "a.b.path": Value("string"), "foo": Value("int64")} ), ) self.assertNotEqual(dset._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset) def test_map(self, in_memory): # standard with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: self.assertDictEqual(dset.features, Features({"filename": Value("string")})) fingerprint = dset._fingerprint with dset.map( lambda x: {"name": x["filename"][:-2], "id": int(x["filename"].split("_")[-1])} ) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual( dset_test.features, Features({"filename": Value("string"), "name": Value("string"), "id": Value("int64")}), ) self.assertListEqual(dset_test["id"], list(range(30))) self.assertNotEqual(dset_test._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset_test) # no transform with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: fingerprint = dset._fingerprint with dset.map(lambda x: None) as dset_test: self.assertEqual(len(dset_test), 30) self.assertEqual(dset_test._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset_test) # with indices with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map( lambda x, i: {"name": x["filename"][:-2], "id": i}, with_indices=True ) as dset_test_with_indices: self.assertEqual(len(dset_test_with_indices), 30) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual( dset_test_with_indices.features, Features({"filename": Value("string"), "name": Value("string"), "id": Value("int64")}), ) self.assertListEqual(dset_test_with_indices["id"], list(range(30))) assert_arrow_metadata_are_synced_with_dataset_features(dset_test_with_indices) # interrupted with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: def func(x, i): if i == 4: raise KeyboardInterrupt() return {"name": x["filename"][:-2], "id": i} tmp_file = os.path.join(tmp_dir, "test.arrow") self.assertRaises( KeyboardInterrupt, dset.map, function=func, with_indices=True, cache_file_name=tmp_file, writer_batch_size=2, ) self.assertFalse(os.path.exists(tmp_file)) with dset.map( lambda x, i: {"name": x["filename"][:-2], "id": i}, with_indices=True, cache_file_name=tmp_file, writer_batch_size=2, ) as dset_test_with_indices: self.assertTrue(os.path.exists(tmp_file)) self.assertEqual(len(dset_test_with_indices), 30) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual( dset_test_with_indices.features, Features({"filename": Value("string"), "name": Value("string"), "id": Value("int64")}), ) self.assertListEqual(dset_test_with_indices["id"], list(range(30))) assert_arrow_metadata_are_synced_with_dataset_features(dset_test_with_indices) # formatted with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: dset.set_format("numpy", columns=["col_1"]) with dset.map(lambda x: {"col_1_plus_one": x["col_1"] + 1}) as dset_test: self.assertEqual(len(dset_test), 4) self.assertEqual(dset_test.format["type"], "numpy") self.assertIsInstance(dset_test["col_1"], np.ndarray) self.assertIsInstance(dset_test["col_1_plus_one"], np.ndarray) self.assertListEqual(sorted(dset_test[0].keys()), ["col_1", "col_1_plus_one"]) self.assertListEqual(sorted(dset_test.column_names), ["col_1", "col_1_plus_one", "col_2", "col_3"]) assert_arrow_metadata_are_synced_with_dataset_features(dset_test) def test_map_multiprocessing(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: # standard with self._create_dummy_dataset(in_memory, tmp_dir) as dset: self.assertDictEqual(dset.features, Features({"filename": Value("string")})) fingerprint = dset._fingerprint with dset.map(picklable_map_function, num_proc=2) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual( dset_test.features, Features({"filename": Value("string"), "id": Value("int64")}), ) self.assertEqual(len(dset_test.cache_files), 0 if in_memory else 2) if not in_memory: self.assertIn("_of_00002.arrow", dset_test.cache_files[0]["filename"]) self.assertListEqual(dset_test["id"], list(range(30))) self.assertNotEqual(dset_test._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset_test) with tempfile.TemporaryDirectory() as tmp_dir: # num_proc > num rows with self._create_dummy_dataset(in_memory, tmp_dir) as dset: self.assertDictEqual(dset.features, Features({"filename": Value("string")})) fingerprint = dset._fingerprint with dset.select([0, 1], keep_in_memory=True).map(picklable_map_function, num_proc=10) as dset_test: self.assertEqual(len(dset_test), 2) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual( dset_test.features, Features({"filename": Value("string"), "id": Value("int64")}), ) self.assertEqual(len(dset_test.cache_files), 0 if in_memory else 2) self.assertListEqual(dset_test["id"], list(range(2))) self.assertNotEqual(dset_test._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset_test) with tempfile.TemporaryDirectory() as tmp_dir: # with_indices with self._create_dummy_dataset(in_memory, tmp_dir) as dset: fingerprint = dset._fingerprint with dset.map(picklable_map_function_with_indices, num_proc=3, with_indices=True) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual( dset_test.features, Features({"filename": Value("string"), "id": Value("int64")}), ) self.assertEqual(len(dset_test.cache_files), 0 if in_memory else 3) self.assertListEqual(dset_test["id"], list(range(30))) self.assertNotEqual(dset_test._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset_test) with tempfile.TemporaryDirectory() as tmp_dir: # with_rank with self._create_dummy_dataset(in_memory, tmp_dir) as dset: fingerprint = dset._fingerprint with dset.map(picklable_map_function_with_rank, num_proc=3, with_rank=True) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual( dset_test.features, Features({"filename": Value("string"), "rank": Value("int64")}), ) self.assertEqual(len(dset_test.cache_files), 0 if in_memory else 3) self.assertListEqual(dset_test["rank"], [0] * 10 + [1] * 10 + [2] * 10) self.assertNotEqual(dset_test._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset_test) with tempfile.TemporaryDirectory() as tmp_dir: # with_indices AND with_rank with self._create_dummy_dataset(in_memory, tmp_dir) as dset: fingerprint = dset._fingerprint with dset.map( picklable_map_function_with_indices_and_rank, num_proc=3, with_indices=True, with_rank=True ) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual( dset_test.features, Features({"filename": Value("string"), "id": Value("int64"), "rank": Value("int64")}), ) self.assertEqual(len(dset_test.cache_files), 0 if in_memory else 3) self.assertListEqual(dset_test["id"], list(range(30))) self.assertListEqual(dset_test["rank"], [0] * 10 + [1] * 10 + [2] * 10) self.assertNotEqual(dset_test._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset_test) with tempfile.TemporaryDirectory() as tmp_dir: # new_fingerprint new_fingerprint = "foobar" invalid_new_fingerprint = "foobar/hey" with self._create_dummy_dataset(in_memory, tmp_dir) as dset: fingerprint = dset._fingerprint self.assertRaises( ValueError, dset.map, picklable_map_function, num_proc=2, new_fingerprint=invalid_new_fingerprint ) with dset.map(picklable_map_function, num_proc=2, new_fingerprint=new_fingerprint) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual( dset_test.features, Features({"filename": Value("string"), "id": Value("int64")}), ) self.assertEqual(len(dset_test.cache_files), 0 if in_memory else 2) self.assertListEqual(dset_test["id"], list(range(30))) self.assertNotEqual(dset_test._fingerprint, fingerprint) self.assertEqual(dset_test._fingerprint, new_fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset_test) file_names = sorted(Path(cache_file["filename"]).name for cache_file in dset_test.cache_files) for i, file_name in enumerate(file_names): self.assertIn(new_fingerprint + f"_{i:05d}", file_name) with tempfile.TemporaryDirectory() as tmp_dir: # lambda (requires multiprocess from pathos) with self._create_dummy_dataset(in_memory, tmp_dir) as dset: fingerprint = dset._fingerprint with dset.map(lambda x: {"id": int(x["filename"].split("_")[-1])}, num_proc=2) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual( dset_test.features, Features({"filename": Value("string"), "id": Value("int64")}), ) self.assertEqual(len(dset_test.cache_files), 0 if in_memory else 2) self.assertListEqual(dset_test["id"], list(range(30))) self.assertNotEqual(dset_test._fingerprint, fingerprint) assert_arrow_metadata_are_synced_with_dataset_features(dset_test) def test_map_new_features(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: features = Features({"filename": Value("string"), "label": ClassLabel(names=["positive", "negative"])}) with dset.map( lambda x, i: {"label": i % 2}, with_indices=True, features=features ) as dset_test_with_indices: self.assertEqual(len(dset_test_with_indices), 30) self.assertDictEqual( dset_test_with_indices.features, features, ) assert_arrow_metadata_are_synced_with_dataset_features(dset_test_with_indices) def test_map_batched(self, in_memory): def map_batched(example): return {"filename_new": [x + "_extension" for x in example["filename"]]} with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map(map_batched, batched=True) as dset_test_batched: self.assertEqual(len(dset_test_batched), 30) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual( dset_test_batched.features, Features({"filename": Value("string"), "filename_new": Value("string")}), ) assert_arrow_metadata_are_synced_with_dataset_features(dset_test_batched) # change batch size and drop the last batch with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: batch_size = 4 with dset.map( map_batched, batched=True, batch_size=batch_size, drop_last_batch=True ) as dset_test_batched: self.assertEqual(len(dset_test_batched), 30 // batch_size * batch_size) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual( dset_test_batched.features, Features({"filename": Value("string"), "filename_new": Value("string")}), ) assert_arrow_metadata_are_synced_with_dataset_features(dset_test_batched) with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.formatted_as("numpy", columns=["filename"]): with dset.map(map_batched, batched=True) as dset_test_batched: self.assertEqual(len(dset_test_batched), 30) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual( dset_test_batched.features, Features({"filename": Value("string"), "filename_new": Value("string")}), ) assert_arrow_metadata_are_synced_with_dataset_features(dset_test_batched) def map_batched_with_indices(example, idx): return {"filename_new": [x + "_extension_" + str(idx) for x in example["filename"]]} with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map( map_batched_with_indices, batched=True, with_indices=True ) as dset_test_with_indices_batched: self.assertEqual(len(dset_test_with_indices_batched), 30) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual( dset_test_with_indices_batched.features, Features({"filename": Value("string"), "filename_new": Value("string")}), ) assert_arrow_metadata_are_synced_with_dataset_features(dset_test_with_indices_batched) # check remove columns for even if the function modifies input in-place def map_batched_modifying_inputs_inplace(example): result = {"filename_new": [x + "_extension" for x in example["filename"]]} del example["filename"] return result with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map( map_batched_modifying_inputs_inplace, batched=True, remove_columns="filename" ) as dset_test_modifying_inputs_inplace: self.assertEqual(len(dset_test_modifying_inputs_inplace), 30) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual( dset_test_modifying_inputs_inplace.features, Features({"filename_new": Value("string")}), ) assert_arrow_metadata_are_synced_with_dataset_features(dset_test_modifying_inputs_inplace) def test_map_nested(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict({"field": ["a", "b"]}) as dset: with self._to(in_memory, tmp_dir, dset) as dset: with dset.map(lambda example: {"otherfield": {"capital": example["field"].capitalize()}}) as dset: with dset.map(lambda example: {"otherfield": {"append_x": example["field"] + "x"}}) as dset: self.assertEqual(dset[0], {"field": "a", "otherfield": {"append_x": "ax"}}) def test_map_return_example_as_dict_value(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict({"en": ["aa", "bb"], "fr": ["cc", "dd"]}) as dset: with self._to(in_memory, tmp_dir, dset) as dset: with dset.map(lambda example: {"translation": example}) as dset: self.assertEqual(dset[0], {"en": "aa", "fr": "cc", "translation": {"en": "aa", "fr": "cc"}}) def test_map_fn_kwargs(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict({"id": range(10)}) as dset: with self._to(in_memory, tmp_dir, dset) as dset: fn_kwargs = {"offset": 3} with dset.map( lambda example, offset: {"id+offset": example["id"] + offset}, fn_kwargs=fn_kwargs ) as mapped_dset: assert mapped_dset["id+offset"] == list(range(3, 13)) with dset.map( lambda id, offset: {"id+offset": id + offset}, fn_kwargs=fn_kwargs, input_columns="id" ) as mapped_dset: assert mapped_dset["id+offset"] == list(range(3, 13)) with dset.map( lambda id, i, offset: {"id+offset": i + offset}, fn_kwargs=fn_kwargs, input_columns="id", with_indices=True, ) as mapped_dset: assert mapped_dset["id+offset"] == list(range(3, 13)) def test_map_caching(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: self._caplog.clear() with self._caplog.at_level(INFO, logger=get_logger().name): with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with patch( "datasets.arrow_dataset.Dataset._map_single", autospec=Dataset._map_single, side_effect=Dataset._map_single, ) as mock_map_single: with dset.map(lambda x: {"foo": "bar"}) as dset_test1: dset_test1_data_files = list(dset_test1.cache_files) self.assertEqual(mock_map_single.call_count, 1) with dset.map(lambda x: {"foo": "bar"}) as dset_test2: self.assertEqual(dset_test1_data_files, dset_test2.cache_files) self.assertEqual(len(dset_test2.cache_files), 1 - int(in_memory)) self.assertTrue(("Loading cached processed dataset" in self._caplog.text) ^ in_memory) self.assertEqual(mock_map_single.call_count, 2 if in_memory else 1) with tempfile.TemporaryDirectory() as tmp_dir: self._caplog.clear() with self._caplog.at_level(INFO, logger=get_logger().name): with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map(lambda x: {"foo": "bar"}) as dset_test1: dset_test1_data_files = list(dset_test1.cache_files) with dset.map(lambda x: {"foo": "bar"}, load_from_cache_file=False) as dset_test2: self.assertEqual(dset_test1_data_files, dset_test2.cache_files) self.assertEqual(len(dset_test2.cache_files), 1 - int(in_memory)) self.assertNotIn("Loading cached processed dataset", self._caplog.text) with tempfile.TemporaryDirectory() as tmp_dir: self._caplog.clear() with self._caplog.at_level(INFO, logger=get_logger().name): with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with patch( "datasets.arrow_dataset.Pool", new_callable=PickableMagicMock, side_effect=datasets.arrow_dataset.Pool, ) as mock_pool: with dset.map(lambda x: {"foo": "bar"}, num_proc=2) as dset_test1: dset_test1_data_files = list(dset_test1.cache_files) self.assertEqual(mock_pool.call_count, 1) with dset.map(lambda x: {"foo": "bar"}, num_proc=2) as dset_test2: self.assertEqual(dset_test1_data_files, dset_test2.cache_files) self.assertTrue( (len(re.findall("Loading cached processed dataset", self._caplog.text)) == 1) ^ in_memory ) self.assertEqual(mock_pool.call_count, 2 if in_memory else 1) with tempfile.TemporaryDirectory() as tmp_dir: self._caplog.clear() with self._caplog.at_level(INFO, logger=get_logger().name): with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map(lambda x: {"foo": "bar"}, num_proc=2) as dset_test1: dset_test1_data_files = list(dset_test1.cache_files) with dset.map(lambda x: {"foo": "bar"}, num_proc=2, load_from_cache_file=False) as dset_test2: self.assertEqual(dset_test1_data_files, dset_test2.cache_files) self.assertEqual(len(dset_test2.cache_files), (1 - int(in_memory)) * 2) self.assertNotIn("Loading cached processed dataset", self._caplog.text) if not in_memory: try: self._caplog.clear() with tempfile.TemporaryDirectory() as tmp_dir: with self._caplog.at_level(INFO, logger=get_logger().name): with self._create_dummy_dataset(in_memory, tmp_dir) as dset: datasets.disable_caching() with dset.map(lambda x: {"foo": "bar"}) as dset_test1: with dset.map(lambda x: {"foo": "bar"}) as dset_test2: self.assertNotEqual(dset_test1.cache_files, dset_test2.cache_files) self.assertEqual(len(dset_test1.cache_files), 1) self.assertEqual(len(dset_test2.cache_files), 1) self.assertNotIn("Loading cached processed dataset", self._caplog.text) # make sure the arrow files are going to be removed self.assertIn("tmp", dset_test1.cache_files[0]["filename"]) self.assertIn("tmp", dset_test2.cache_files[0]["filename"]) finally: datasets.enable_caching() def test_map_return_pa_table(self, in_memory): def func_return_single_row_pa_table(x): return pa.table({"id": [0], "text": ["a"]}) with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map(func_return_single_row_pa_table) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual( dset_test.features, Features({"id": Value("int64"), "text": Value("string")}), ) self.assertEqual(dset_test[0]["id"], 0) self.assertEqual(dset_test[0]["text"], "a") # Batched def func_return_single_row_pa_table_batched(x): batch_size = len(x[next(iter(x))]) return pa.table({"id": [0] * batch_size, "text": ["a"] * batch_size}) with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map(func_return_single_row_pa_table_batched, batched=True) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual( dset_test.features, Features({"id": Value("int64"), "text": Value("string")}), ) self.assertEqual(dset_test[0]["id"], 0) self.assertEqual(dset_test[0]["text"], "a") # Error when returning a table with more than one row in the non-batched mode def func_return_multi_row_pa_table(x): return pa.table({"id": [0, 1], "text": ["a", "b"]}) with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: self.assertRaises(ValueError, dset.map, func_return_multi_row_pa_table) def test_map_return_pd_dataframe(self, in_memory): def func_return_single_row_pd_dataframe(x): return pd.DataFrame({"id": [0], "text": ["a"]}) with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map(func_return_single_row_pd_dataframe) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual( dset_test.features, Features({"id": Value("int64"), "text": Value("string")}), ) self.assertEqual(dset_test[0]["id"], 0) self.assertEqual(dset_test[0]["text"], "a") # Batched def func_return_single_row_pd_dataframe_batched(x): batch_size = len(x[next(iter(x))]) return pd.DataFrame({"id": [0] * batch_size, "text": ["a"] * batch_size}) with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map(func_return_single_row_pd_dataframe_batched, batched=True) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual( dset_test.features, Features({"id": Value("int64"), "text": Value("string")}), ) self.assertEqual(dset_test[0]["id"], 0) self.assertEqual(dset_test[0]["text"], "a") # Error when returning a table with more than one row in the non-batched mode def func_return_multi_row_pd_dataframe(x): return pd.DataFrame({"id": [0, 1], "text": ["a", "b"]}) with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: self.assertRaises(ValueError, dset.map, func_return_multi_row_pd_dataframe) @require_torch def test_map_torch(self, in_memory): import torch def func(example): return {"tensor": torch.tensor([1.0, 2, 3])} with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map(func) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual( dset_test.features, Features({"filename": Value("string"), "tensor": Sequence(Value("float32"))}), ) self.assertListEqual(dset_test[0]["tensor"], [1, 2, 3]) @require_tf def test_map_tf(self, in_memory): import tensorflow as tf def func(example): return {"tensor": tf.constant([1.0, 2, 3])} with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map(func) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual( dset_test.features, Features({"filename": Value("string"), "tensor": Sequence(Value("float32"))}), ) self.assertListEqual(dset_test[0]["tensor"], [1, 2, 3]) @require_jax def test_map_jax(self, in_memory): import jax.numpy as jnp def func(example): return {"tensor": jnp.asarray([1.0, 2, 3])} with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map(func) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual( dset_test.features, Features({"filename": Value("string"), "tensor": Sequence(Value("float32"))}), ) self.assertListEqual(dset_test[0]["tensor"], [1, 2, 3]) def test_map_numpy(self, in_memory): def func(example): return {"tensor": np.array([1.0, 2, 3])} with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map(func) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual( dset_test.features, Features({"filename": Value("string"), "tensor": Sequence(Value("float64"))}), ) self.assertListEqual(dset_test[0]["tensor"], [1, 2, 3]) @require_torch def test_map_tensor_batched(self, in_memory): import torch def func(batch): return {"tensor": torch.tensor([[1.0, 2, 3]] * len(batch["filename"]))} with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map(func, batched=True) as dset_test: self.assertEqual(len(dset_test), 30) self.assertDictEqual( dset_test.features, Features({"filename": Value("string"), "tensor": Sequence(Value("float32"))}), ) self.assertListEqual(dset_test[0]["tensor"], [1, 2, 3]) def test_map_input_columns(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: with dset.map(lambda col_1: {"label": col_1 % 2}, input_columns="col_1") as mapped_dset: self.assertEqual(mapped_dset[0].keys(), {"col_1", "col_2", "col_3", "label"}) self.assertEqual( mapped_dset.features, Features( { "col_1": Value("int64"), "col_2": Value("string"), "col_3": Value("bool"), "label": Value("int64"), } ), ) def test_map_remove_columns(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.map(lambda x, i: {"name": x["filename"][:-2], "id": i}, with_indices=True) as dset: self.assertTrue("id" in dset[0]) self.assertDictEqual( dset.features, Features({"filename": Value("string"), "name": Value("string"), "id": Value("int64")}), ) assert_arrow_metadata_are_synced_with_dataset_features(dset) with dset.map(lambda x: x, remove_columns=["id"]) as mapped_dset: self.assertTrue("id" not in mapped_dset[0]) self.assertDictEqual( mapped_dset.features, Features({"filename": Value("string"), "name": Value("string")}) ) assert_arrow_metadata_are_synced_with_dataset_features(mapped_dset) with mapped_dset.with_format("numpy", columns=mapped_dset.column_names) as mapped_dset: with mapped_dset.map( lambda x: {"name": 1}, remove_columns=mapped_dset.column_names ) as mapped_dset: self.assertTrue("filename" not in mapped_dset[0]) self.assertTrue("name" in mapped_dset[0]) self.assertDictEqual(mapped_dset.features, Features({"name": Value(dtype="int64")})) assert_arrow_metadata_are_synced_with_dataset_features(mapped_dset) # empty dataset columns_names = dset.column_names with dset.select([]) as empty_dset: self.assertEqual(len(empty_dset), 0) with empty_dset.map(lambda x: {}, remove_columns=columns_names[0]) as mapped_dset: self.assertListEqual(columns_names[1:], mapped_dset.column_names) assert_arrow_metadata_are_synced_with_dataset_features(mapped_dset) def test_map_stateful_callable(self, in_memory): # be sure that the state of the map callable is unaffected # before processing the dataset examples class ExampleCounter: def __init__(self, batched=False): self.batched = batched # state self.cnt = 0 def __call__(self, example): if self.batched: self.cnt += len(example) else: self.cnt += 1 with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: ex_cnt = ExampleCounter() dset.map(ex_cnt) self.assertEqual(ex_cnt.cnt, len(dset)) ex_cnt = ExampleCounter(batched=True) dset.map(ex_cnt) self.assertEqual(ex_cnt.cnt, len(dset)) @require_not_windows def test_map_crash_subprocess(self, in_memory): # be sure that a crash in one of the subprocess will not # hang dataset.map() call forever def do_crash(row): import os os.kill(os.getpid(), 9) return row with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with pytest.raises(RuntimeError) as excinfo: dset.map(do_crash, num_proc=2) assert str(excinfo.value) == ( "One of the subprocesses has abruptly died during map operation." "To debug the error, disable multiprocessing." ) def test_filter(self, in_memory): # keep only first five examples with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: fingerprint = dset._fingerprint with dset.filter(lambda x, i: i < 5, with_indices=True) as dset_filter_first_five: self.assertEqual(len(dset_filter_first_five), 5) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_filter_first_five.features, Features({"filename": Value("string")})) self.assertNotEqual(dset_filter_first_five._fingerprint, fingerprint) # filter filenames with even id at the end + formatted with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: dset.set_format("numpy") fingerprint = dset._fingerprint with dset.filter(lambda x: (int(x["filename"][-1]) % 2 == 0)) as dset_filter_even_num: self.assertEqual(len(dset_filter_even_num), 15) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_filter_even_num.features, Features({"filename": Value("string")})) self.assertNotEqual(dset_filter_even_num._fingerprint, fingerprint) self.assertEqual(dset_filter_even_num.format["type"], "numpy") def test_filter_with_indices_mapping(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: dset = Dataset.from_dict({"col": [0, 1, 2]}) with self._to(in_memory, tmp_dir, dset) as dset: with dset.filter(lambda x: x["col"] > 0) as dset: self.assertListEqual(dset["col"], [1, 2]) with dset.filter(lambda x: x["col"] < 2) as dset: self.assertListEqual(dset["col"], [1]) def test_filter_empty(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: self.assertIsNone(dset._indices, None) tmp_file = os.path.join(tmp_dir, "test.arrow") with dset.filter(lambda _: False, cache_file_name=tmp_file) as dset: self.assertEqual(len(dset), 0) self.assertIsNotNone(dset._indices, None) tmp_file_2 = os.path.join(tmp_dir, "test_2.arrow") with dset.filter(lambda _: False, cache_file_name=tmp_file_2) as dset2: self.assertEqual(len(dset2), 0) self.assertEqual(dset._indices, dset2._indices) def test_filter_batched(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: dset = Dataset.from_dict({"col": [0, 1, 2]}) with self._to(in_memory, tmp_dir, dset) as dset: with dset.filter(lambda x: [i > 0 for i in x["col"]], batched=True) as dset: self.assertListEqual(dset["col"], [1, 2]) with dset.filter(lambda x: [i < 2 for i in x["col"]], batched=True) as dset: self.assertListEqual(dset["col"], [1]) def test_filter_input_columns(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: dset = Dataset.from_dict({"col_1": [0, 1, 2], "col_2": ["a", "b", "c"]}) with self._to(in_memory, tmp_dir, dset) as dset: with dset.filter(lambda x: x > 0, input_columns=["col_1"]) as filtered_dset: self.assertListEqual(filtered_dset.column_names, dset.column_names) self.assertListEqual(filtered_dset["col_1"], [1, 2]) self.assertListEqual(filtered_dset["col_2"], ["b", "c"]) def test_filter_fn_kwargs(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict({"id": range(10)}) as dset: with self._to(in_memory, tmp_dir, dset) as dset: fn_kwargs = {"max_offset": 3} with dset.filter( lambda example, max_offset: example["id"] < max_offset, fn_kwargs=fn_kwargs ) as filtered_dset: assert len(filtered_dset) == 3 with dset.filter( lambda id, max_offset: id < max_offset, fn_kwargs=fn_kwargs, input_columns="id" ) as filtered_dset: assert len(filtered_dset) == 3 with dset.filter( lambda id, i, max_offset: i < max_offset, fn_kwargs=fn_kwargs, input_columns="id", with_indices=True, ) as filtered_dset: assert len(filtered_dset) == 3 def test_filter_multiprocessing(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: fingerprint = dset._fingerprint with dset.filter(picklable_filter_function, num_proc=2) as dset_filter_first_ten: self.assertEqual(len(dset_filter_first_ten), 10) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_filter_first_ten.features, Features({"filename": Value("string")})) self.assertEqual(len(dset_filter_first_ten.cache_files), 0 if in_memory else 2) self.assertNotEqual(dset_filter_first_ten._fingerprint, fingerprint) def test_filter_caching(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: self._caplog.clear() with self._caplog.at_level(INFO, logger=get_logger().name): with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.filter(lambda x, i: i < 5, with_indices=True) as dset_filter_first_five1: dset_test1_data_files = list(dset_filter_first_five1.cache_files) with dset.filter(lambda x, i: i < 5, with_indices=True) as dset_filter_first_five2: self.assertEqual(dset_test1_data_files, dset_filter_first_five2.cache_files) self.assertEqual(len(dset_filter_first_five2.cache_files), 0 if in_memory else 2) self.assertTrue(("Loading cached processed dataset" in self._caplog.text) ^ in_memory) def test_keep_features_after_transform_specified(self, in_memory): features = Features( {"tokens": Sequence(Value("string")), "labels": Sequence(ClassLabel(names=["negative", "positive"]))} ) def invert_labels(x): return {"labels": [(1 - label) for label in x["labels"]]} with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict( {"tokens": [["foo"] * 5] * 10, "labels": [[1] * 5] * 10}, features=features ) as dset: with self._to(in_memory, tmp_dir, dset) as dset: with dset.map(invert_labels, features=features) as inverted_dset: self.assertEqual(inverted_dset.features.type, features.type) self.assertDictEqual(inverted_dset.features, features) assert_arrow_metadata_are_synced_with_dataset_features(inverted_dset) def test_keep_features_after_transform_unspecified(self, in_memory): features = Features( {"tokens": Sequence(Value("string")), "labels": Sequence(ClassLabel(names=["negative", "positive"]))} ) def invert_labels(x): return {"labels": [(1 - label) for label in x["labels"]]} with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict( {"tokens": [["foo"] * 5] * 10, "labels": [[1] * 5] * 10}, features=features ) as dset: with self._to(in_memory, tmp_dir, dset) as dset: with dset.map(invert_labels) as inverted_dset: self.assertEqual(inverted_dset.features.type, features.type) self.assertDictEqual(inverted_dset.features, features) assert_arrow_metadata_are_synced_with_dataset_features(inverted_dset) def test_keep_features_after_transform_to_file(self, in_memory): features = Features( {"tokens": Sequence(Value("string")), "labels": Sequence(ClassLabel(names=["negative", "positive"]))} ) def invert_labels(x): return {"labels": [(1 - label) for label in x["labels"]]} with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict( {"tokens": [["foo"] * 5] * 10, "labels": [[1] * 5] * 10}, features=features ) as dset: with self._to(in_memory, tmp_dir, dset) as dset: tmp_file = os.path.join(tmp_dir, "test.arrow") dset.map(invert_labels, cache_file_name=tmp_file) with Dataset.from_file(tmp_file) as inverted_dset: self.assertEqual(inverted_dset.features.type, features.type) self.assertDictEqual(inverted_dset.features, features) def test_keep_features_after_transform_to_memory(self, in_memory): features = Features( {"tokens": Sequence(Value("string")), "labels": Sequence(ClassLabel(names=["negative", "positive"]))} ) def invert_labels(x): return {"labels": [(1 - label) for label in x["labels"]]} with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict( {"tokens": [["foo"] * 5] * 10, "labels": [[1] * 5] * 10}, features=features ) as dset: with self._to(in_memory, tmp_dir, dset) as dset: with dset.map(invert_labels, keep_in_memory=True) as inverted_dset: self.assertEqual(inverted_dset.features.type, features.type) self.assertDictEqual(inverted_dset.features, features) def test_keep_features_after_loading_from_cache(self, in_memory): features = Features( {"tokens": Sequence(Value("string")), "labels": Sequence(ClassLabel(names=["negative", "positive"]))} ) def invert_labels(x): return {"labels": [(1 - label) for label in x["labels"]]} with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict( {"tokens": [["foo"] * 5] * 10, "labels": [[1] * 5] * 10}, features=features ) as dset: with self._to(in_memory, tmp_dir, dset) as dset: tmp_file1 = os.path.join(tmp_dir, "test1.arrow") tmp_file2 = os.path.join(tmp_dir, "test2.arrow") # TODO: Why mapped twice? inverted_dset = dset.map(invert_labels, cache_file_name=tmp_file1) inverted_dset = dset.map(invert_labels, cache_file_name=tmp_file2) self.assertGreater(len(inverted_dset.cache_files), 0) self.assertEqual(inverted_dset.features.type, features.type) self.assertDictEqual(inverted_dset.features, features) del inverted_dset def test_keep_features_with_new_features(self, in_memory): features = Features( {"tokens": Sequence(Value("string")), "labels": Sequence(ClassLabel(names=["negative", "positive"]))} ) def invert_labels(x): return {"labels": [(1 - label) for label in x["labels"]], "labels2": x["labels"]} expected_features = Features( { "tokens": Sequence(Value("string")), "labels": Sequence(ClassLabel(names=["negative", "positive"])), "labels2": Sequence(Value("int64")), } ) with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict( {"tokens": [["foo"] * 5] * 10, "labels": [[1] * 5] * 10}, features=features ) as dset: with self._to(in_memory, tmp_dir, dset) as dset: with dset.map(invert_labels) as inverted_dset: self.assertEqual(inverted_dset.features.type, expected_features.type) self.assertDictEqual(inverted_dset.features, expected_features) assert_arrow_metadata_are_synced_with_dataset_features(inverted_dset) def test_select(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: # select every two example indices = list(range(0, len(dset), 2)) tmp_file = os.path.join(tmp_dir, "test.arrow") fingerprint = dset._fingerprint with dset.select(indices, indices_cache_file_name=tmp_file) as dset_select_even: self.assertIsNotNone(dset_select_even._indices) # an indices mapping is created self.assertTrue(os.path.exists(tmp_file)) self.assertEqual(len(dset_select_even), 15) for row in dset_select_even: self.assertEqual(int(row["filename"][-1]) % 2, 0) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_select_even.features, Features({"filename": Value("string")})) self.assertNotEqual(dset_select_even._fingerprint, fingerprint) with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: indices = list(range(0, len(dset))) with dset.select(indices) as dset_select_all: # no indices mapping, since the indices are contiguous # (in this case the arrow table is simply sliced, which is more efficient) self.assertIsNone(dset_select_all._indices) self.assertEqual(len(dset_select_all), len(dset)) self.assertListEqual(list(dset_select_all), list(dset)) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_select_all.features, Features({"filename": Value("string")})) self.assertNotEqual(dset_select_all._fingerprint, fingerprint) indices = range(0, len(dset)) with dset.select(indices) as dset_select_all: # same but with range self.assertIsNone(dset_select_all._indices) self.assertEqual(len(dset_select_all), len(dset)) self.assertListEqual(list(dset_select_all), list(dset)) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_select_all.features, Features({"filename": Value("string")})) self.assertNotEqual(dset_select_all._fingerprint, fingerprint) with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: bad_indices = list(range(5)) bad_indices[-1] = len(dset) + 10 # out of bounds tmp_file = os.path.join(tmp_dir, "test.arrow") self.assertRaises( Exception, dset.select, indices=bad_indices, indices_cache_file_name=tmp_file, writer_batch_size=2, ) self.assertFalse(os.path.exists(tmp_file)) with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: indices = iter(range(len(dset))) # iterator of contiguous indices with dset.select(indices) as dset_select_all: # no indices mapping, since the indices are contiguous self.assertIsNone(dset_select_all._indices) self.assertEqual(len(dset_select_all), len(dset)) indices = reversed(range(len(dset))) # iterator of not contiguous indices tmp_file = os.path.join(tmp_dir, "test.arrow") with dset.select(indices, indices_cache_file_name=tmp_file) as dset_select_all: # new indices mapping, since the indices are not contiguous self.assertIsNotNone(dset_select_all._indices) self.assertEqual(len(dset_select_all), len(dset)) with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: bad_indices = list(range(5)) bad_indices[3] = "foo" # wrong type tmp_file = os.path.join(tmp_dir, "test.arrow") self.assertRaises( Exception, dset.select, indices=bad_indices, indices_cache_file_name=tmp_file, writer_batch_size=2, ) self.assertFalse(os.path.exists(tmp_file)) dset.set_format("numpy") with dset.select( range(5), indices_cache_file_name=tmp_file, writer_batch_size=2, ) as dset_select_five: self.assertIsNone(dset_select_five._indices) self.assertEqual(len(dset_select_five), 5) self.assertEqual(dset_select_five.format["type"], "numpy") for i, row in enumerate(dset_select_five): self.assertEqual(int(row["filename"][-1]), i) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_select_five.features, Features({"filename": Value("string")})) def test_select_then_map(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.select([0]) as d1: with d1.map(lambda x: {"id": int(x["filename"].split("_")[-1])}) as d1: self.assertEqual(d1[0]["id"], 0) with dset.select([1]) as d2: with d2.map(lambda x: {"id": int(x["filename"].split("_")[-1])}) as d2: self.assertEqual(d2[0]["id"], 1) with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: with dset.select([0], indices_cache_file_name=os.path.join(tmp_dir, "i1.arrow")) as d1: with d1.map(lambda x: {"id": int(x["filename"].split("_")[-1])}) as d1: self.assertEqual(d1[0]["id"], 0) with dset.select([1], indices_cache_file_name=os.path.join(tmp_dir, "i2.arrow")) as d2: with d2.map(lambda x: {"id": int(x["filename"].split("_")[-1])}) as d2: self.assertEqual(d2[0]["id"], 1) def test_pickle_after_many_transforms_on_disk(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: self.assertEqual(len(dset.cache_files), 0 if in_memory else 1) with dset.rename_column("filename", "file") as dset: self.assertListEqual(dset.column_names, ["file"]) with dset.select(range(5)) as dset: self.assertEqual(len(dset), 5) with dset.map(lambda x: {"id": int(x["file"][-1])}) as dset: self.assertListEqual(sorted(dset.column_names), ["file", "id"]) with dset.rename_column("id", "number") as dset: self.assertListEqual(sorted(dset.column_names), ["file", "number"]) with dset.select([1, 0]) as dset: self.assertEqual(dset[0]["file"], "my_name-train_1") self.assertEqual(dset[0]["number"], 1) self.assertEqual(dset._indices["indices"].to_pylist(), [1, 0]) if not in_memory: self.assertIn( ("rename_columns", (["file", "number"],), {}), dset._data.replays, ) if not in_memory: dset._data.table = Unpicklable() # check that we don't pickle the entire table pickled = pickle.dumps(dset) with pickle.loads(pickled) as loaded: self.assertEqual(loaded[0]["file"], "my_name-train_1") self.assertEqual(loaded[0]["number"], 1) def test_shuffle(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: tmp_file = os.path.join(tmp_dir, "test.arrow") fingerprint = dset._fingerprint with dset.shuffle(seed=1234, keep_in_memory=True) as dset_shuffled: self.assertEqual(len(dset_shuffled), 30) self.assertEqual(dset_shuffled[0]["filename"], "my_name-train_28") self.assertEqual(dset_shuffled[2]["filename"], "my_name-train_10") self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_shuffled.features, Features({"filename": Value("string")})) self.assertNotEqual(dset_shuffled._fingerprint, fingerprint) with dset.shuffle(seed=1234, indices_cache_file_name=tmp_file) as dset_shuffled: self.assertEqual(len(dset_shuffled), 30) self.assertEqual(dset_shuffled[0]["filename"], "my_name-train_28") self.assertEqual(dset_shuffled[2]["filename"], "my_name-train_10") self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_shuffled.features, Features({"filename": Value("string")})) self.assertNotEqual(dset_shuffled._fingerprint, fingerprint) # Reproducibility tmp_file = os.path.join(tmp_dir, "test_2.arrow") with dset.shuffle(seed=1234, indices_cache_file_name=tmp_file) as dset_shuffled_2: self.assertListEqual(dset_shuffled["filename"], dset_shuffled_2["filename"]) # Compatible with temp_seed with temp_seed(42), dset.shuffle() as d1: with temp_seed(42), dset.shuffle() as d2, dset.shuffle() as d3: self.assertListEqual(d1["filename"], d2["filename"]) self.assertEqual(d1._fingerprint, d2._fingerprint) self.assertNotEqual(d3["filename"], d2["filename"]) self.assertNotEqual(d3._fingerprint, d2._fingerprint) def test_sort(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: # Sort on a single key with self._create_dummy_dataset(in_memory=in_memory, tmp_dir=tmp_dir) as dset: # Keep only 10 examples tmp_file = os.path.join(tmp_dir, "test.arrow") with dset.select(range(10), indices_cache_file_name=tmp_file) as dset: tmp_file = os.path.join(tmp_dir, "test_2.arrow") with dset.shuffle(seed=1234, indices_cache_file_name=tmp_file) as dset: self.assertEqual(len(dset), 10) self.assertEqual(dset[0]["filename"], "my_name-train_8") self.assertEqual(dset[1]["filename"], "my_name-train_9") # Sort tmp_file = os.path.join(tmp_dir, "test_3.arrow") fingerprint = dset._fingerprint with dset.sort("filename", indices_cache_file_name=tmp_file) as dset_sorted: for i, row in enumerate(dset_sorted): self.assertEqual(int(row["filename"][-1]), i) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_sorted.features, Features({"filename": Value("string")})) self.assertNotEqual(dset_sorted._fingerprint, fingerprint) # Sort reversed tmp_file = os.path.join(tmp_dir, "test_4.arrow") fingerprint = dset._fingerprint with dset.sort("filename", indices_cache_file_name=tmp_file, reverse=True) as dset_sorted: for i, row in enumerate(dset_sorted): self.assertEqual(int(row["filename"][-1]), len(dset_sorted) - 1 - i) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_sorted.features, Features({"filename": Value("string")})) self.assertNotEqual(dset_sorted._fingerprint, fingerprint) # formatted dset.set_format("numpy") with dset.sort("filename") as dset_sorted_formatted: self.assertEqual(dset_sorted_formatted.format["type"], "numpy") # Sort on multiple keys with self._create_dummy_dataset(in_memory=in_memory, tmp_dir=tmp_dir, multiple_columns=True) as dset: tmp_file = os.path.join(tmp_dir, "test_5.arrow") fingerprint = dset._fingerprint # Throw error when reverse is a list of bools that does not match the length of column_names with pytest.raises(ValueError): dset.sort(["col_1", "col_2", "col_3"], reverse=[False]) with dset.shuffle(seed=1234, indices_cache_file_name=tmp_file) as dset: # Sort with dset.sort(["col_1", "col_2", "col_3"], reverse=[False, True, False]) as dset_sorted: for i, row in enumerate(dset_sorted): self.assertEqual(row["col_1"], i) self.assertDictEqual( dset.features, Features( { "col_1": Value("int64"), "col_2": Value("string"), "col_3": Value("bool"), } ), ) self.assertDictEqual( dset_sorted.features, Features( { "col_1": Value("int64"), "col_2": Value("string"), "col_3": Value("bool"), } ), ) self.assertNotEqual(dset_sorted._fingerprint, fingerprint) # Sort reversed with dset.sort(["col_1", "col_2", "col_3"], reverse=[True, False, True]) as dset_sorted: for i, row in enumerate(dset_sorted): self.assertEqual(row["col_1"], len(dset_sorted) - 1 - i) self.assertDictEqual( dset.features, Features( { "col_1": Value("int64"), "col_2": Value("string"), "col_3": Value("bool"), } ), ) self.assertDictEqual( dset_sorted.features, Features( { "col_1": Value("int64"), "col_2": Value("string"), "col_3": Value("bool"), } ), ) self.assertNotEqual(dset_sorted._fingerprint, fingerprint) # formatted dset.set_format("numpy") with dset.sort( ["col_1", "col_2", "col_3"], reverse=[False, True, False] ) as dset_sorted_formatted: self.assertEqual(dset_sorted_formatted.format["type"], "numpy") @require_tf def test_export(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: # Export the data tfrecord_path = os.path.join(tmp_dir, "test.tfrecord") with dset.map( lambda ex, i: { "id": i, "question": f"Question {i}", "answers": {"text": [f"Answer {i}-0", f"Answer {i}-1"], "answer_start": [0, 1]}, }, with_indices=True, remove_columns=["filename"], ) as formatted_dset: with formatted_dset.flatten() as formatted_dset: formatted_dset.set_format("numpy") formatted_dset.export(filename=tfrecord_path, format="tfrecord") # Import the data import tensorflow as tf tf_dset = tf.data.TFRecordDataset([tfrecord_path]) feature_description = { "id": tf.io.FixedLenFeature([], tf.int64), "question": tf.io.FixedLenFeature([], tf.string), "answers.text": tf.io.VarLenFeature(tf.string), "answers.answer_start": tf.io.VarLenFeature(tf.int64), } tf_parsed_dset = tf_dset.map( lambda example_proto: tf.io.parse_single_example(example_proto, feature_description) ) # Test that keys match original dataset for i, ex in enumerate(tf_parsed_dset): self.assertEqual(ex.keys(), formatted_dset[i].keys()) # Test for equal number of elements self.assertEqual(i, len(formatted_dset) - 1) def test_to_csv(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: # File path argument with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: file_path = os.path.join(tmp_dir, "test_path.csv") bytes_written = dset.to_csv(path_or_buf=file_path) self.assertTrue(os.path.isfile(file_path)) self.assertEqual(bytes_written, os.path.getsize(file_path)) csv_dset = pd.read_csv(file_path) self.assertEqual(csv_dset.shape, dset.shape) self.assertListEqual(list(csv_dset.columns), list(dset.column_names)) # File buffer argument with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: file_path = os.path.join(tmp_dir, "test_buffer.csv") with open(file_path, "wb+") as buffer: bytes_written = dset.to_csv(path_or_buf=buffer) self.assertTrue(os.path.isfile(file_path)) self.assertEqual(bytes_written, os.path.getsize(file_path)) csv_dset = pd.read_csv(file_path) self.assertEqual(csv_dset.shape, dset.shape) self.assertListEqual(list(csv_dset.columns), list(dset.column_names)) # After a select/shuffle transform with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: dset = dset.select(range(0, len(dset), 2)).shuffle() file_path = os.path.join(tmp_dir, "test_path.csv") bytes_written = dset.to_csv(path_or_buf=file_path) self.assertTrue(os.path.isfile(file_path)) self.assertEqual(bytes_written, os.path.getsize(file_path)) csv_dset = pd.read_csv(file_path) self.assertEqual(csv_dset.shape, dset.shape) self.assertListEqual(list(csv_dset.columns), list(dset.column_names)) # With array features with self._create_dummy_dataset(in_memory, tmp_dir, array_features=True) as dset: file_path = os.path.join(tmp_dir, "test_path.csv") bytes_written = dset.to_csv(path_or_buf=file_path) self.assertTrue(os.path.isfile(file_path)) self.assertEqual(bytes_written, os.path.getsize(file_path)) csv_dset = pd.read_csv(file_path) self.assertEqual(csv_dset.shape, dset.shape) self.assertListEqual(list(csv_dset.columns), list(dset.column_names)) def test_to_dict(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: # Full dset_to_dict = dset.to_dict() self.assertIsInstance(dset_to_dict, dict) self.assertListEqual(sorted(dset_to_dict.keys()), sorted(dset.column_names)) for col_name in dset.column_names: self.assertLessEqual(len(dset_to_dict[col_name]), len(dset)) # With index mapping with dset.select([1, 0, 3]) as dset: dset_to_dict = dset.to_dict() self.assertIsInstance(dset_to_dict, dict) self.assertEqual(len(dset_to_dict), 3) self.assertListEqual(sorted(dset_to_dict.keys()), sorted(dset.column_names)) for col_name in dset.column_names: self.assertIsInstance(dset_to_dict[col_name], list) self.assertEqual(len(dset_to_dict[col_name]), len(dset)) def test_to_list(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: dset_to_list = dset.to_list() self.assertIsInstance(dset_to_list, list) for row in dset_to_list: self.assertIsInstance(row, dict) self.assertListEqual(sorted(row.keys()), sorted(dset.column_names)) # With index mapping with dset.select([1, 0, 3]) as dset: dset_to_list = dset.to_list() self.assertIsInstance(dset_to_list, list) self.assertEqual(len(dset_to_list), 3) for row in dset_to_list: self.assertIsInstance(row, dict) self.assertListEqual(sorted(row.keys()), sorted(dset.column_names)) def test_to_pandas(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: # Batched with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: batch_size = dset.num_rows - 1 to_pandas_generator = dset.to_pandas(batched=True, batch_size=batch_size) for batch in to_pandas_generator: self.assertIsInstance(batch, pd.DataFrame) self.assertListEqual(sorted(batch.columns), sorted(dset.column_names)) for col_name in dset.column_names: self.assertLessEqual(len(batch[col_name]), batch_size) # Full dset_to_pandas = dset.to_pandas() self.assertIsInstance(dset_to_pandas, pd.DataFrame) self.assertListEqual(sorted(dset_to_pandas.columns), sorted(dset.column_names)) for col_name in dset.column_names: self.assertEqual(len(dset_to_pandas[col_name]), len(dset)) # With index mapping with dset.select([1, 0, 3]) as dset: dset_to_pandas = dset.to_pandas() self.assertIsInstance(dset_to_pandas, pd.DataFrame) self.assertEqual(len(dset_to_pandas), 3) self.assertListEqual(sorted(dset_to_pandas.columns), sorted(dset.column_names)) for col_name in dset.column_names: self.assertEqual(len(dset_to_pandas[col_name]), dset.num_rows) def test_to_parquet(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: # File path argument with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: file_path = os.path.join(tmp_dir, "test_path.parquet") dset.to_parquet(path_or_buf=file_path) self.assertTrue(os.path.isfile(file_path)) # self.assertEqual(bytes_written, os.path.getsize(file_path)) # because of compression, the number of bytes doesn't match parquet_dset = pd.read_parquet(file_path) self.assertEqual(parquet_dset.shape, dset.shape) self.assertListEqual(list(parquet_dset.columns), list(dset.column_names)) # File buffer argument with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: file_path = os.path.join(tmp_dir, "test_buffer.parquet") with open(file_path, "wb+") as buffer: dset.to_parquet(path_or_buf=buffer) self.assertTrue(os.path.isfile(file_path)) # self.assertEqual(bytes_written, os.path.getsize(file_path)) # because of compression, the number of bytes doesn't match parquet_dset = pd.read_parquet(file_path) self.assertEqual(parquet_dset.shape, dset.shape) self.assertListEqual(list(parquet_dset.columns), list(dset.column_names)) # After a select/shuffle transform with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: dset = dset.select(range(0, len(dset), 2)).shuffle() file_path = os.path.join(tmp_dir, "test_path.parquet") dset.to_parquet(path_or_buf=file_path) self.assertTrue(os.path.isfile(file_path)) # self.assertEqual(bytes_written, os.path.getsize(file_path)) # because of compression, the number of bytes doesn't match parquet_dset = pd.read_parquet(file_path) self.assertEqual(parquet_dset.shape, dset.shape) self.assertListEqual(list(parquet_dset.columns), list(dset.column_names)) # With array features with self._create_dummy_dataset(in_memory, tmp_dir, array_features=True) as dset: file_path = os.path.join(tmp_dir, "test_path.parquet") dset.to_parquet(path_or_buf=file_path) self.assertTrue(os.path.isfile(file_path)) # self.assertEqual(bytes_written, os.path.getsize(file_path)) # because of compression, the number of bytes doesn't match parquet_dset = pd.read_parquet(file_path) self.assertEqual(parquet_dset.shape, dset.shape) self.assertListEqual(list(parquet_dset.columns), list(dset.column_names)) @require_sqlalchemy def test_to_sql(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: # Destionation specified as database URI string with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: file_path = os.path.join(tmp_dir, "test_path.sqlite") _ = dset.to_sql("data", "sqlite:///" + file_path) self.assertTrue(os.path.isfile(file_path)) sql_dset = pd.read_sql("data", "sqlite:///" + file_path) self.assertEqual(sql_dset.shape, dset.shape) self.assertListEqual(list(sql_dset.columns), list(dset.column_names)) # Destionation specified as sqlite3 connection with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: import sqlite3 file_path = os.path.join(tmp_dir, "test_path.sqlite") with contextlib.closing(sqlite3.connect(file_path)) as con: _ = dset.to_sql("data", con, if_exists="replace") self.assertTrue(os.path.isfile(file_path)) sql_dset = pd.read_sql("data", "sqlite:///" + file_path) self.assertEqual(sql_dset.shape, dset.shape) self.assertListEqual(list(sql_dset.columns), list(dset.column_names)) # Test writing to a database in chunks with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: file_path = os.path.join(tmp_dir, "test_path.sqlite") _ = dset.to_sql("data", "sqlite:///" + file_path, batch_size=1, if_exists="replace") self.assertTrue(os.path.isfile(file_path)) sql_dset = pd.read_sql("data", "sqlite:///" + file_path) self.assertEqual(sql_dset.shape, dset.shape) self.assertListEqual(list(sql_dset.columns), list(dset.column_names)) # After a select/shuffle transform with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: dset = dset.select(range(0, len(dset), 2)).shuffle() file_path = os.path.join(tmp_dir, "test_path.sqlite") _ = dset.to_sql("data", "sqlite:///" + file_path, if_exists="replace") self.assertTrue(os.path.isfile(file_path)) sql_dset = pd.read_sql("data", "sqlite:///" + file_path) self.assertEqual(sql_dset.shape, dset.shape) self.assertListEqual(list(sql_dset.columns), list(dset.column_names)) # With array features with self._create_dummy_dataset(in_memory, tmp_dir, array_features=True) as dset: file_path = os.path.join(tmp_dir, "test_path.sqlite") _ = dset.to_sql("data", "sqlite:///" + file_path, if_exists="replace") self.assertTrue(os.path.isfile(file_path)) sql_dset = pd.read_sql("data", "sqlite:///" + file_path) self.assertEqual(sql_dset.shape, dset.shape) self.assertListEqual(list(sql_dset.columns), list(dset.column_names)) def test_train_test_split(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: fingerprint = dset._fingerprint dset_dict = dset.train_test_split(test_size=10, shuffle=False) self.assertListEqual(list(dset_dict.keys()), ["train", "test"]) dset_train = dset_dict["train"] dset_test = dset_dict["test"] self.assertEqual(len(dset_train), 20) self.assertEqual(len(dset_test), 10) self.assertEqual(dset_train[0]["filename"], "my_name-train_0") self.assertEqual(dset_train[-1]["filename"], "my_name-train_19") self.assertEqual(dset_test[0]["filename"], "my_name-train_20") self.assertEqual(dset_test[-1]["filename"], "my_name-train_29") self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_train.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_test.features, Features({"filename": Value("string")})) self.assertNotEqual(dset_train._fingerprint, fingerprint) self.assertNotEqual(dset_test._fingerprint, fingerprint) self.assertNotEqual(dset_train._fingerprint, dset_test._fingerprint) dset_dict = dset.train_test_split(test_size=0.5, shuffle=False) self.assertListEqual(list(dset_dict.keys()), ["train", "test"]) dset_train = dset_dict["train"] dset_test = dset_dict["test"] self.assertEqual(len(dset_train), 15) self.assertEqual(len(dset_test), 15) self.assertEqual(dset_train[0]["filename"], "my_name-train_0") self.assertEqual(dset_train[-1]["filename"], "my_name-train_14") self.assertEqual(dset_test[0]["filename"], "my_name-train_15") self.assertEqual(dset_test[-1]["filename"], "my_name-train_29") self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_train.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_test.features, Features({"filename": Value("string")})) dset_dict = dset.train_test_split(train_size=10, shuffle=False) self.assertListEqual(list(dset_dict.keys()), ["train", "test"]) dset_train = dset_dict["train"] dset_test = dset_dict["test"] self.assertEqual(len(dset_train), 10) self.assertEqual(len(dset_test), 20) self.assertEqual(dset_train[0]["filename"], "my_name-train_0") self.assertEqual(dset_train[-1]["filename"], "my_name-train_9") self.assertEqual(dset_test[0]["filename"], "my_name-train_10") self.assertEqual(dset_test[-1]["filename"], "my_name-train_29") self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_train.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_test.features, Features({"filename": Value("string")})) dset.set_format("numpy") dset_dict = dset.train_test_split(train_size=10, seed=42) self.assertListEqual(list(dset_dict.keys()), ["train", "test"]) dset_train = dset_dict["train"] dset_test = dset_dict["test"] self.assertEqual(len(dset_train), 10) self.assertEqual(len(dset_test), 20) self.assertEqual(dset_train.format["type"], "numpy") self.assertEqual(dset_test.format["type"], "numpy") self.assertNotEqual(dset_train[0]["filename"].item(), "my_name-train_0") self.assertNotEqual(dset_train[-1]["filename"].item(), "my_name-train_9") self.assertNotEqual(dset_test[0]["filename"].item(), "my_name-train_10") self.assertNotEqual(dset_test[-1]["filename"].item(), "my_name-train_29") self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_train.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_test.features, Features({"filename": Value("string")})) del dset_test, dset_train, dset_dict # DatasetDict def test_shard(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir, self._create_dummy_dataset(in_memory, tmp_dir) as dset: tmp_file = os.path.join(tmp_dir, "test.arrow") with dset.select(range(10), indices_cache_file_name=tmp_file) as dset: self.assertEqual(len(dset), 10) # Shard tmp_file_1 = os.path.join(tmp_dir, "test_1.arrow") fingerprint = dset._fingerprint with dset.shard(num_shards=8, index=1, indices_cache_file_name=tmp_file_1) as dset_sharded: self.assertEqual(2, len(dset_sharded)) self.assertEqual(["my_name-train_1", "my_name-train_9"], dset_sharded["filename"]) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_sharded.features, Features({"filename": Value("string")})) self.assertNotEqual(dset_sharded._fingerprint, fingerprint) # Shard contiguous tmp_file_2 = os.path.join(tmp_dir, "test_2.arrow") with dset.shard( num_shards=3, index=0, contiguous=True, indices_cache_file_name=tmp_file_2 ) as dset_sharded_contiguous: self.assertEqual([f"my_name-train_{i}" for i in (0, 1, 2, 3)], dset_sharded_contiguous["filename"]) self.assertDictEqual(dset.features, Features({"filename": Value("string")})) self.assertDictEqual(dset_sharded_contiguous.features, Features({"filename": Value("string")})) # Test lengths of sharded contiguous self.assertEqual( [4, 3, 3], [ len(dset.shard(3, index=i, contiguous=True, indices_cache_file_name=tmp_file_2 + str(i))) for i in range(3) ], ) # formatted dset.set_format("numpy") with dset.shard(num_shards=3, index=0) as dset_sharded_formatted: self.assertEqual(dset_sharded_formatted.format["type"], "numpy") def test_flatten_indices(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: self.assertIsNone(dset._indices) tmp_file = os.path.join(tmp_dir, "test.arrow") with dset.select(range(0, 10, 2), indices_cache_file_name=tmp_file) as dset: self.assertEqual(len(dset), 5) self.assertIsNotNone(dset._indices) tmp_file_2 = os.path.join(tmp_dir, "test_2.arrow") fingerprint = dset._fingerprint dset.set_format("numpy") with dset.flatten_indices(cache_file_name=tmp_file_2) as dset: self.assertEqual(len(dset), 5) self.assertEqual(len(dset.data), len(dset)) self.assertIsNone(dset._indices) self.assertNotEqual(dset._fingerprint, fingerprint) self.assertEqual(dset.format["type"], "numpy") # Test unique works dset.unique(dset.column_names[0]) assert_arrow_metadata_are_synced_with_dataset_features(dset) # Empty indices mapping with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir) as dset: self.assertIsNone(dset._indices, None) tmp_file = os.path.join(tmp_dir, "test.arrow") with dset.filter(lambda _: False, cache_file_name=tmp_file) as dset: self.assertEqual(len(dset), 0) self.assertIsNotNone(dset._indices, None) tmp_file_2 = os.path.join(tmp_dir, "test_2.arrow") fingerprint = dset._fingerprint dset.set_format("numpy") with dset.flatten_indices(cache_file_name=tmp_file_2) as dset: self.assertEqual(len(dset), 0) self.assertEqual(len(dset.data), len(dset)) self.assertIsNone(dset._indices, None) self.assertNotEqual(dset._fingerprint, fingerprint) self.assertEqual(dset.format["type"], "numpy") # Test unique works dset.unique(dset.column_names[0]) assert_arrow_metadata_are_synced_with_dataset_features(dset) @require_tf @require_torch def test_format_vectors(self, in_memory): import numpy as np import tensorflow as tf import torch with tempfile.TemporaryDirectory() as tmp_dir, self._create_dummy_dataset( in_memory, tmp_dir ) as dset, dset.map(lambda ex, i: {"vec": np.ones(3) * i}, with_indices=True) as dset: columns = dset.column_names self.assertIsNotNone(dset[0]) self.assertIsNotNone(dset[:2]) for col in columns: self.assertIsInstance(dset[0][col], (str, list)) self.assertIsInstance(dset[:2][col], list) self.assertDictEqual( dset.features, Features({"filename": Value("string"), "vec": Sequence(Value("float64"))}) ) dset.set_format("tensorflow") self.assertIsNotNone(dset[0]) self.assertIsNotNone(dset[:2]) for col in columns: self.assertIsInstance(dset[0][col], (tf.Tensor, tf.RaggedTensor)) self.assertIsInstance(dset[:2][col], (tf.Tensor, tf.RaggedTensor)) self.assertIsInstance(dset[col], (tf.Tensor, tf.RaggedTensor)) self.assertTupleEqual(tuple(dset[:2]["vec"].shape), (2, 3)) self.assertTupleEqual(tuple(dset["vec"][:2].shape), (2, 3)) dset.set_format("numpy") self.assertIsNotNone(dset[0]) self.assertIsNotNone(dset[:2]) self.assertIsInstance(dset[0]["filename"], np.str_) self.assertIsInstance(dset[:2]["filename"], np.ndarray) self.assertIsInstance(dset["filename"], np.ndarray) self.assertIsInstance(dset[0]["vec"], np.ndarray) self.assertIsInstance(dset[:2]["vec"], np.ndarray) self.assertIsInstance(dset["vec"], np.ndarray) self.assertTupleEqual(dset[:2]["vec"].shape, (2, 3)) self.assertTupleEqual(dset["vec"][:2].shape, (2, 3)) dset.set_format("torch", columns=["vec"]) self.assertIsNotNone(dset[0]) self.assertIsNotNone(dset[:2]) # torch.Tensor is only for numerical columns self.assertIsInstance(dset[0]["vec"], torch.Tensor) self.assertIsInstance(dset[:2]["vec"], torch.Tensor) self.assertIsInstance(dset["vec"][:2], torch.Tensor) self.assertTupleEqual(dset[:2]["vec"].shape, (2, 3)) self.assertTupleEqual(dset["vec"][:2].shape, (2, 3)) @require_tf @require_torch def test_format_ragged_vectors(self, in_memory): import numpy as np import tensorflow as tf import torch with tempfile.TemporaryDirectory() as tmp_dir, self._create_dummy_dataset( in_memory, tmp_dir ) as dset, dset.map(lambda ex, i: {"vec": np.ones(3 + i) * i}, with_indices=True) as dset: columns = dset.column_names self.assertIsNotNone(dset[0]) self.assertIsNotNone(dset[:2]) for col in columns: self.assertIsInstance(dset[0][col], (str, list)) self.assertIsInstance(dset[:2][col], list) self.assertDictEqual( dset.features, Features({"filename": Value("string"), "vec": Sequence(Value("float64"))}) ) dset.set_format("tensorflow") self.assertIsNotNone(dset[0]) self.assertIsNotNone(dset[:2]) for col in columns: self.assertIsInstance(dset[0][col], tf.Tensor) self.assertIsInstance(dset[:2][col], tf.RaggedTensor if col == "vec" else tf.Tensor) self.assertIsInstance(dset[col], tf.RaggedTensor if col == "vec" else tf.Tensor) # dim is None for ragged vectors in tensorflow self.assertListEqual(dset[:2]["vec"].shape.as_list(), [2, None]) self.assertListEqual(dset["vec"][:2].shape.as_list(), [2, None]) dset.set_format("numpy") self.assertIsNotNone(dset[0]) self.assertIsNotNone(dset[:2]) self.assertIsInstance(dset[0]["filename"], np.str_) self.assertIsInstance(dset[:2]["filename"], np.ndarray) self.assertIsInstance(dset["filename"], np.ndarray) self.assertIsInstance(dset[0]["vec"], np.ndarray) self.assertIsInstance(dset[:2]["vec"], np.ndarray) self.assertIsInstance(dset["vec"], np.ndarray) # array is flat for ragged vectors in numpy self.assertTupleEqual(dset[:2]["vec"].shape, (2,)) self.assertTupleEqual(dset["vec"][:2].shape, (2,)) dset.set_format("torch") self.assertIsNotNone(dset[0]) self.assertIsNotNone(dset[:2]) self.assertIsInstance(dset[0]["filename"], str) self.assertIsInstance(dset[:2]["filename"], list) self.assertIsInstance(dset["filename"], list) self.assertIsInstance(dset[0]["vec"], torch.Tensor) self.assertIsInstance(dset[:2]["vec"][0], torch.Tensor) self.assertIsInstance(dset["vec"][0], torch.Tensor) # pytorch doesn't support ragged tensors, so we should have lists self.assertIsInstance(dset[:2]["vec"], list) self.assertIsInstance(dset[:2]["vec"][0], torch.Tensor) self.assertIsInstance(dset["vec"][:2], list) self.assertIsInstance(dset["vec"][0], torch.Tensor) @require_tf @require_torch def test_format_nested(self, in_memory): import numpy as np import tensorflow as tf import torch with tempfile.TemporaryDirectory() as tmp_dir, self._create_dummy_dataset( in_memory, tmp_dir ) as dset, dset.map(lambda ex: {"nested": [{"foo": np.ones(3)}] * len(ex["filename"])}, batched=True) as dset: self.assertDictEqual( dset.features, Features({"filename": Value("string"), "nested": {"foo": Sequence(Value("float64"))}}) ) dset.set_format("tensorflow") self.assertIsNotNone(dset[0]) self.assertIsInstance(dset[0]["nested"]["foo"], (tf.Tensor, tf.RaggedTensor)) self.assertIsNotNone(dset[:2]) self.assertIsInstance(dset[:2]["nested"][0]["foo"], (tf.Tensor, tf.RaggedTensor)) self.assertIsInstance(dset["nested"][0]["foo"], (tf.Tensor, tf.RaggedTensor)) dset.set_format("numpy") self.assertIsNotNone(dset[0]) self.assertIsInstance(dset[0]["nested"]["foo"], np.ndarray) self.assertIsNotNone(dset[:2]) self.assertIsInstance(dset[:2]["nested"][0]["foo"], np.ndarray) self.assertIsInstance(dset["nested"][0]["foo"], np.ndarray) dset.set_format("torch", columns="nested") self.assertIsNotNone(dset[0]) self.assertIsInstance(dset[0]["nested"]["foo"], torch.Tensor) self.assertIsNotNone(dset[:2]) self.assertIsInstance(dset[:2]["nested"][0]["foo"], torch.Tensor) self.assertIsInstance(dset["nested"][0]["foo"], torch.Tensor) def test_format_pandas(self, in_memory): import pandas as pd with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: dset.set_format("pandas") self.assertIsInstance(dset[0], pd.DataFrame) self.assertIsInstance(dset[:2], pd.DataFrame) self.assertIsInstance(dset["col_1"], pd.Series) def test_transmit_format_single(self, in_memory): @transmit_format def my_single_transform(self, return_factory, *args, **kwargs): return return_factory() with tempfile.TemporaryDirectory() as tmp_dir: return_factory = partial( self._create_dummy_dataset, in_memory=in_memory, tmp_dir=tmp_dir, multiple_columns=True ) with return_factory() as dset: dset.set_format("numpy", columns=["col_1"]) prev_format = dset.format with my_single_transform(dset, return_factory) as transformed_dset: self.assertDictEqual(transformed_dset.format, prev_format) def test_transmit_format_dict(self, in_memory): @transmit_format def my_split_transform(self, return_factory, *args, **kwargs): return DatasetDict({"train": return_factory()}) with tempfile.TemporaryDirectory() as tmp_dir: return_factory = partial( self._create_dummy_dataset, in_memory=in_memory, tmp_dir=tmp_dir, multiple_columns=True ) with return_factory() as dset: dset.set_format("numpy", columns=["col_1"]) prev_format = dset.format transformed_dset = my_split_transform(dset, return_factory)["train"] self.assertDictEqual(transformed_dset.format, prev_format) del transformed_dset # DatasetDict def test_with_format(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: with dset.with_format("numpy", columns=["col_1"]) as dset2: dset.set_format("numpy", columns=["col_1"]) self.assertDictEqual(dset.format, dset2.format) self.assertEqual(dset._fingerprint, dset2._fingerprint) # dset.reset_format() # self.assertNotEqual(dset.format, dset2.format) # self.assertNotEqual(dset._fingerprint, dset2._fingerprint) def test_with_transform(self, in_memory): with tempfile.TemporaryDirectory() as tmp_dir: with self._create_dummy_dataset(in_memory, tmp_dir, multiple_columns=True) as dset: transform = lambda x: {"foo": x["col_1"]} # noqa: E731 with dset.with_transform(transform, columns=["col_1"]) as dset2: dset.set_transform(transform, columns=["col_1"]) self.assertDictEqual(dset.format, dset2.format) self.assertEqual(dset._fingerprint, dset2._fingerprint) dset.reset_format() self.assertNotEqual(dset.format, dset2.format) self.assertNotEqual(dset._fingerprint, dset2._fingerprint) @require_tf def test_tf_dataset_conversion(self, in_memory): tmp_dir = tempfile.TemporaryDirectory() for num_workers in [0, 1, 2]: if num_workers > 0 and sys.platform == "win32" and not in_memory: continue # This test hangs on the Py3.10 test worker, but it runs fine locally on my Windows machine with self._create_dummy_dataset(in_memory, tmp_dir.name, array_features=True) as dset: tf_dataset = dset.to_tf_dataset(columns="col_3", batch_size=2, num_workers=num_workers) batch = next(iter(tf_dataset)) self.assertEqual(batch.shape.as_list(), [2, 4]) self.assertEqual(batch.dtype.name, "int64") with self._create_dummy_dataset(in_memory, tmp_dir.name, multiple_columns=True) as dset: tf_dataset = dset.to_tf_dataset(columns="col_1", batch_size=2, num_workers=num_workers) batch = next(iter(tf_dataset)) self.assertEqual(batch.shape.as_list(), [2]) self.assertEqual(batch.dtype.name, "int64") with self._create_dummy_dataset(in_memory, tmp_dir.name, multiple_columns=True) as dset: # Check that it works with all default options (except batch_size because the dummy dataset only has 4) tf_dataset = dset.to_tf_dataset(batch_size=2, num_workers=num_workers) batch = next(iter(tf_dataset)) self.assertEqual(batch["col_1"].shape.as_list(), [2]) self.assertEqual(batch["col_2"].shape.as_list(), [2]) self.assertEqual(batch["col_1"].dtype.name, "int64") self.assertEqual(batch["col_2"].dtype.name, "string") # Assert that we're converting strings properly with self._create_dummy_dataset(in_memory, tmp_dir.name, multiple_columns=True) as dset: # Check that when we use a transform that creates a new column from existing column values # but don't load the old columns that the new column depends on in the final dataset, # that they're still kept around long enough to be used in the transform transform_dset = dset.with_transform( lambda x: {"new_col": [val * 2 for val in x["col_1"]], "col_1": x["col_1"]} ) tf_dataset = transform_dset.to_tf_dataset(columns="new_col", batch_size=2, num_workers=num_workers) batch = next(iter(tf_dataset)) self.assertEqual(batch.shape.as_list(), [2]) self.assertEqual(batch.dtype.name, "int64") del transform_dset del tf_dataset # For correct cleanup @require_tf def test_tf_index_reshuffling(self, in_memory): # This test checks that when we do two epochs over a tf.data.Dataset from to_tf_dataset # that we get a different shuffle order each time # It also checks that when we aren't shuffling, that the dataset order is fully preserved # even when loading is split across multiple workers data = {"col_1": list(range(20))} for num_workers in [0, 1, 2, 3]: with Dataset.from_dict(data) as dset: tf_dataset = dset.to_tf_dataset(batch_size=10, shuffle=True, num_workers=num_workers) indices = [] for batch in tf_dataset: indices.append(batch["col_1"]) indices = np.concatenate([arr.numpy() for arr in indices]) second_indices = [] for batch in tf_dataset: second_indices.append(batch["col_1"]) second_indices = np.concatenate([arr.numpy() for arr in second_indices]) self.assertFalse(np.array_equal(indices, second_indices)) self.assertEqual(len(indices), len(np.unique(indices))) self.assertEqual(len(second_indices), len(np.unique(second_indices))) tf_dataset = dset.to_tf_dataset(batch_size=1, shuffle=False, num_workers=num_workers) for i, batch in enumerate(tf_dataset): # Assert that the unshuffled order is fully preserved even when multiprocessing self.assertEqual(i, batch["col_1"].numpy()) @require_tf def test_tf_label_renaming(self, in_memory): # Protect TF-specific imports in here import tensorflow as tf from datasets.utils.tf_utils import minimal_tf_collate_fn_with_renaming tmp_dir = tempfile.TemporaryDirectory() with self._create_dummy_dataset(in_memory, tmp_dir.name, multiple_columns=True) as dset: with dset.rename_columns({"col_1": "features", "col_2": "label"}) as new_dset: tf_dataset = new_dset.to_tf_dataset(collate_fn=minimal_tf_collate_fn_with_renaming, batch_size=4) batch = next(iter(tf_dataset)) self.assertTrue("labels" in batch and "features" in batch) tf_dataset = new_dset.to_tf_dataset( columns=["features", "labels"], collate_fn=minimal_tf_collate_fn_with_renaming, batch_size=4 ) batch = next(iter(tf_dataset)) self.assertTrue("labels" in batch and "features" in batch) tf_dataset = new_dset.to_tf_dataset( columns=["features", "label"], collate_fn=minimal_tf_collate_fn_with_renaming, batch_size=4 ) batch = next(iter(tf_dataset)) self.assertTrue("labels" in batch and "features" in batch) # Assert renaming was handled correctly tf_dataset = new_dset.to_tf_dataset( columns=["features"], label_cols=["labels"], collate_fn=minimal_tf_collate_fn_with_renaming, batch_size=4, ) batch = next(iter(tf_dataset)) self.assertEqual(len(batch), 2) # Assert that we don't have any empty entries here self.assertTrue(isinstance(batch[0], tf.Tensor) and isinstance(batch[1], tf.Tensor)) tf_dataset = new_dset.to_tf_dataset( columns=["features"], label_cols=["label"], collate_fn=minimal_tf_collate_fn_with_renaming, batch_size=4, ) batch = next(iter(tf_dataset)) self.assertEqual(len(batch), 2) # Assert that we don't have any empty entries here self.assertTrue(isinstance(batch[0], tf.Tensor) and isinstance(batch[1], tf.Tensor)) tf_dataset = new_dset.to_tf_dataset( columns=["features"], collate_fn=minimal_tf_collate_fn_with_renaming, batch_size=4, ) batch = next(iter(tf_dataset)) # Assert that labels didn't creep in when we don't ask for them # just because the collate_fn added them self.assertTrue(isinstance(batch, tf.Tensor)) del tf_dataset # For correct cleanup @require_tf def test_tf_dataset_options(self, in_memory): tmp_dir = tempfile.TemporaryDirectory() # Test that batch_size option works as expected with self._create_dummy_dataset(in_memory, tmp_dir.name, array_features=True) as dset: tf_dataset = dset.to_tf_dataset(columns="col_3", batch_size=2) batch = next(iter(tf_dataset)) self.assertEqual(batch.shape.as_list(), [2, 4]) self.assertEqual(batch.dtype.name, "int64") # Test that batch_size=None (optional) works as expected with self._create_dummy_dataset(in_memory, tmp_dir.name, multiple_columns=True) as dset: tf_dataset = dset.to_tf_dataset(columns="col_3", batch_size=None) single_example = next(iter(tf_dataset)) self.assertEqual(single_example.shape.as_list(), []) self.assertEqual(single_example.dtype.name, "int64") # Assert that we can batch it with `tf.data.Dataset.batch` method batched_dataset = tf_dataset.batch(batch_size=2) batch = next(iter(batched_dataset)) self.assertEqual(batch.shape.as_list(), [2]) self.assertEqual(batch.dtype.name, "int64") # Test that batching a batch_size=None dataset produces the same results as using batch_size arg with self._create_dummy_dataset(in_memory, tmp_dir.name, multiple_columns=True) as dset: batch_size = 2 tf_dataset_no_batch = dset.to_tf_dataset(columns="col_3") tf_dataset_batch = dset.to_tf_dataset(columns="col_3", batch_size=batch_size) self.assertEqual(tf_dataset_no_batch.element_spec, tf_dataset_batch.unbatch().element_spec) self.assertEqual(tf_dataset_no_batch.cardinality(), tf_dataset_batch.cardinality() * batch_size) for batch_1, batch_2 in zip(tf_dataset_no_batch.batch(batch_size=batch_size), tf_dataset_batch): self.assertEqual(batch_1.shape, batch_2.shape) self.assertEqual(batch_1.dtype, batch_2.dtype) self.assertListEqual(batch_1.numpy().tolist(), batch_2.numpy().tolist()) # Test that requesting label_cols works as expected with self._create_dummy_dataset(in_memory, tmp_dir.name, multiple_columns=True) as dset: tf_dataset = dset.to_tf_dataset(columns="col_1", label_cols=["col_2", "col_3"], batch_size=4) batch = next(iter(tf_dataset)) self.assertEqual(len(batch), 2) self.assertEqual(set(batch[1].keys()), {"col_2", "col_3"}) self.assertEqual(batch[0].dtype.name, "int64") # Assert data comes out as expected and isn't shuffled self.assertEqual(batch[0].numpy().tolist(), [3, 2, 1, 0]) self.assertEqual(batch[1]["col_2"].numpy().tolist(), [b"a", b"b", b"c", b"d"]) self.assertEqual(batch[1]["col_3"].numpy().tolist(), [0, 1, 0, 1]) # Check that incomplete batches are dropped if requested with self._create_dummy_dataset(in_memory, tmp_dir.name, multiple_columns=True) as dset: tf_dataset = dset.to_tf_dataset(columns="col_1", batch_size=3) tf_dataset_with_drop = dset.to_tf_dataset(columns="col_1", batch_size=3, drop_remainder=True) self.assertEqual(len(tf_dataset), 2) # One batch of 3 and one batch of 1 self.assertEqual(len(tf_dataset_with_drop), 1) # Incomplete batch of 1 is dropped # Test that `NotImplementedError` is raised `batch_size` is None and `num_workers` is > 0 if sys.version_info >= (3, 8): with self._create_dummy_dataset(in_memory, tmp_dir.name, multiple_columns=True) as dset: with self.assertRaisesRegex( NotImplementedError, "`batch_size` must be specified when using multiple workers" ): dset.to_tf_dataset(columns="col_1", batch_size=None, num_workers=2) del tf_dataset # For correct cleanup del tf_dataset_with_drop class MiscellaneousDatasetTest(TestCase): def test_from_pandas(self): data = {"col_1": [3, 2, 1, 0], "col_2": ["a", "b", "c", "d"]} df = pd.DataFrame.from_dict(data) with Dataset.from_pandas(df) as dset: self.assertListEqual(dset["col_1"], data["col_1"]) self.assertListEqual(dset["col_2"], data["col_2"]) self.assertListEqual(list(dset.features.keys()), ["col_1", "col_2"]) self.assertDictEqual(dset.features, Features({"col_1": Value("int64"), "col_2": Value("string")})) features = Features({"col_1": Value("int64"), "col_2": Value("string")}) with Dataset.from_pandas(df, features=features) as dset: self.assertListEqual(dset["col_1"], data["col_1"]) self.assertListEqual(dset["col_2"], data["col_2"]) self.assertListEqual(list(dset.features.keys()), ["col_1", "col_2"]) self.assertDictEqual(dset.features, Features({"col_1": Value("int64"), "col_2": Value("string")})) features = Features({"col_1": Value("int64"), "col_2": Value("string")}) with Dataset.from_pandas(df, features=features, info=DatasetInfo(features=features)) as dset: self.assertListEqual(dset["col_1"], data["col_1"]) self.assertListEqual(dset["col_2"], data["col_2"]) self.assertListEqual(list(dset.features.keys()), ["col_1", "col_2"]) self.assertDictEqual(dset.features, Features({"col_1": Value("int64"), "col_2": Value("string")})) features = Features({"col_1": Sequence(Value("string")), "col_2": Value("string")}) self.assertRaises(TypeError, Dataset.from_pandas, df, features=features) def test_from_dict(self): data = {"col_1": [3, 2, 1, 0], "col_2": ["a", "b", "c", "d"], "col_3": pa.array([True, False, True, False])} with Dataset.from_dict(data) as dset: self.assertListEqual(dset["col_1"], data["col_1"]) self.assertListEqual(dset["col_2"], data["col_2"]) self.assertListEqual(dset["col_3"], data["col_3"].to_pylist()) self.assertListEqual(list(dset.features.keys()), ["col_1", "col_2", "col_3"]) self.assertDictEqual( dset.features, Features({"col_1": Value("int64"), "col_2": Value("string"), "col_3": Value("bool")}) ) features = Features({"col_1": Value("int64"), "col_2": Value("string"), "col_3": Value("bool")}) with Dataset.from_dict(data, features=features) as dset: self.assertListEqual(dset["col_1"], data["col_1"]) self.assertListEqual(dset["col_2"], data["col_2"]) self.assertListEqual(dset["col_3"], data["col_3"].to_pylist()) self.assertListEqual(list(dset.features.keys()), ["col_1", "col_2", "col_3"]) self.assertDictEqual( dset.features, Features({"col_1": Value("int64"), "col_2": Value("string"), "col_3": Value("bool")}) ) features = Features({"col_1": Value("int64"), "col_2": Value("string"), "col_3": Value("bool")}) with Dataset.from_dict(data, features=features, info=DatasetInfo(features=features)) as dset: self.assertListEqual(dset["col_1"], data["col_1"]) self.assertListEqual(dset["col_2"], data["col_2"]) self.assertListEqual(dset["col_3"], data["col_3"].to_pylist()) self.assertListEqual(list(dset.features.keys()), ["col_1", "col_2", "col_3"]) self.assertDictEqual( dset.features, Features({"col_1": Value("int64"), "col_2": Value("string"), "col_3": Value("bool")}) ) features = Features({"col_1": Value("string"), "col_2": Value("string"), "col_3": Value("int32")}) with Dataset.from_dict(data, features=features) as dset: # the integers are converted to strings self.assertListEqual(dset["col_1"], [str(x) for x in data["col_1"]]) self.assertListEqual(dset["col_2"], data["col_2"]) self.assertListEqual(dset["col_3"], [int(x) for x in data["col_3"].to_pylist()]) self.assertListEqual(list(dset.features.keys()), ["col_1", "col_2", "col_3"]) self.assertDictEqual( dset.features, Features({"col_1": Value("string"), "col_2": Value("string"), "col_3": Value("int32")}) ) features = Features({"col_1": Value("int64"), "col_2": Value("int64"), "col_3": Value("bool")}) self.assertRaises(ValueError, Dataset.from_dict, data, features=features) def test_concatenate_mixed_memory_and_disk(self): data1, data2, data3 = {"id": [0, 1, 2]}, {"id": [3, 4, 5]}, {"id": [6, 7]} info1 = DatasetInfo(description="Dataset1") info2 = DatasetInfo(description="Dataset2") with tempfile.TemporaryDirectory() as tmp_dir: with Dataset.from_dict(data1, info=info1).map( cache_file_name=os.path.join(tmp_dir, "d1.arrow") ) as dset1, Dataset.from_dict(data2, info=info2).map( cache_file_name=os.path.join(tmp_dir, "d2.arrow") ) as dset2, Dataset.from_dict( data3 ) as dset3: with concatenate_datasets([dset1, dset2, dset3]) as concatenated_dset: self.assertEqual(len(concatenated_dset), len(dset1) + len(dset2) + len(dset3)) self.assertListEqual(concatenated_dset["id"], dset1["id"] + dset2["id"] + dset3["id"]) @require_transformers @pytest.mark.integration def test_set_format_encode(self): from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") def encode(batch): return tokenizer(batch["text"], padding="longest", return_tensors="np") with Dataset.from_dict({"text": ["hello there", "foo"]}) as dset: dset.set_transform(transform=encode) self.assertEqual(str(dset[:2]), str(encode({"text": ["hello there", "foo"]}))) @require_tf def test_tf_string_encoding(self): data = {"col_1": ["á", "é", "í", "ó", "ú"], "col_2": ["à", "è", "ì", "ò", "ù"]} with Dataset.from_dict(data) as dset: tf_dset_wo_batch = dset.to_tf_dataset(columns=["col_1", "col_2"]) for tf_row, row in zip(tf_dset_wo_batch, dset): self.assertEqual(tf_row["col_1"].numpy().decode("utf-8"), row["col_1"]) self.assertEqual(tf_row["col_2"].numpy().decode("utf-8"), row["col_2"]) tf_dset_w_batch = dset.to_tf_dataset(columns=["col_1", "col_2"], batch_size=2) for tf_row, row in zip(tf_dset_w_batch.unbatch(), dset): self.assertEqual(tf_row["col_1"].numpy().decode("utf-8"), row["col_1"]) self.assertEqual(tf_row["col_2"].numpy().decode("utf-8"), row["col_2"]) self.assertEqual(tf_dset_w_batch.unbatch().element_spec, tf_dset_wo_batch.element_spec) self.assertEqual(tf_dset_w_batch.element_spec, tf_dset_wo_batch.batch(2).element_spec) def test_cast_with_sliced_list(): old_features = Features({"foo": Sequence(Value("int64"))}) new_features = Features({"foo": Sequence(Value("int32"))}) dataset = Dataset.from_dict({"foo": [[i] * (i % 3) for i in range(20)]}, features=old_features) casted_dataset = dataset.cast(new_features, batch_size=2) # small batch size to slice the ListArray assert dataset["foo"] == casted_dataset["foo"] assert casted_dataset.features == new_features @pytest.mark.parametrize("include_nulls", [False, True]) def test_class_encode_column_with_none(include_nulls): dataset = Dataset.from_dict({"col_1": ["a", "b", "c", None, "d", None]}) dataset = dataset.class_encode_column("col_1", include_nulls=include_nulls) class_names = ["a", "b", "c", "d"] if include_nulls: class_names += ["None"] assert isinstance(dataset.features["col_1"], ClassLabel) assert set(dataset.features["col_1"].names) == set(class_names) assert (None in dataset.unique("col_1")) == (not include_nulls) @pytest.mark.parametrize("null_placement", ["first", "last"]) def test_sort_with_none(null_placement): dataset = Dataset.from_dict({"col_1": ["item_2", "item_3", "item_1", None, "item_4", None]}) dataset = dataset.sort("col_1", null_placement=null_placement) if null_placement == "first": assert dataset["col_1"] == [None, None, "item_1", "item_2", "item_3", "item_4"] else: assert dataset["col_1"] == ["item_1", "item_2", "item_3", "item_4", None, None] def test_update_metadata_with_features(dataset_dict): table1 = pa.Table.from_pydict(dataset_dict) features1 = Features.from_arrow_schema(table1.schema) features2 = features1.copy() features2["col_2"] = ClassLabel(num_classes=len(table1)) assert features1 != features2 table2 = update_metadata_with_features(table1, features2) metadata = json.loads(table2.schema.metadata[b"huggingface"].decode()) assert features2 == Features.from_dict(metadata["info"]["features"]) with Dataset(table1) as dset1, Dataset(table2) as dset2: assert dset1.features == features1 assert dset2.features == features2 @pytest.mark.parametrize("dataset_type", ["in_memory", "memory_mapped", "mixed"]) @pytest.mark.parametrize("axis, expected_shape", [(0, (4, 3)), (1, (2, 6))]) def test_concatenate_datasets(dataset_type, axis, expected_shape, dataset_dict, arrow_path): table = { "in_memory": InMemoryTable.from_pydict(dataset_dict), "memory_mapped": MemoryMappedTable.from_file(arrow_path), } tables = [ table[dataset_type if dataset_type != "mixed" else "memory_mapped"].slice(0, 2), # shape = (2, 3) table[dataset_type if dataset_type != "mixed" else "in_memory"].slice(2, 4), # shape = (2, 3) ] if axis == 1: # don't duplicate columns tables[1] = tables[1].rename_columns([col + "_bis" for col in tables[1].column_names]) datasets = [Dataset(table) for table in tables] dataset = concatenate_datasets(datasets, axis=axis) assert dataset.shape == expected_shape assert_arrow_metadata_are_synced_with_dataset_features(dataset) def test_concatenate_datasets_new_columns(): dataset1 = Dataset.from_dict({"col_1": ["a", "b", "c"]}) dataset2 = Dataset.from_dict({"col_1": ["d", "e", "f"], "col_2": [True, False, True]}) dataset = concatenate_datasets([dataset1, dataset2]) assert dataset.data.shape == (6, 2) assert dataset.features == Features({"col_1": Value("string"), "col_2": Value("bool")}) assert dataset[:] == {"col_1": ["a", "b", "c", "d", "e", "f"], "col_2": [None, None, None, True, False, True]} dataset3 = Dataset.from_dict({"col_3": ["a_1"]}) dataset = concatenate_datasets([dataset, dataset3]) assert dataset.data.shape == (7, 3) assert dataset.features == Features({"col_1": Value("string"), "col_2": Value("bool"), "col_3": Value("string")}) assert dataset[:] == { "col_1": ["a", "b", "c", "d", "e", "f", None], "col_2": [None, None, None, True, False, True, None], "col_3": [None, None, None, None, None, None, "a_1"], } @pytest.mark.parametrize("axis", [0, 1]) def test_concatenate_datasets_complex_features(axis): n = 5 dataset1 = Dataset.from_dict( {"col_1": [0] * n, "col_2": list(range(n))}, features=Features({"col_1": Value("int32"), "col_2": ClassLabel(num_classes=n)}), ) if axis == 1: dataset2 = dataset1.rename_columns({col: col + "_" for col in dataset1.column_names}) expected_features = Features({**dataset1.features, **dataset2.features}) else: dataset2 = dataset1 expected_features = dataset1.features assert concatenate_datasets([dataset1, dataset2], axis=axis).features == expected_features @pytest.mark.parametrize("other_dataset_type", ["in_memory", "memory_mapped", "concatenation"]) @pytest.mark.parametrize("axis, expected_shape", [(0, (8, 3)), (1, (4, 6))]) def test_concatenate_datasets_with_concatenation_tables( axis, expected_shape, other_dataset_type, dataset_dict, arrow_path ): def _create_concatenation_table(axis): if axis == 0: # shape: (4, 3) = (4, 1) + (4, 2) concatenation_table = ConcatenationTable.from_blocks( [ [ InMemoryTable.from_pydict({"col_1": dataset_dict["col_1"]}), MemoryMappedTable.from_file(arrow_path).remove_column(0), ] ] ) elif axis == 1: # shape: (4, 3) = (1, 3) + (3, 3) concatenation_table = ConcatenationTable.from_blocks( [ [InMemoryTable.from_pydict(dataset_dict).slice(0, 1)], [MemoryMappedTable.from_file(arrow_path).slice(1, 4)], ] ) return concatenation_table concatenation_table = _create_concatenation_table(axis) assert concatenation_table.shape == (4, 3) if other_dataset_type == "in_memory": other_table = InMemoryTable.from_pydict(dataset_dict) elif other_dataset_type == "memory_mapped": other_table = MemoryMappedTable.from_file(arrow_path) elif other_dataset_type == "concatenation": other_table = _create_concatenation_table(axis) assert other_table.shape == (4, 3) tables = [concatenation_table, other_table] if axis == 1: # don't duplicate columns tables[1] = tables[1].rename_columns([col + "_bis" for col in tables[1].column_names]) for tables in [tables, reversed(tables)]: datasets = [Dataset(table) for table in tables] dataset = concatenate_datasets(datasets, axis=axis) assert dataset.shape == expected_shape def test_concatenate_datasets_duplicate_columns(dataset): with pytest.raises(ValueError) as excinfo: concatenate_datasets([dataset, dataset], axis=1) assert "duplicated" in str(excinfo.value) def test_interleave_datasets(): d1 = Dataset.from_dict({"a": [0, 1, 2]}) d2 = Dataset.from_dict({"a": [10, 11, 12, 13]}) d3 = Dataset.from_dict({"a": [22, 21, 20]}).select([2, 1, 0]) dataset = interleave_datasets([d1, d2, d3]) expected_length = 3 * min(len(d1), len(d2), len(d3)) expected_values = [x["a"] for x in itertools.chain(*zip(d1, d2, d3))] assert isinstance(dataset, Dataset) assert len(dataset) == expected_length assert dataset["a"] == expected_values assert dataset._fingerprint == interleave_datasets([d1, d2, d3])._fingerprint def test_interleave_datasets_probabilities(): seed = 42 probabilities = [0.3, 0.5, 0.2] d1 = Dataset.from_dict({"a": [0, 1, 2]}) d2 = Dataset.from_dict({"a": [10, 11, 12, 13]}) d3 = Dataset.from_dict({"a": [22, 21, 20]}).select([2, 1, 0]) dataset = interleave_datasets([d1, d2, d3], probabilities=probabilities, seed=seed) expected_length = 7 # hardcoded expected_values = [10, 11, 20, 12, 0, 21, 13] # hardcoded assert isinstance(dataset, Dataset) assert len(dataset) == expected_length assert dataset["a"] == expected_values assert ( dataset._fingerprint == interleave_datasets([d1, d2, d3], probabilities=probabilities, seed=seed)._fingerprint ) def test_interleave_datasets_oversampling_strategy(): d1 = Dataset.from_dict({"a": [0, 1, 2]}) d2 = Dataset.from_dict({"a": [10, 11, 12, 13]}) d3 = Dataset.from_dict({"a": [22, 21, 20]}).select([2, 1, 0]) dataset = interleave_datasets([d1, d2, d3], stopping_strategy="all_exhausted") expected_length = 3 * max(len(d1), len(d2), len(d3)) expected_values = [0, 10, 20, 1, 11, 21, 2, 12, 22, 0, 13, 20] # hardcoded assert isinstance(dataset, Dataset) assert len(dataset) == expected_length assert dataset["a"] == expected_values assert dataset._fingerprint == interleave_datasets([d1, d2, d3], stopping_strategy="all_exhausted")._fingerprint def test_interleave_datasets_probabilities_oversampling_strategy(): seed = 42 probabilities = [0.3, 0.5, 0.2] d1 = Dataset.from_dict({"a": [0, 1, 2]}) d2 = Dataset.from_dict({"a": [10, 11, 12, 13]}) d3 = Dataset.from_dict({"a": [22, 21, 20]}).select([2, 1, 0]) dataset = interleave_datasets( [d1, d2, d3], stopping_strategy="all_exhausted", probabilities=probabilities, seed=seed ) expected_length = 16 # hardcoded expected_values = [10, 11, 20, 12, 0, 21, 13, 10, 1, 11, 12, 22, 13, 20, 10, 2] # hardcoded assert isinstance(dataset, Dataset) assert len(dataset) == expected_length assert dataset["a"] == expected_values assert ( dataset._fingerprint == interleave_datasets( [d1, d2, d3], stopping_strategy="all_exhausted", probabilities=probabilities, seed=seed )._fingerprint ) @pytest.mark.parametrize("batch_size", [4, 5]) @pytest.mark.parametrize("drop_last_batch", [False, True]) def test_dataset_iter_batch(batch_size, drop_last_batch): n = 25 dset = Dataset.from_dict({"i": list(range(n))}) all_col_values = list(range(n)) batches = [] for i, batch in enumerate(dset.iter(batch_size, drop_last_batch=drop_last_batch)): assert batch == {"i": all_col_values[i * batch_size : (i + 1) * batch_size]} batches.append(batch) if drop_last_batch: assert all(len(batch["i"]) == batch_size for batch in batches) else: assert all(len(batch["i"]) == batch_size for batch in batches[:-1]) assert len(batches[-1]["i"]) <= batch_size @pytest.mark.parametrize( "column, expected_dtype", [(["a", "b", "c", "d"], "string"), ([1, 2, 3, 4], "int64"), ([1.0, 2.0, 3.0, 4.0], "float64")], ) @pytest.mark.parametrize("in_memory", [False, True]) @pytest.mark.parametrize( "transform", [ None, ("shuffle", (42,), {}), ("with_format", ("pandas",), {}), ("class_encode_column", ("col_2",), {}), ("select", (range(3),), {}), ], ) def test_dataset_add_column(column, expected_dtype, in_memory, transform, dataset_dict, arrow_path): column_name = "col_4" original_dataset = ( Dataset(InMemoryTable.from_pydict(dataset_dict)) if in_memory else Dataset(MemoryMappedTable.from_file(arrow_path)) ) if transform is not None: transform_name, args, kwargs = transform original_dataset: Dataset = getattr(original_dataset, transform_name)(*args, **kwargs) column = column[:3] if transform is not None and transform_name == "select" else column dataset = original_dataset.add_column(column_name, column) assert dataset.data.shape == (3, 4) if transform is not None and transform_name == "select" else (4, 4) expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} # Sort expected features as in the original dataset expected_features = {feature: expected_features[feature] for feature in original_dataset.features} # Add new column feature expected_features[column_name] = expected_dtype assert dataset.data.column_names == list(expected_features.keys()) for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype assert len(dataset.data.blocks) == 1 if in_memory else 2 # multiple InMemoryTables are consolidated as one assert dataset.format["type"] == original_dataset.format["type"] assert dataset._fingerprint != original_dataset._fingerprint dataset.reset_format() original_dataset.reset_format() assert all(dataset[col] == original_dataset[col] for col in original_dataset.column_names) assert set(dataset["col_4"]) == set(column) if dataset._indices is not None: dataset_indices = dataset._indices["indices"].to_pylist() expected_dataset_indices = original_dataset._indices["indices"].to_pylist() assert dataset_indices == expected_dataset_indices assert_arrow_metadata_are_synced_with_dataset_features(dataset) @pytest.mark.parametrize( "transform", [None, ("shuffle", (42,), {}), ("with_format", ("pandas",), {}), ("class_encode_column", ("col_2",), {})], ) @pytest.mark.parametrize("in_memory", [False, True]) @pytest.mark.parametrize( "item", [ {"col_1": "2", "col_2": 2, "col_3": 2.0}, {"col_1": "2", "col_2": "2", "col_3": "2"}, {"col_1": 2, "col_2": 2, "col_3": 2}, {"col_1": 2.0, "col_2": 2.0, "col_3": 2.0}, ], ) def test_dataset_add_item(item, in_memory, dataset_dict, arrow_path, transform): dataset_to_test = ( Dataset(InMemoryTable.from_pydict(dataset_dict)) if in_memory else Dataset(MemoryMappedTable.from_file(arrow_path)) ) if transform is not None: transform_name, args, kwargs = transform dataset_to_test: Dataset = getattr(dataset_to_test, transform_name)(*args, **kwargs) dataset = dataset_to_test.add_item(item) assert dataset.data.shape == (5, 3) expected_features = dataset_to_test.features assert sorted(dataset.data.column_names) == sorted(expected_features.keys()) for feature, expected_dtype in expected_features.items(): assert dataset.features[feature] == expected_dtype assert len(dataset.data.blocks) == 1 if in_memory else 2 # multiple InMemoryTables are consolidated as one assert dataset.format["type"] == dataset_to_test.format["type"] assert dataset._fingerprint != dataset_to_test._fingerprint dataset.reset_format() dataset_to_test.reset_format() assert dataset[:-1] == dataset_to_test[:] assert {k: int(v) for k, v in dataset[-1].items()} == {k: int(v) for k, v in item.items()} if dataset._indices is not None: dataset_indices = dataset._indices["indices"].to_pylist() dataset_to_test_indices = dataset_to_test._indices["indices"].to_pylist() assert dataset_indices == dataset_to_test_indices + [len(dataset_to_test._data)] def test_dataset_add_item_new_columns(): dataset = Dataset.from_dict({"col_1": [0, 1, 2]}, features=Features({"col_1": Value("uint8")})) dataset = dataset.add_item({"col_1": 3, "col_2": "a"}) assert dataset.data.shape == (4, 2) assert dataset.features == Features({"col_1": Value("uint8"), "col_2": Value("string")}) assert dataset[:] == {"col_1": [0, 1, 2, 3], "col_2": [None, None, None, "a"]} dataset = dataset.add_item({"col_3": True}) assert dataset.data.shape == (5, 3) assert dataset.features == Features({"col_1": Value("uint8"), "col_2": Value("string"), "col_3": Value("bool")}) assert dataset[:] == { "col_1": [0, 1, 2, 3, None], "col_2": [None, None, None, "a", None], "col_3": [None, None, None, None, True], } def test_dataset_add_item_introduce_feature_type(): dataset = Dataset.from_dict({"col_1": [None, None, None]}) dataset = dataset.add_item({"col_1": "a"}) assert dataset.data.shape == (4, 1) assert dataset.features == Features({"col_1": Value("string")}) assert dataset[:] == {"col_1": [None, None, None, "a"]} def test_dataset_filter_batched_indices(): ds = Dataset.from_dict({"num": [0, 1, 2, 3]}) ds = ds.filter(lambda num: num % 2 == 0, input_columns="num", batch_size=2) assert all(item["num"] % 2 == 0 for item in ds) @pytest.mark.parametrize("in_memory", [False, True]) def test_dataset_from_file(in_memory, dataset, arrow_file): filename = arrow_file with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase(): dataset_from_file = Dataset.from_file(filename, in_memory=in_memory) assert dataset_from_file.features.type == dataset.features.type assert dataset_from_file.features == dataset.features assert dataset_from_file.cache_files == ([{"filename": filename}] if not in_memory else []) def _check_csv_dataset(dataset, expected_features): assert isinstance(dataset, Dataset) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_dataset_from_csv_keep_in_memory(keep_in_memory, csv_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "int64", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = Dataset.from_csv(csv_path, cache_dir=cache_dir, keep_in_memory=keep_in_memory) _check_csv_dataset(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ], ) def test_dataset_from_csv_features(features, csv_path, tmp_path): cache_dir = tmp_path / "cache" # CSV file loses col_1 string dtype information: default now is "int64" instead of "string" default_expected_features = {"col_1": "int64", "col_2": "int64", "col_3": "float64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = Dataset.from_csv(csv_path, features=features, cache_dir=cache_dir) _check_csv_dataset(dataset, expected_features) @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_dataset_from_csv_split(split, csv_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "int64", "col_2": "int64", "col_3": "float64"} dataset = Dataset.from_csv(csv_path, cache_dir=cache_dir, split=split) _check_csv_dataset(dataset, expected_features) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type", [str, list]) def test_dataset_from_csv_path_type(path_type, csv_path, tmp_path): if issubclass(path_type, str): path = csv_path elif issubclass(path_type, list): path = [csv_path] cache_dir = tmp_path / "cache" expected_features = {"col_1": "int64", "col_2": "int64", "col_3": "float64"} dataset = Dataset.from_csv(path, cache_dir=cache_dir) _check_csv_dataset(dataset, expected_features) def _check_json_dataset(dataset, expected_features): assert isinstance(dataset, Dataset) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_dataset_from_json_keep_in_memory(keep_in_memory, jsonl_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = Dataset.from_json(jsonl_path, cache_dir=cache_dir, keep_in_memory=keep_in_memory) _check_json_dataset(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ], ) def test_dataset_from_json_features(features, jsonl_path, tmp_path): cache_dir = tmp_path / "cache" default_expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = Dataset.from_json(jsonl_path, features=features, cache_dir=cache_dir) _check_json_dataset(dataset, expected_features) def test_dataset_from_json_with_class_label_feature(jsonl_str_path, tmp_path): features = Features( {"col_1": ClassLabel(names=["s0", "s1", "s2", "s3"]), "col_2": Value("int64"), "col_3": Value("float64")} ) cache_dir = tmp_path / "cache" dataset = Dataset.from_json(jsonl_str_path, features=features, cache_dir=cache_dir) assert dataset.features["col_1"].dtype == "int64" @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_dataset_from_json_split(split, jsonl_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} dataset = Dataset.from_json(jsonl_path, cache_dir=cache_dir, split=split) _check_json_dataset(dataset, expected_features) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type", [str, list]) def test_dataset_from_json_path_type(path_type, jsonl_path, tmp_path): if issubclass(path_type, str): path = jsonl_path elif issubclass(path_type, list): path = [jsonl_path] cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} dataset = Dataset.from_json(path, cache_dir=cache_dir) _check_json_dataset(dataset, expected_features) def _check_parquet_dataset(dataset, expected_features): assert isinstance(dataset, Dataset) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_dataset_from_parquet_keep_in_memory(keep_in_memory, parquet_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = Dataset.from_parquet(parquet_path, cache_dir=cache_dir, keep_in_memory=keep_in_memory) _check_parquet_dataset(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ], ) def test_dataset_from_parquet_features(features, parquet_path, tmp_path): cache_dir = tmp_path / "cache" default_expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = Dataset.from_parquet(parquet_path, features=features, cache_dir=cache_dir) _check_parquet_dataset(dataset, expected_features) @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_dataset_from_parquet_split(split, parquet_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} dataset = Dataset.from_parquet(parquet_path, cache_dir=cache_dir, split=split) _check_parquet_dataset(dataset, expected_features) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type", [str, list]) def test_dataset_from_parquet_path_type(path_type, parquet_path, tmp_path): if issubclass(path_type, str): path = parquet_path elif issubclass(path_type, list): path = [parquet_path] cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} dataset = Dataset.from_parquet(path, cache_dir=cache_dir) _check_parquet_dataset(dataset, expected_features) def _check_text_dataset(dataset, expected_features): assert isinstance(dataset, Dataset) assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_dataset_from_text_keep_in_memory(keep_in_memory, text_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"text": "string"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = Dataset.from_text(text_path, cache_dir=cache_dir, keep_in_memory=keep_in_memory) _check_text_dataset(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"text": "string"}, {"text": "int32"}, {"text": "float32"}, ], ) def test_dataset_from_text_features(features, text_path, tmp_path): cache_dir = tmp_path / "cache" default_expected_features = {"text": "string"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = Dataset.from_text(text_path, features=features, cache_dir=cache_dir) _check_text_dataset(dataset, expected_features) @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_dataset_from_text_split(split, text_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"text": "string"} dataset = Dataset.from_text(text_path, cache_dir=cache_dir, split=split) _check_text_dataset(dataset, expected_features) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type", [str, list]) def test_dataset_from_text_path_type(path_type, text_path, tmp_path): if issubclass(path_type, str): path = text_path elif issubclass(path_type, list): path = [text_path] cache_dir = tmp_path / "cache" expected_features = {"text": "string"} dataset = Dataset.from_text(path, cache_dir=cache_dir) _check_text_dataset(dataset, expected_features) @pytest.fixture def data_generator(): def _gen(): data = [ {"col_1": "0", "col_2": 0, "col_3": 0.0}, {"col_1": "1", "col_2": 1, "col_3": 1.0}, {"col_1": "2", "col_2": 2, "col_3": 2.0}, {"col_1": "3", "col_2": 3, "col_3": 3.0}, ] for item in data: yield item return _gen def _check_generator_dataset(dataset, expected_features): assert isinstance(dataset, Dataset) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_dataset_from_generator_keep_in_memory(keep_in_memory, data_generator, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = Dataset.from_generator(data_generator, cache_dir=cache_dir, keep_in_memory=keep_in_memory) _check_generator_dataset(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ], ) def test_dataset_from_generator_features(features, data_generator, tmp_path): cache_dir = tmp_path / "cache" default_expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = Dataset.from_generator(data_generator, features=features, cache_dir=cache_dir) _check_generator_dataset(dataset, expected_features) @require_not_windows @require_dill_gt_0_3_2 @require_pyspark def test_from_spark(): import pyspark spark = pyspark.sql.SparkSession.builder.master("local[*]").appName("pyspark").getOrCreate() data = [ ("0", 0, 0.0), ("1", 1, 1.0), ("2", 2, 2.0), ("3", 3, 3.0), ] df = spark.createDataFrame(data, "col_1: string, col_2: int, col_3: float") dataset = Dataset.from_spark(df) assert isinstance(dataset, Dataset) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] @require_not_windows @require_dill_gt_0_3_2 @require_pyspark def test_from_spark_features(): import PIL.Image import pyspark spark = pyspark.sql.SparkSession.builder.master("local[*]").appName("pyspark").getOrCreate() data = [(0, np.arange(4 * 4 * 3).reshape(4, 4, 3).tolist())] df = spark.createDataFrame(data, "idx: int, image: array<array<array<int>>>") features = Features({"idx": Value("int64"), "image": Image()}) dataset = Dataset.from_spark( df, features=features, ) assert isinstance(dataset, Dataset) assert dataset.num_rows == 1 assert dataset.num_columns == 2 assert dataset.column_names == ["idx", "image"] assert isinstance(dataset[0]["image"], PIL.Image.Image) assert dataset.features == features assert_arrow_metadata_are_synced_with_dataset_features(dataset) @require_not_windows @require_dill_gt_0_3_2 @require_pyspark def test_from_spark_different_cache(): import pyspark spark = pyspark.sql.SparkSession.builder.master("local[*]").appName("pyspark").getOrCreate() df = spark.createDataFrame([("0", 0)], "col_1: string, col_2: int") dataset = Dataset.from_spark(df) assert isinstance(dataset, Dataset) different_df = spark.createDataFrame([("1", 1)], "col_1: string, col_2: int") different_dataset = Dataset.from_spark(different_df) assert isinstance(different_dataset, Dataset) assert dataset[0]["col_1"] == "0" # Check to make sure that the second dataset wasn't read from the cache. assert different_dataset[0]["col_1"] == "1" def _check_sql_dataset(dataset, expected_features): assert isinstance(dataset, Dataset) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize("con_type", ["string", "engine"]) def test_dataset_from_sql_con_type(con_type, sqlite_path, tmp_path, set_sqlalchemy_silence_uber_warning): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} if con_type == "string": con = "sqlite:///" + sqlite_path elif con_type == "engine": import sqlalchemy con = sqlalchemy.create_engine("sqlite:///" + sqlite_path) # # https://github.com/huggingface/datasets/issues/2832 needs to be fixed first for this to work # with caplog.at_level(INFO): # dataset = Dataset.from_sql( # "dataset", # con, # cache_dir=cache_dir, # ) # if con_type == "string": # assert "couldn't be hashed properly" not in caplog.text # elif con_type == "engine": # assert "couldn't be hashed properly" in caplog.text dataset = Dataset.from_sql( "dataset", con, cache_dir=cache_dir, ) _check_sql_dataset(dataset, expected_features) @require_sqlalchemy @pytest.mark.parametrize( "features", [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ], ) def test_dataset_from_sql_features(features, sqlite_path, tmp_path, set_sqlalchemy_silence_uber_warning): cache_dir = tmp_path / "cache" default_expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = Dataset.from_sql("dataset", "sqlite:///" + sqlite_path, features=features, cache_dir=cache_dir) _check_sql_dataset(dataset, expected_features) @require_sqlalchemy @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_dataset_from_sql_keep_in_memory(keep_in_memory, sqlite_path, tmp_path, set_sqlalchemy_silence_uber_warning): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = Dataset.from_sql( "dataset", "sqlite:///" + sqlite_path, cache_dir=cache_dir, keep_in_memory=keep_in_memory ) _check_sql_dataset(dataset, expected_features) def test_dataset_to_json(dataset, tmp_path): file_path = tmp_path / "test_path.jsonl" bytes_written = dataset.to_json(path_or_buf=file_path) assert file_path.is_file() assert bytes_written == file_path.stat().st_size df = pd.read_json(file_path, orient="records", lines=True) assert df.shape == dataset.shape assert list(df.columns) == list(dataset.column_names) @pytest.mark.parametrize("in_memory", [False, True]) @pytest.mark.parametrize( "method_and_params", [ ("rename_column", (), {"original_column_name": "labels", "new_column_name": "label"}), ("remove_columns", (), {"column_names": "labels"}), ( "cast", (), { "features": Features( { "tokens": Sequence(Value("string")), "labels": Sequence(Value("int16")), "answers": Sequence( { "text": Value("string"), "answer_start": Value("int32"), } ), "id": Value("int32"), } ) }, ), ("flatten", (), {}), ], ) def test_pickle_dataset_after_transforming_the_table(in_memory, method_and_params, arrow_file): method, args, kwargs = method_and_params with Dataset.from_file(arrow_file, in_memory=in_memory) as dataset, Dataset.from_file( arrow_file, in_memory=in_memory ) as reference_dataset: out = getattr(dataset, method)(*args, **kwargs) dataset = out if out is not None else dataset pickled_dataset = pickle.dumps(dataset) reloaded_dataset = pickle.loads(pickled_dataset) assert dataset._data != reference_dataset._data assert dataset._data.table == reloaded_dataset._data.table def test_dummy_dataset_serialize_fs(dataset, mockfs): dataset_path = "mock://my_dataset" dataset.save_to_disk(dataset_path, storage_options=mockfs.storage_options) assert mockfs.isdir(dataset_path) assert mockfs.glob(dataset_path + "/*") reloaded = dataset.load_from_disk(dataset_path, storage_options=mockfs.storage_options) assert len(reloaded) == len(dataset) assert reloaded.features == dataset.features assert reloaded.to_dict() == dataset.to_dict() @pytest.mark.parametrize( "uri_or_path", [ "relative/path", "/absolute/path", "s3://bucket/relative/path", "hdfs://relative/path", "hdfs:///absolute/path", ], ) def test_build_local_temp_path(uri_or_path): extracted_path = extract_path_from_uri(uri_or_path) local_temp_path = Dataset._build_local_temp_path(extracted_path) path_relative_to_tmp_dir = local_temp_path.as_posix().split("tmp")[-1].split("/", 1)[1] assert ( "tmp" in local_temp_path.as_posix() and "hdfs" not in path_relative_to_tmp_dir and "s3" not in path_relative_to_tmp_dir and not local_temp_path.as_posix().startswith(extracted_path) and local_temp_path.as_posix().endswith(extracted_path) ), f"Local temp path: {local_temp_path.as_posix()}" class TaskTemplatesTest(TestCase): def test_task_text_classification(self): labels = sorted(["pos", "neg"]) features_before_cast = Features( { "input_text": Value("string"), "input_labels": ClassLabel(names=labels), } ) # Labels are cast to tuple during `TextClassification.__post_init_`, so we do the same here features_after_cast = Features( { "text": Value("string"), "labels": ClassLabel(names=labels), } ) # Label names are added in `DatasetInfo.__post_init__` so not needed here task_without_labels = TextClassification(text_column="input_text", label_column="input_labels") info1 = DatasetInfo( features=features_before_cast, task_templates=task_without_labels, ) # Label names are required when passing a TextClassification template directly to `Dataset.prepare_for_task` # However they also can be used to define `DatasetInfo` so we include a test for this too task_with_labels = TextClassification(text_column="input_text", label_column="input_labels") info2 = DatasetInfo( features=features_before_cast, task_templates=task_with_labels, ) data = {"input_text": ["i love transformers!"], "input_labels": [1]} # Test we can load from task name when label names not included in template (default behaviour) with Dataset.from_dict(data, info=info1) as dset: self.assertSetEqual({"input_text", "input_labels"}, set(dset.column_names)) self.assertDictEqual(features_before_cast, dset.features) with dset.prepare_for_task(task="text-classification") as dset: self.assertSetEqual({"labels", "text"}, set(dset.column_names)) self.assertDictEqual(features_after_cast, dset.features) # Test we can load from task name when label names included in template with Dataset.from_dict(data, info=info2) as dset: self.assertSetEqual({"input_text", "input_labels"}, set(dset.column_names)) self.assertDictEqual(features_before_cast, dset.features) with dset.prepare_for_task(task="text-classification") as dset: self.assertSetEqual({"labels", "text"}, set(dset.column_names)) self.assertDictEqual(features_after_cast, dset.features) # Test we can load from TextClassification template info1.task_templates = None with Dataset.from_dict(data, info=info1) as dset: with dset.prepare_for_task(task=task_with_labels) as dset: self.assertSetEqual({"labels", "text"}, set(dset.column_names)) self.assertDictEqual(features_after_cast, dset.features) def test_task_question_answering(self): features_before_cast = Features( { "input_context": Value("string"), "input_question": Value("string"), "input_answers": Sequence( { "text": Value("string"), "answer_start": Value("int32"), } ), } ) features_after_cast = Features( { "context": Value("string"), "question": Value("string"), "answers": Sequence( { "text": Value("string"), "answer_start": Value("int32"), } ), } ) task = QuestionAnsweringExtractive( context_column="input_context", question_column="input_question", answers_column="input_answers" ) info = DatasetInfo(features=features_before_cast, task_templates=task) data = { "input_context": ["huggingface is going to the moon!"], "input_question": ["where is huggingface going?"], "input_answers": [{"text": ["to the moon!"], "answer_start": [2]}], } # Test we can load from task name with Dataset.from_dict(data, info=info) as dset: self.assertSetEqual( {"input_context", "input_question", "input_answers.text", "input_answers.answer_start"}, set(dset.flatten().column_names), ) self.assertDictEqual(features_before_cast, dset.features) with dset.prepare_for_task(task="question-answering-extractive") as dset: self.assertSetEqual( {"context", "question", "answers.text", "answers.answer_start"}, set(dset.flatten().column_names), ) self.assertDictEqual(features_after_cast, dset.features) # Test we can load from QuestionAnsweringExtractive template info.task_templates = None with Dataset.from_dict(data, info=info) as dset: with dset.prepare_for_task(task=task) as dset: self.assertSetEqual( {"context", "question", "answers.text", "answers.answer_start"}, set(dset.flatten().column_names), ) self.assertDictEqual(features_after_cast, dset.features) def test_task_summarization(self): # Include a dummy extra column `dummy` to test we drop it correctly features_before_cast = Features( {"input_text": Value("string"), "input_summary": Value("string"), "dummy": Value("string")} ) features_after_cast = Features({"text": Value("string"), "summary": Value("string")}) task = Summarization(text_column="input_text", summary_column="input_summary") info = DatasetInfo(features=features_before_cast, task_templates=task) data = { "input_text": ["jack and jill took a taxi to attend a super duper party in the city."], "input_summary": ["jack and jill attend party"], "dummy": ["123456"], } # Test we can load from task name with Dataset.from_dict(data, info=info) as dset: with dset.prepare_for_task(task="summarization") as dset: self.assertSetEqual( {"text", "summary"}, set(dset.column_names), ) self.assertDictEqual(features_after_cast, dset.features) # Test we can load from Summarization template info.task_templates = None with Dataset.from_dict(data, info=info) as dset: with dset.prepare_for_task(task=task) as dset: self.assertSetEqual( {"text", "summary"}, set(dset.column_names), ) self.assertDictEqual(features_after_cast, dset.features) def test_task_automatic_speech_recognition(self): # Include a dummy extra column `dummy` to test we drop it correctly features_before_cast = Features( { "input_audio": Audio(sampling_rate=16_000), "input_transcription": Value("string"), "dummy": Value("string"), } ) features_after_cast = Features({"audio": Audio(sampling_rate=16_000), "transcription": Value("string")}) task = AutomaticSpeechRecognition(audio_column="input_audio", transcription_column="input_transcription") info = DatasetInfo(features=features_before_cast, task_templates=task) data = { "input_audio": [{"bytes": None, "path": "path/to/some/audio/file.wav"}], "input_transcription": ["hello, my name is bob!"], "dummy": ["123456"], } # Test we can load from task name with Dataset.from_dict(data, info=info) as dset: with dset.prepare_for_task(task="automatic-speech-recognition") as dset: self.assertSetEqual( {"audio", "transcription"}, set(dset.column_names), ) self.assertDictEqual(features_after_cast, dset.features) # Test we can load from Summarization template info.task_templates = None with Dataset.from_dict(data, info=info) as dset: with dset.prepare_for_task(task=task) as dset: self.assertSetEqual( {"audio", "transcription"}, set(dset.column_names), ) self.assertDictEqual(features_after_cast, dset.features) def test_task_with_no_template(self): data = {"input_text": ["i love transformers!"], "input_labels": [1]} with Dataset.from_dict(data) as dset: with self.assertRaises(ValueError): dset.prepare_for_task("text-classification") def test_task_with_incompatible_templates(self): labels = sorted(["pos", "neg"]) features = Features( { "input_text": Value("string"), "input_labels": ClassLabel(names=labels), } ) task = TextClassification(text_column="input_text", label_column="input_labels") info = DatasetInfo( features=features, task_templates=task, ) data = {"input_text": ["i love transformers!"], "input_labels": [1]} with Dataset.from_dict(data, info=info) as dset: # Invalid task name self.assertRaises(ValueError, dset.prepare_for_task, "this-task-does-not-exist") # Invalid task type self.assertRaises(ValueError, dset.prepare_for_task, 1) def test_task_with_multiple_compatible_task_templates(self): features = Features( { "text1": Value("string"), "text2": Value("string"), } ) task1 = LanguageModeling(text_column="text1") task2 = LanguageModeling(text_column="text2") info = DatasetInfo( features=features, task_templates=[task1, task2], ) data = {"text1": ["i love transformers!"], "text2": ["i love datasets!"]} with Dataset.from_dict(data, info=info) as dset: self.assertRaises(ValueError, dset.prepare_for_task, "language-modeling", id=3) with dset.prepare_for_task("language-modeling") as dset1: self.assertEqual(dset1[0]["text"], "i love transformers!") with dset.prepare_for_task("language-modeling", id=1) as dset2: self.assertEqual(dset2[0]["text"], "i love datasets!") def test_task_templates_empty_after_preparation(self): features = Features( { "input_text": Value("string"), "input_labels": ClassLabel(names=["pos", "neg"]), } ) task = TextClassification(text_column="input_text", label_column="input_labels") info = DatasetInfo( features=features, task_templates=task, ) data = {"input_text": ["i love transformers!"], "input_labels": [1]} with Dataset.from_dict(data, info=info) as dset: with dset.prepare_for_task(task="text-classification") as dset: self.assertIsNone(dset.info.task_templates) def test_align_labels_with_mapping_classification(self): features = Features( { "input_text": Value("string"), "input_labels": ClassLabel(num_classes=3, names=["entailment", "neutral", "contradiction"]), } ) data = {"input_text": ["a", "a", "b", "b", "c", "c"], "input_labels": [0, 0, 1, 1, 2, 2]} label2id = {"CONTRADICTION": 0, "ENTAILMENT": 2, "NEUTRAL": 1} id2label = {v: k for k, v in label2id.items()} expected_labels = [2, 2, 1, 1, 0, 0] expected_label_names = [id2label[idx] for idx in expected_labels] with Dataset.from_dict(data, features=features) as dset: with dset.align_labels_with_mapping(label2id, "input_labels") as dset: self.assertListEqual(expected_labels, dset["input_labels"]) aligned_label_names = [dset.features["input_labels"].int2str(idx) for idx in dset["input_labels"]] self.assertListEqual(expected_label_names, aligned_label_names) def test_align_labels_with_mapping_ner(self): features = Features( { "input_text": Value("string"), "input_labels": Sequence( ClassLabel( names=[ "b-per", "i-per", "o", ] ) ), } ) data = {"input_text": [["Optimus", "Prime", "is", "a", "Transformer"]], "input_labels": [[0, 1, 2, 2, 2]]} label2id = {"B-PER": 2, "I-PER": 1, "O": 0} id2label = {v: k for k, v in label2id.items()} expected_labels = [[2, 1, 0, 0, 0]] expected_label_names = [[id2label[idx] for idx in seq] for seq in expected_labels] with Dataset.from_dict(data, features=features) as dset: with dset.align_labels_with_mapping(label2id, "input_labels") as dset: self.assertListEqual(expected_labels, dset["input_labels"]) aligned_label_names = [ dset.features["input_labels"].feature.int2str(idx) for idx in dset["input_labels"] ] self.assertListEqual(expected_label_names, aligned_label_names) def test_concatenate_with_no_task_templates(self): info = DatasetInfo(task_templates=None) data = {"text": ["i love transformers!"], "labels": [1]} with Dataset.from_dict(data, info=info) as dset1, Dataset.from_dict( data, info=info ) as dset2, Dataset.from_dict(data, info=info) as dset3: with concatenate_datasets([dset1, dset2, dset3]) as dset_concat: self.assertEqual(dset_concat.info.task_templates, None) def test_concatenate_with_equal_task_templates(self): labels = ["neg", "pos"] task_template = TextClassification(text_column="text", label_column="labels") info = DatasetInfo( features=Features({"text": Value("string"), "labels": ClassLabel(names=labels)}), # Label names are added in `DatasetInfo.__post_init__` so not included here task_templates=TextClassification(text_column="text", label_column="labels"), ) data = {"text": ["i love transformers!"], "labels": [1]} with Dataset.from_dict(data, info=info) as dset1, Dataset.from_dict( data, info=info ) as dset2, Dataset.from_dict(data, info=info) as dset3: with concatenate_datasets([dset1, dset2, dset3]) as dset_concat: self.assertListEqual(dset_concat.info.task_templates, [task_template]) def test_concatenate_with_mixed_task_templates_in_common(self): tc_template = TextClassification(text_column="text", label_column="labels") qa_template = QuestionAnsweringExtractive( question_column="question", context_column="context", answers_column="answers" ) info1 = DatasetInfo( task_templates=[qa_template], features=Features( { "text": Value("string"), "labels": ClassLabel(names=["pos", "neg"]), "context": Value("string"), "question": Value("string"), "answers": Sequence( { "text": Value("string"), "answer_start": Value("int32"), } ), } ), ) info2 = DatasetInfo( task_templates=[qa_template, tc_template], features=Features( { "text": Value("string"), "labels": ClassLabel(names=["pos", "neg"]), "context": Value("string"), "question": Value("string"), "answers": Sequence( { "text": Value("string"), "answer_start": Value("int32"), } ), } ), ) data = { "text": ["i love transformers!"], "labels": [1], "context": ["huggingface is going to the moon!"], "question": ["where is huggingface going?"], "answers": [{"text": ["to the moon!"], "answer_start": [2]}], } with Dataset.from_dict(data, info=info1) as dset1, Dataset.from_dict( data, info=info2 ) as dset2, Dataset.from_dict(data, info=info2) as dset3: with concatenate_datasets([dset1, dset2, dset3]) as dset_concat: self.assertListEqual(dset_concat.info.task_templates, [qa_template]) def test_concatenate_with_no_mixed_task_templates_in_common(self): tc_template1 = TextClassification(text_column="text", label_column="labels") tc_template2 = TextClassification(text_column="text", label_column="sentiment") qa_template = QuestionAnsweringExtractive( question_column="question", context_column="context", answers_column="answers" ) info1 = DatasetInfo( features=Features( { "text": Value("string"), "labels": ClassLabel(names=["pos", "neg"]), "sentiment": ClassLabel(names=["pos", "neg", "neutral"]), "context": Value("string"), "question": Value("string"), "answers": Sequence( { "text": Value("string"), "answer_start": Value("int32"), } ), } ), task_templates=[tc_template1], ) info2 = DatasetInfo( features=Features( { "text": Value("string"), "labels": ClassLabel(names=["pos", "neg"]), "sentiment": ClassLabel(names=["pos", "neg", "neutral"]), "context": Value("string"), "question": Value("string"), "answers": Sequence( { "text": Value("string"), "answer_start": Value("int32"), } ), } ), task_templates=[tc_template2], ) info3 = DatasetInfo( features=Features( { "text": Value("string"), "labels": ClassLabel(names=["pos", "neg"]), "sentiment": ClassLabel(names=["pos", "neg", "neutral"]), "context": Value("string"), "question": Value("string"), "answers": Sequence( { "text": Value("string"), "answer_start": Value("int32"), } ), } ), task_templates=[qa_template], ) data = { "text": ["i love transformers!"], "labels": [1], "sentiment": [0], "context": ["huggingface is going to the moon!"], "question": ["where is huggingface going?"], "answers": [{"text": ["to the moon!"], "answer_start": [2]}], } with Dataset.from_dict(data, info=info1) as dset1, Dataset.from_dict( data, info=info2 ) as dset2, Dataset.from_dict(data, info=info3) as dset3: with concatenate_datasets([dset1, dset2, dset3]) as dset_concat: self.assertEqual(dset_concat.info.task_templates, None) def test_task_text_classification_when_columns_removed(self): labels = sorted(["pos", "neg"]) features_before_map = Features( { "input_text": Value("string"), "input_labels": ClassLabel(names=labels), } ) features_after_map = Features({"new_column": Value("int64")}) # Label names are added in `DatasetInfo.__post_init__` so not needed here task = TextClassification(text_column="input_text", label_column="input_labels") info = DatasetInfo( features=features_before_map, task_templates=task, ) data = {"input_text": ["i love transformers!"], "input_labels": [1]} with Dataset.from_dict(data, info=info) as dset: with dset.map(lambda x: {"new_column": 0}, remove_columns=dset.column_names) as dset: self.assertDictEqual(dset.features, features_after_map) class StratifiedTest(TestCase): def test_errors_train_test_split_stratify(self): ys = [ np.array([0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2]), np.array([0, 1, 1, 1, 2, 2, 2, 3, 3, 3]), np.array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2] * 2), np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]), np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]), ] for i in range(len(ys)): features = Features({"text": Value("int64"), "label": ClassLabel(len(np.unique(ys[i])))}) data = {"text": np.ones(len(ys[i])), "label": ys[i]} d1 = Dataset.from_dict(data, features=features) # For checking stratify_by_column exist as key in self.features.keys() if i == 0: self.assertRaises(ValueError, d1.train_test_split, 0.33, stratify_by_column="labl") # For checking minimum class count error elif i == 1: self.assertRaises(ValueError, d1.train_test_split, 0.33, stratify_by_column="label") # For check typeof label as ClassLabel type elif i == 2: d1 = Dataset.from_dict(data) self.assertRaises(ValueError, d1.train_test_split, 0.33, stratify_by_column="label") # For checking test_size should be greater than or equal to number of classes elif i == 3: self.assertRaises(ValueError, d1.train_test_split, 0.30, stratify_by_column="label") # For checking train_size should be greater than or equal to number of classes elif i == 4: self.assertRaises(ValueError, d1.train_test_split, 0.60, stratify_by_column="label") def test_train_test_split_startify(self): ys = [ np.array([0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2]), np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]), np.array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2] * 2), np.array([0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3]), np.array([0] * 800 + [1] * 50), ] for y in ys: features = Features({"text": Value("int64"), "label": ClassLabel(len(np.unique(y)))}) data = {"text": np.ones(len(y)), "label": y} d1 = Dataset.from_dict(data, features=features) d1 = d1.train_test_split(test_size=0.33, stratify_by_column="label") y = np.asanyarray(y) # To make it indexable for y[train] test_size = np.ceil(0.33 * len(y)) train_size = len(y) - test_size npt.assert_array_equal(np.unique(d1["train"]["label"]), np.unique(d1["test"]["label"])) # checking classes proportion p_train = np.bincount(np.unique(d1["train"]["label"], return_inverse=True)[1]) / float( len(d1["train"]["label"]) ) p_test = np.bincount(np.unique(d1["test"]["label"], return_inverse=True)[1]) / float( len(d1["test"]["label"]) ) npt.assert_array_almost_equal(p_train, p_test, 1) assert len(d1["train"]["text"]) + len(d1["test"]["text"]) == y.size assert len(d1["train"]["text"]) == train_size assert len(d1["test"]["text"]) == test_size def test_dataset_estimate_nbytes(): ds = Dataset.from_dict({"a": ["0" * 100] * 100}) assert 0.9 * ds._estimate_nbytes() < 100 * 100, "must be smaller than full dataset size" ds = Dataset.from_dict({"a": ["0" * 100] * 100}).select([0]) assert 0.9 * ds._estimate_nbytes() < 100 * 100, "must be smaller than one chunk" ds = Dataset.from_dict({"a": ["0" * 100] * 100}) ds = concatenate_datasets([ds] * 100) assert 0.9 * ds._estimate_nbytes() < 100 * 100 * 100, "must be smaller than full dataset size" assert 1.1 * ds._estimate_nbytes() > 100 * 100 * 100, "must be bigger than full dataset size" ds = Dataset.from_dict({"a": ["0" * 100] * 100}) ds = concatenate_datasets([ds] * 100).select([0]) assert 0.9 * ds._estimate_nbytes() < 100 * 100, "must be smaller than one chunk" def test_dataset_to_iterable_dataset(dataset: Dataset): iterable_dataset = dataset.to_iterable_dataset() assert isinstance(iterable_dataset, IterableDataset) assert list(iterable_dataset) == list(dataset) assert iterable_dataset.features == dataset.features iterable_dataset = dataset.to_iterable_dataset(num_shards=3) assert isinstance(iterable_dataset, IterableDataset) assert list(iterable_dataset) == list(dataset) assert iterable_dataset.features == dataset.features assert iterable_dataset.n_shards == 3 with pytest.raises(ValueError): dataset.to_iterable_dataset(num_shards=len(dataset) + 1) with pytest.raises(NotImplementedError): dataset.with_format("torch").to_iterable_dataset() @pytest.mark.parametrize("batch_size", [1, 4]) @require_torch def test_dataset_with_torch_dataloader(dataset, batch_size): from torch.utils.data import DataLoader from datasets import config dataloader = DataLoader(dataset, batch_size=batch_size) with patch.object(dataset, "_getitem", wraps=dataset._getitem) as mock_getitem: out = list(dataloader) getitem_call_count = mock_getitem.call_count assert len(out) == len(dataset) // batch_size + int(len(dataset) % batch_size > 0) # calling dataset[list_of_indices] is much more efficient than [dataset[idx] for idx in list of indices] if config.TORCH_VERSION >= version.parse("1.13.0"): assert getitem_call_count == len(dataset) // batch_size + int(len(dataset) % batch_size > 0) @pytest.mark.parametrize("return_lazy_dict", [True, False, "mix"]) def test_map_cases(return_lazy_dict): def f(x): """May return a mix of LazyDict and regular Dict""" if x["a"] < 2: x["a"] = -1 return dict(x) if return_lazy_dict is False else x else: return x if return_lazy_dict is True else {} ds = Dataset.from_dict({"a": [0, 1, 2, 3]}) ds = ds.map(f) outputs = ds[:] assert outputs == {"a": [-1, -1, 2, 3]} def f(x): """May return a mix of LazyDict and regular Dict, but sometimes with None values""" if x["a"] < 2: x["a"] = None return dict(x) if return_lazy_dict is False else x else: return x if return_lazy_dict is True else {} ds = Dataset.from_dict({"a": [0, 1, 2, 3]}) ds = ds.map(f) outputs = ds[:] assert outputs == {"a": [None, None, 2, 3]} def f(x): """Return a LazyDict, but we remove a lazy column and add a new one""" if x["a"] < 2: x["b"] = -1 return x else: x["b"] = x["a"] return x ds = Dataset.from_dict({"a": [0, 1, 2, 3]}) ds = ds.map(f, remove_columns=["a"]) outputs = ds[:] assert outputs == {"b": [-1, -1, 2, 3]} # The formatted dataset version removes the lazy column from a different dictionary, hence it should be preserved in the output ds = Dataset.from_dict({"a": [0, 1, 2, 3]}) ds = ds.with_format("numpy") ds = ds.map(f, remove_columns=["a"]) ds = ds.with_format(None) outputs = ds[:] assert outputs == {"a": [0, 1, 2, 3], "b": [-1, -1, 2, 3]} def f(x): """May return a mix of LazyDict and regular Dict, but we replace a lazy column""" if x["a"] < 2: x["a"] = -1 return dict(x) if return_lazy_dict is False else x else: x["a"] = x["a"] return x if return_lazy_dict is True else {"a": x["a"]} ds = Dataset.from_dict({"a": [0, 1, 2, 3]}) ds = ds.map(f, remove_columns=["a"]) outputs = ds[:] assert outputs == ({"a": [-1, -1, 2, 3]} if return_lazy_dict is False else {}) def f(x): """May return a mix of LazyDict and regular Dict, but we modify a nested lazy column in-place""" if x["a"]["b"] < 2: x["a"]["c"] = -1 return dict(x) if return_lazy_dict is False else x else: x["a"]["c"] = x["a"]["b"] return x if return_lazy_dict is True else {} ds = Dataset.from_dict({"a": [{"b": 0}, {"b": 1}, {"b": 2}, {"b": 3}]}) ds = ds.map(f) outputs = ds[:] assert outputs == {"a": [{"b": 0, "c": -1}, {"b": 1, "c": -1}, {"b": 2, "c": 2}, {"b": 3, "c": 3}]} def f(x): """May return a mix of LazyDict and regular Dict, but using an extension type""" if x["a"][0][0] < 2: x["a"] = [[-1]] return dict(x) if return_lazy_dict is False else x else: return x if return_lazy_dict is True else {} features = Features({"a": Array2D(shape=(1, 1), dtype="int32")}) ds = Dataset.from_dict({"a": [[[i]] for i in [0, 1, 2, 3]]}, features=features) ds = ds.map(f) outputs = ds[:] assert outputs == {"a": [[[i]] for i in [-1, -1, 2, 3]]} def f(x): """May return a mix of LazyDict and regular Dict, but using a nested extension type""" if x["a"]["nested"][0][0] < 2: x["a"] = {"nested": [[-1]]} return dict(x) if return_lazy_dict is False else x else: return x if return_lazy_dict is True else {} features = Features({"a": {"nested": Array2D(shape=(1, 1), dtype="int64")}}) ds = Dataset.from_dict({"a": [{"nested": [[i]]} for i in [0, 1, 2, 3]]}, features=features) ds = ds.map(f) outputs = ds[:] assert outputs == {"a": [{"nested": [[i]]} for i in [-1, -1, 2, 3]]} def test_dataset_getitem_raises(): ds = Dataset.from_dict({"a": [0, 1, 2, 3]}) with pytest.raises(TypeError): ds[False] with pytest.raises(TypeError): ds._getitem(True)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_arrow_reader.py
import os import tempfile from pathlib import Path from unittest import TestCase import pyarrow as pa import pytest from datasets.arrow_dataset import Dataset from datasets.arrow_reader import ArrowReader, BaseReader, FileInstructions, ReadInstruction, make_file_instructions from datasets.info import DatasetInfo from datasets.splits import NamedSplit, Split, SplitDict, SplitInfo from .utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases class ReaderTest(BaseReader): """ Build a Dataset object out of Instruction instance(s). This reader is made for testing. It mocks file reads. """ def _get_table_from_filename(self, filename_skip_take, in_memory=False): """Returns a Dataset instance from given (filename, skip, take).""" filename, skip, take = ( filename_skip_take["filename"], filename_skip_take["skip"] if "skip" in filename_skip_take else None, filename_skip_take["take"] if "take" in filename_skip_take else None, ) open(os.path.join(filename), "wb").close() pa_table = pa.Table.from_pydict({"filename": [Path(filename).name] * 100}) if take == -1: take = len(pa_table) - skip if skip is not None and take is not None: pa_table = pa_table.slice(skip, take) return pa_table class BaseReaderTest(TestCase): def test_read(self): name = "my_name" train_info = SplitInfo(name="train", num_examples=100) test_info = SplitInfo(name="test", num_examples=100) split_infos = [train_info, test_info] split_dict = SplitDict() split_dict.add(train_info) split_dict.add(test_info) info = DatasetInfo(splits=split_dict) with tempfile.TemporaryDirectory() as tmp_dir: reader = ReaderTest(tmp_dir, info) instructions = "test[:33%]" dset = Dataset(**reader.read(name, instructions, split_infos)) self.assertEqual(dset["filename"][0], f"{name}-test") self.assertEqual(dset.num_rows, 33) self.assertEqual(dset.num_columns, 1) instructions1 = ["train", "test[:33%]"] instructions2 = [Split.TRAIN, ReadInstruction.from_spec("test[:33%]")] for instructions in [instructions1, instructions2]: datasets_kwargs = [reader.read(name, instr, split_infos) for instr in instructions] train_dset, test_dset = (Dataset(**dataset_kwargs) for dataset_kwargs in datasets_kwargs) self.assertEqual(train_dset["filename"][0], f"{name}-train") self.assertEqual(train_dset.num_rows, 100) self.assertEqual(train_dset.num_columns, 1) self.assertIsInstance(train_dset.split, NamedSplit) self.assertEqual(str(train_dset.split), "train") self.assertEqual(test_dset["filename"][0], f"{name}-test") self.assertEqual(test_dset.num_rows, 33) self.assertEqual(test_dset.num_columns, 1) self.assertIsInstance(test_dset.split, NamedSplit) self.assertEqual(str(test_dset.split), "test[:33%]") del train_dset, test_dset def test_read_sharded(self): name = "my_name" train_info = SplitInfo(name="train", num_examples=1000, shard_lengths=[100] * 10) split_infos = [train_info] split_dict = SplitDict() split_dict.add(train_info) info = DatasetInfo(splits=split_dict) with tempfile.TemporaryDirectory() as tmp_dir: reader = ReaderTest(tmp_dir, info) instructions = "train[:33%]" dset = Dataset(**reader.read(name, instructions, split_infos)) self.assertEqual(dset["filename"][0], f"{name}-train-00000-of-00010") self.assertEqual(dset["filename"][-1], f"{name}-train-00003-of-00010") self.assertEqual(dset.num_rows, 330) self.assertEqual(dset.num_columns, 1) def test_read_files(self): train_info = SplitInfo(name="train", num_examples=100) test_info = SplitInfo(name="test", num_examples=100) split_dict = SplitDict() split_dict.add(train_info) split_dict.add(test_info) info = DatasetInfo(splits=split_dict) with tempfile.TemporaryDirectory() as tmp_dir: reader = ReaderTest(tmp_dir, info) files = [ {"filename": os.path.join(tmp_dir, "train")}, {"filename": os.path.join(tmp_dir, "test"), "skip": 10, "take": 10}, ] dset = Dataset(**reader.read_files(files, original_instructions="train+test[10:20]")) self.assertEqual(dset.num_rows, 110) self.assertEqual(dset.num_columns, 1) del dset @pytest.mark.parametrize("in_memory", [False, True]) def test_read_table(in_memory, dataset, arrow_file): filename = arrow_file with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase(): table = ArrowReader.read_table(filename, in_memory=in_memory) assert table.shape == dataset.data.shape assert set(table.column_names) == set(dataset.data.column_names) assert dict(table.to_pydict()) == dict(dataset.data.to_pydict()) # to_pydict returns OrderedDict @pytest.mark.parametrize("in_memory", [False, True]) def test_read_files(in_memory, dataset, arrow_file): filename = arrow_file reader = ArrowReader("", None) with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase(): dataset_kwargs = reader.read_files([{"filename": filename}], in_memory=in_memory) assert dataset_kwargs.keys() == {"arrow_table", "info", "split"} table = dataset_kwargs["arrow_table"] assert table.shape == dataset.data.shape assert set(table.column_names) == set(dataset.data.column_names) assert dict(table.to_pydict()) == dict(dataset.data.to_pydict()) # to_pydict returns OrderedDict def test_read_instruction_spec(): assert ReadInstruction("train", to=10, unit="abs").to_spec() == "train[:10]" assert ReadInstruction("train", from_=-80, to=10, unit="%").to_spec() == "train[-80%:10%]" spec_train_test = "train+test" assert ReadInstruction.from_spec(spec_train_test).to_spec() == spec_train_test spec_train_abs = "train[2:10]" assert ReadInstruction.from_spec(spec_train_abs).to_spec() == spec_train_abs spec_train_pct = "train[15%:-20%]" assert ReadInstruction.from_spec(spec_train_pct).to_spec() == spec_train_pct spec_train_pct_rounding = "train[:10%](closest)" assert ReadInstruction.from_spec(spec_train_pct_rounding).to_spec() == "train[:10%]" spec_train_pct_rounding = "train[:10%](pct1_dropremainder)" assert ReadInstruction.from_spec(spec_train_pct_rounding).to_spec() == spec_train_pct_rounding spec_train_test_pct_rounding = "train[:10%](pct1_dropremainder)+test[-10%:](pct1_dropremainder)" assert ReadInstruction.from_spec(spec_train_test_pct_rounding).to_spec() == spec_train_test_pct_rounding def test_make_file_instructions(): name = "dummy" split_infos = [SplitInfo(name="train", num_examples=100)] instruction = "train[:33%]" filetype_suffix = "arrow" prefix_path = "prefix" file_instructions = make_file_instructions(name, split_infos, instruction, filetype_suffix, prefix_path) assert isinstance(file_instructions, FileInstructions) assert file_instructions.num_examples == 33 assert file_instructions.file_instructions == [ {"filename": os.path.join(prefix_path, f"{name}-train.arrow"), "skip": 0, "take": 33} ] split_infos = [SplitInfo(name="train", num_examples=100, shard_lengths=[10] * 10)] file_instructions = make_file_instructions(name, split_infos, instruction, filetype_suffix, prefix_path) assert isinstance(file_instructions, FileInstructions) assert file_instructions.num_examples == 33 assert file_instructions.file_instructions == [ {"filename": os.path.join(prefix_path, f"{name}-train-00000-of-00010.arrow"), "skip": 0, "take": -1}, {"filename": os.path.join(prefix_path, f"{name}-train-00001-of-00010.arrow"), "skip": 0, "take": -1}, {"filename": os.path.join(prefix_path, f"{name}-train-00002-of-00010.arrow"), "skip": 0, "take": -1}, {"filename": os.path.join(prefix_path, f"{name}-train-00003-of-00010.arrow"), "skip": 0, "take": 3}, ] @pytest.mark.parametrize("name, expected_exception", [(None, TypeError), ("", ValueError)]) def test_make_file_instructions_raises(name, expected_exception): split_infos = [SplitInfo(name="train", num_examples=100)] instruction = "train" filetype_suffix = "arrow" prefix_path = "prefix_path" with pytest.raises(expected_exception): _ = make_file_instructions(name, split_infos, instruction, filetype_suffix, prefix_path)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_arrow_writer.py
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import Array2D, ClassLabel, Features, Image, Value from datasets.features.features import Array2DExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class TypedSequenceTest(TestCase): def test_no_type(self): arr = pa.array(TypedSequence([1, 2, 3])) self.assertEqual(arr.type, pa.int64()) def test_array_type_forbidden(self): with self.assertRaises(ValueError): _ = pa.array(TypedSequence([1, 2, 3]), type=pa.int64()) def test_try_type_and_type_forbidden(self): with self.assertRaises(ValueError): _ = pa.array(TypedSequence([1, 2, 3], try_type=Value("bool"), type=Value("int64"))) def test_compatible_type(self): arr = pa.array(TypedSequence([1, 2, 3], type=Value("int32"))) self.assertEqual(arr.type, pa.int32()) def test_incompatible_type(self): with self.assertRaises((TypeError, pa.lib.ArrowInvalid)): _ = pa.array(TypedSequence(["foo", "bar"], type=Value("int64"))) def test_try_compatible_type(self): arr = pa.array(TypedSequence([1, 2, 3], try_type=Value("int32"))) self.assertEqual(arr.type, pa.int32()) def test_try_incompatible_type(self): arr = pa.array(TypedSequence(["foo", "bar"], try_type=Value("int64"))) self.assertEqual(arr.type, pa.string()) def test_compatible_extension_type(self): arr = pa.array(TypedSequence([[[1, 2, 3]]], type=Array2D((1, 3), "int64"))) self.assertEqual(arr.type, Array2DExtensionType((1, 3), "int64")) def test_incompatible_extension_type(self): with self.assertRaises((TypeError, pa.lib.ArrowInvalid)): _ = pa.array(TypedSequence(["foo", "bar"], type=Array2D((1, 3), "int64"))) def test_try_compatible_extension_type(self): arr = pa.array(TypedSequence([[[1, 2, 3]]], try_type=Array2D((1, 3), "int64"))) self.assertEqual(arr.type, Array2DExtensionType((1, 3), "int64")) def test_try_incompatible_extension_type(self): arr = pa.array(TypedSequence(["foo", "bar"], try_type=Array2D((1, 3), "int64"))) self.assertEqual(arr.type, pa.string()) @require_pil def test_exhaustive_cast(self): import PIL.Image pil_image = PIL.Image.fromarray(np.arange(10, dtype=np.uint8).reshape(2, 5)) with patch( "datasets.arrow_writer.cast_to_python_objects", side_effect=cast_to_python_objects ) as mock_cast_to_python_objects: _ = pa.array(TypedSequence([{"path": None, "bytes": b"image_bytes"}, pil_image], type=Image())) args, kwargs = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("optimize_list_casting", kwargs) self.assertFalse(kwargs["optimize_list_casting"]) def _check_output(output, expected_num_chunks: int): stream = pa.BufferReader(output) if isinstance(output, pa.Buffer) else pa.memory_map(output) f = pa.ipc.open_stream(stream) pa_table: pa.Table = f.read_all() assert len(pa_table.to_batches()) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("writer_batch_size", [None, 1, 10]) @pytest.mark.parametrize( "fields", [None, {"col_1": pa.string(), "col_2": pa.int64()}, {"col_1": pa.string(), "col_2": pa.int32()}] ) def test_write(fields, writer_batch_size): output = pa.BufferOutputStream() schema = pa.schema(fields) if fields else None with ArrowWriter(stream=output, schema=schema, writer_batch_size=writer_batch_size) as writer: writer.write({"col_1": "foo", "col_2": 1}) writer.write({"col_1": "bar", "col_2": 2}) num_examples, num_bytes = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: fields = {"col_1": pa.string(), "col_2": pa.int64()} assert writer._schema == pa.schema(fields, metadata=writer._schema.metadata) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1) def test_write_with_features(): output = pa.BufferOutputStream() features = Features({"labels": ClassLabel(names=["neg", "pos"])}) with ArrowWriter(stream=output, features=features) as writer: writer.write({"labels": 0}) writer.write({"labels": 1}) num_examples, num_bytes = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata stream = pa.BufferReader(output.getvalue()) f = pa.ipc.open_stream(stream) pa_table: pa.Table = f.read_all() schema = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(schema) @pytest.mark.parametrize("writer_batch_size", [None, 1, 10]) def test_key_datatype(writer_batch_size): output = pa.BufferOutputStream() with ArrowWriter( stream=output, writer_batch_size=writer_batch_size, hash_salt="split_name", check_duplicates=True, ) as writer: with pytest.raises(InvalidKeyError): writer.write({"col_1": "foo", "col_2": 1}, key=[1, 2]) num_examples, num_bytes = writer.finalize() @pytest.mark.parametrize("writer_batch_size", [None, 2, 10]) def test_duplicate_keys(writer_batch_size): output = pa.BufferOutputStream() with ArrowWriter( stream=output, writer_batch_size=writer_batch_size, hash_salt="split_name", check_duplicates=True, ) as writer: with pytest.raises(DuplicatedKeysError): writer.write({"col_1": "foo", "col_2": 1}, key=10) writer.write({"col_1": "bar", "col_2": 2}, key=10) num_examples, num_bytes = writer.finalize() @pytest.mark.parametrize("writer_batch_size", [None, 2, 10]) def test_write_with_keys(writer_batch_size): output = pa.BufferOutputStream() with ArrowWriter( stream=output, writer_batch_size=writer_batch_size, hash_salt="split_name", check_duplicates=True, ) as writer: writer.write({"col_1": "foo", "col_2": 1}, key=1) writer.write({"col_1": "bar", "col_2": 2}, key=2) num_examples, num_bytes = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1) @pytest.mark.parametrize("writer_batch_size", [None, 1, 10]) @pytest.mark.parametrize( "fields", [None, {"col_1": pa.string(), "col_2": pa.int64()}, {"col_1": pa.string(), "col_2": pa.int32()}] ) def test_write_batch(fields, writer_batch_size): output = pa.BufferOutputStream() schema = pa.schema(fields) if fields else None with ArrowWriter(stream=output, schema=schema, writer_batch_size=writer_batch_size) as writer: writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]}) writer.write_batch({"col_1": [], "col_2": []}) num_examples, num_bytes = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: fields = {"col_1": pa.string(), "col_2": pa.int64()} assert writer._schema == pa.schema(fields, metadata=writer._schema.metadata) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1) @pytest.mark.parametrize("writer_batch_size", [None, 1, 10]) @pytest.mark.parametrize( "fields", [None, {"col_1": pa.string(), "col_2": pa.int64()}, {"col_1": pa.string(), "col_2": pa.int32()}] ) def test_write_table(fields, writer_batch_size): output = pa.BufferOutputStream() schema = pa.schema(fields) if fields else None with ArrowWriter(stream=output, schema=schema, writer_batch_size=writer_batch_size) as writer: writer.write_table(pa.Table.from_pydict({"col_1": ["foo", "bar"], "col_2": [1, 2]})) num_examples, num_bytes = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: fields = {"col_1": pa.string(), "col_2": pa.int64()} assert writer._schema == pa.schema(fields, metadata=writer._schema.metadata) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1) @pytest.mark.parametrize("writer_batch_size", [None, 1, 10]) @pytest.mark.parametrize( "fields", [None, {"col_1": pa.string(), "col_2": pa.int64()}, {"col_1": pa.string(), "col_2": pa.int32()}] ) def test_write_row(fields, writer_batch_size): output = pa.BufferOutputStream() schema = pa.schema(fields) if fields else None with ArrowWriter(stream=output, schema=schema, writer_batch_size=writer_batch_size) as writer: writer.write_row(pa.Table.from_pydict({"col_1": ["foo"], "col_2": [1]})) writer.write_row(pa.Table.from_pydict({"col_1": ["bar"], "col_2": [2]})) num_examples, num_bytes = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: fields = {"col_1": pa.string(), "col_2": pa.int64()} assert writer._schema == pa.schema(fields, metadata=writer._schema.metadata) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1) def test_write_file(): with tempfile.TemporaryDirectory() as tmp_dir: fields = {"col_1": pa.string(), "col_2": pa.int64()} output = os.path.join(tmp_dir, "test.arrow") with ArrowWriter(path=output, schema=pa.schema(fields)) as writer: writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]}) num_examples, num_bytes = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(fields, metadata=writer._schema.metadata) _check_output(output, 1) def get_base_dtype(arr_type): if pa.types.is_list(arr_type): return get_base_dtype(arr_type.value_type) else: return arr_type def change_first_primitive_element_in_list(lst, value): if isinstance(lst[0], list): change_first_primitive_element_in_list(lst[0], value) else: lst[0] = value @pytest.mark.parametrize("optimized_int_type, expected_dtype", [(None, pa.int64()), (Value("int32"), pa.int32())]) @pytest.mark.parametrize("sequence", [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]) def test_optimized_int_type_for_typed_sequence(sequence, optimized_int_type, expected_dtype): arr = pa.array(TypedSequence(sequence, optimized_int_type=optimized_int_type)) assert get_base_dtype(arr.type) == expected_dtype @pytest.mark.parametrize( "col, expected_dtype", [ ("attention_mask", pa.int8()), ("special_tokens_mask", pa.int8()), ("token_type_ids", pa.int8()), ("input_ids", pa.int32()), ("other", pa.int64()), ], ) @pytest.mark.parametrize("sequence", [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]) def test_optimized_typed_sequence(sequence, col, expected_dtype): # in range arr = pa.array(OptimizedTypedSequence(sequence, col=col)) assert get_base_dtype(arr.type) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications sequence = copy.deepcopy(sequence) value = np.iinfo(expected_dtype.to_pandas_dtype()).max + 1 change_first_primitive_element_in_list(sequence, value) arr = pa.array(OptimizedTypedSequence(sequence, col=col)) assert get_base_dtype(arr.type) == pa.int64() @pytest.mark.parametrize("raise_exception", [False, True]) def test_arrow_writer_closes_stream(raise_exception, tmp_path): path = str(tmp_path / "dataset-train.arrow") try: with ArrowWriter(path=path) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def test_arrow_writer_with_filesystem(mockfs): path = "mock://dataset-train.arrow" with ArrowWriter(path=path, storage_options=mockfs.storage_options) as writer: assert isinstance(writer._fs, type(mockfs)) assert writer._fs.storage_options == mockfs.storage_options writer.write({"col_1": "foo", "col_2": 1}) writer.write({"col_1": "bar", "col_2": 2}) num_examples, num_bytes = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(path) def test_parquet_writer_write(): output = pa.BufferOutputStream() with ParquetWriter(stream=output) as writer: writer.write({"col_1": "foo", "col_2": 1}) writer.write({"col_1": "bar", "col_2": 2}) num_examples, num_bytes = writer.finalize() assert num_examples == 2 assert num_bytes > 0 stream = pa.BufferReader(output.getvalue()) pa_table: pa.Table = pq.read_table(stream) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("embed_local_files", [False, True]) def test_writer_embed_local_files(tmp_path, embed_local_files): import PIL.Image image_path = str(tmp_path / "test_image_rgb.jpg") PIL.Image.fromarray(np.zeros((5, 5), dtype=np.uint8)).save(image_path, format="png") output = pa.BufferOutputStream() with ParquetWriter( stream=output, features=Features({"image": Image()}), embed_local_files=embed_local_files ) as writer: writer.write({"image": image_path}) writer.finalize() stream = pa.BufferReader(output.getvalue()) pa_table: pa.Table = pq.read_table(stream) out = pa_table.to_pydict() if embed_local_files: assert isinstance(out["image"][0]["path"], str) with open(image_path, "rb") as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def test_always_nullable(): non_nullable_schema = pa.schema([pa.field("col_1", pa.string(), nullable=False)]) output = pa.BufferOutputStream() with ArrowWriter(stream=output) as writer: writer._build_writer(inferred_schema=non_nullable_schema) assert writer._schema == pa.schema([pa.field("col_1", pa.string())])
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_beam.py
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class DummyBeamDataset(datasets.BeamBasedBuilder): """Dummy beam dataset.""" def _info(self): return datasets.DatasetInfo( features=datasets.Features({"content": datasets.Value("string")}), # No default supervised_keys. supervised_keys=None, ) def _split_generators(self, dl_manager, pipeline): return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"examples": get_test_dummy_examples()})] def _build_pcollection(self, pipeline, examples): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(examples) class NestedBeamDataset(datasets.BeamBasedBuilder): """Dummy beam dataset.""" def _info(self): return datasets.DatasetInfo( features=datasets.Features({"a": datasets.Sequence({"b": datasets.Value("string")})}), # No default supervised_keys. supervised_keys=None, ) def _split_generators(self, dl_manager, pipeline): return [ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"examples": get_test_nested_examples()}) ] def _build_pcollection(self, pipeline, examples): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(examples) def get_test_dummy_examples(): return [(i, {"content": content}) for i, content in enumerate(["foo", "bar", "foobar"])] def get_test_nested_examples(): return [(i, {"a": {"b": [content]}}) for i, content in enumerate(["foo", "bar", "foobar"])] class BeamBuilderTest(TestCase): @require_beam def test_download_and_prepare(self): expected_num_examples = len(get_test_dummy_examples()) with tempfile.TemporaryDirectory() as tmp_cache_dir: builder = DummyBeamDataset(cache_dir=tmp_cache_dir, beam_runner="DirectRunner") builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(tmp_cache_dir, builder.name, "default", "0.0.0", f"{builder.name}-train.arrow") ) ) self.assertDictEqual(builder.info.features, datasets.Features({"content": datasets.Value("string")})) dset = builder.as_dataset() self.assertEqual(dset["train"].num_rows, expected_num_examples) self.assertEqual(dset["train"].info.splits["train"].num_examples, expected_num_examples) self.assertDictEqual(dset["train"][0], get_test_dummy_examples()[0][1]) self.assertDictEqual( dset["train"][expected_num_examples - 1], get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(tmp_cache_dir, builder.name, "default", "0.0.0", "dataset_info.json")) ) del dset @require_beam def test_download_and_prepare_sharded(self): import apache_beam as beam original_write_parquet = beam.io.parquetio.WriteToParquet expected_num_examples = len(get_test_dummy_examples()) with tempfile.TemporaryDirectory() as tmp_cache_dir: builder = DummyBeamDataset(cache_dir=tmp_cache_dir, beam_runner="DirectRunner") with patch("apache_beam.io.parquetio.WriteToParquet") as write_parquet_mock: write_parquet_mock.side_effect = partial(original_write_parquet, num_shards=2) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( tmp_cache_dir, builder.name, "default", "0.0.0", f"{builder.name}-train-00000-of-00002.arrow" ) ) ) self.assertTrue( os.path.exists( os.path.join( tmp_cache_dir, builder.name, "default", "0.0.0", f"{builder.name}-train-00000-of-00002.arrow" ) ) ) self.assertDictEqual(builder.info.features, datasets.Features({"content": datasets.Value("string")})) dset = builder.as_dataset() self.assertEqual(dset["train"].num_rows, expected_num_examples) self.assertEqual(dset["train"].info.splits["train"].num_examples, expected_num_examples) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset["train"]["content"]), sorted(["foo", "bar", "foobar"])) self.assertTrue( os.path.exists(os.path.join(tmp_cache_dir, builder.name, "default", "0.0.0", "dataset_info.json")) ) del dset @require_beam def test_no_beam_options(self): with tempfile.TemporaryDirectory() as tmp_cache_dir: builder = DummyBeamDataset(cache_dir=tmp_cache_dir) self.assertRaises(datasets.builder.MissingBeamOptions, builder.download_and_prepare) @require_beam def test_nested_features(self): expected_num_examples = len(get_test_nested_examples()) with tempfile.TemporaryDirectory() as tmp_cache_dir: builder = NestedBeamDataset(cache_dir=tmp_cache_dir, beam_runner="DirectRunner") builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(tmp_cache_dir, builder.name, "default", "0.0.0", f"{builder.name}-train.arrow") ) ) self.assertDictEqual( builder.info.features, datasets.Features({"a": datasets.Sequence({"b": datasets.Value("string")})}) ) dset = builder.as_dataset() self.assertEqual(dset["train"].num_rows, expected_num_examples) self.assertEqual(dset["train"].info.splits["train"].num_examples, expected_num_examples) self.assertDictEqual(dset["train"][0], get_test_nested_examples()[0][1]) self.assertDictEqual( dset["train"][expected_num_examples - 1], get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(tmp_cache_dir, builder.name, "default", "0.0.0", "dataset_info.json")) ) del dset
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_builder.py
import importlib import os import tempfile import types from contextlib import nullcontext as does_not_raise from multiprocessing import Process from pathlib import Path from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from multiprocess.pool import Pool from datasets.arrow_dataset import Dataset from datasets.arrow_reader import DatasetNotOnHfGcsError from datasets.arrow_writer import ArrowWriter from datasets.builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from datasets.dataset_dict import DatasetDict, IterableDatasetDict from datasets.download.download_manager import DownloadMode from datasets.features import Features, Value from datasets.info import DatasetInfo, PostProcessedInfo from datasets.iterable_dataset import IterableDataset from datasets.splits import Split, SplitDict, SplitGenerator, SplitInfo from datasets.streaming import xjoin from datasets.utils.file_utils import is_local_path from datasets.utils.info_utils import VerificationMode from datasets.utils.logging import INFO, get_logger from .utils import ( assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_beam, require_faiss, set_current_working_directory_to_temp_dir, ) class DummyBuilder(DatasetBuilder): def _info(self): return DatasetInfo(features=Features({"text": Value("string")})) def _split_generators(self, dl_manager): return [SplitGenerator(name=Split.TRAIN)] def _prepare_split(self, split_generator, **kwargs): fname = f"{self.dataset_name}-{split_generator.name}.arrow" with ArrowWriter(features=self.info.features, path=os.path.join(self._output_dir, fname)) as writer: writer.write_batch({"text": ["foo"] * 100}) num_examples, num_bytes = writer.finalize() split_generator.split_info.num_examples = num_examples split_generator.split_info.num_bytes = num_bytes class DummyGeneratorBasedBuilder(GeneratorBasedBuilder): def _info(self): return DatasetInfo(features=Features({"text": Value("string")})) def _split_generators(self, dl_manager): return [SplitGenerator(name=Split.TRAIN)] def _generate_examples(self): for i in range(100): yield i, {"text": "foo"} class DummyArrowBasedBuilder(ArrowBasedBuilder): def _info(self): return DatasetInfo(features=Features({"text": Value("string")})) def _split_generators(self, dl_manager): return [SplitGenerator(name=Split.TRAIN)] def _generate_tables(self): for i in range(10): yield i, pa.table({"text": ["foo"] * 10}) class DummyBeamBasedBuilder(BeamBasedBuilder): def _info(self): return DatasetInfo(features=Features({"text": Value("string")})) def _split_generators(self, dl_manager): return [SplitGenerator(name=Split.TRAIN)] def _build_pcollection(self, pipeline): import apache_beam as beam def _process(item): for i in range(10): yield f"{i}_{item}", {"text": "foo"} return pipeline | "Initialize" >> beam.Create(range(10)) | "Extract content" >> beam.FlatMap(_process) class DummyGeneratorBasedBuilderWithIntegers(GeneratorBasedBuilder): def _info(self): return DatasetInfo(features=Features({"id": Value("int8")})) def _split_generators(self, dl_manager): return [SplitGenerator(name=Split.TRAIN)] def _generate_examples(self): for i in range(100): yield i, {"id": i} class DummyGeneratorBasedBuilderConfig(BuilderConfig): def __init__(self, content="foo", times=2, *args, **kwargs): super().__init__(*args, **kwargs) self.content = content self.times = times class DummyGeneratorBasedBuilderWithConfig(GeneratorBasedBuilder): BUILDER_CONFIG_CLASS = DummyGeneratorBasedBuilderConfig def _info(self): return DatasetInfo(features=Features({"text": Value("string")})) def _split_generators(self, dl_manager): return [SplitGenerator(name=Split.TRAIN)] def _generate_examples(self): for i in range(100): yield i, {"text": self.config.content * self.config.times} class DummyBuilderWithMultipleConfigs(DummyBuilder): BUILDER_CONFIGS = [ DummyGeneratorBasedBuilderConfig(name="a"), DummyGeneratorBasedBuilderConfig(name="b"), ] class DummyBuilderWithDefaultConfig(DummyBuilderWithMultipleConfigs): DEFAULT_CONFIG_NAME = "a" class DummyBuilderWithDownload(DummyBuilder): def __init__(self, *args, rel_path=None, abs_path=None, **kwargs): super().__init__(*args, **kwargs) self._rel_path = rel_path self._abs_path = abs_path def _split_generators(self, dl_manager): if self._rel_path is not None: assert os.path.exists(dl_manager.download(self._rel_path)), "dl_manager must support relative paths" if self._abs_path is not None: assert os.path.exists(dl_manager.download(self._abs_path)), "dl_manager must support absolute paths" return [SplitGenerator(name=Split.TRAIN)] class DummyBuilderWithManualDownload(DummyBuilderWithMultipleConfigs): @property def manual_download_instructions(self): return "To use the dataset you have to download some stuff manually and pass the data path to data_dir" def _split_generators(self, dl_manager): if not os.path.exists(self.config.data_dir): raise FileNotFoundError(f"data_dir {self.config.data_dir} doesn't exist.") return [SplitGenerator(name=Split.TRAIN)] class DummyArrowBasedBuilderWithShards(ArrowBasedBuilder): def _info(self): return DatasetInfo(features=Features({"id": Value("int8"), "filepath": Value("string")})) def _split_generators(self, dl_manager): return [SplitGenerator(name=Split.TRAIN, gen_kwargs={"filepaths": [f"data{i}.txt" for i in range(4)]})] def _generate_tables(self, filepaths): idx = 0 for filepath in filepaths: for i in range(10): yield idx, pa.table({"id": range(10 * i, 10 * (i + 1)), "filepath": [filepath] * 10}) idx += 1 class DummyGeneratorBasedBuilderWithShards(GeneratorBasedBuilder): def _info(self): return DatasetInfo(features=Features({"id": Value("int8"), "filepath": Value("string")})) def _split_generators(self, dl_manager): return [SplitGenerator(name=Split.TRAIN, gen_kwargs={"filepaths": [f"data{i}.txt" for i in range(4)]})] def _generate_examples(self, filepaths): idx = 0 for filepath in filepaths: for i in range(100): yield idx, {"id": i, "filepath": filepath} idx += 1 class DummyArrowBasedBuilderWithAmbiguousShards(ArrowBasedBuilder): def _info(self): return DatasetInfo(features=Features({"id": Value("int8"), "filepath": Value("string")})) def _split_generators(self, dl_manager): return [ SplitGenerator( name=Split.TRAIN, gen_kwargs={ "filepaths": [f"data{i}.txt" for i in range(4)], "dummy_kwarg_with_different_length": [f"dummy_data{i}.txt" for i in range(3)], }, ) ] def _generate_tables(self, filepaths, dummy_kwarg_with_different_length): idx = 0 for filepath in filepaths: for i in range(10): yield idx, pa.table({"id": range(10 * i, 10 * (i + 1)), "filepath": [filepath] * 10}) idx += 1 class DummyGeneratorBasedBuilderWithAmbiguousShards(GeneratorBasedBuilder): def _info(self): return DatasetInfo(features=Features({"id": Value("int8"), "filepath": Value("string")})) def _split_generators(self, dl_manager): return [ SplitGenerator( name=Split.TRAIN, gen_kwargs={ "filepaths": [f"data{i}.txt" for i in range(4)], "dummy_kwarg_with_different_length": [f"dummy_data{i}.txt" for i in range(3)], }, ) ] def _generate_examples(self, filepaths, dummy_kwarg_with_different_length): idx = 0 for filepath in filepaths: for i in range(100): yield idx, {"id": i, "filepath": filepath} idx += 1 def _run_concurrent_download_and_prepare(tmp_dir): builder = DummyBuilder(cache_dir=tmp_dir) builder.download_and_prepare(try_from_hf_gcs=False, download_mode=DownloadMode.REUSE_DATASET_IF_EXISTS) return builder def check_streaming(builder): builders_module = importlib.import_module(builder.__module__) assert builders_module._patched_for_streaming assert builders_module.os.path.join is xjoin class BuilderTest(TestCase): def test_download_and_prepare(self): with tempfile.TemporaryDirectory() as tmp_dir: builder = DummyBuilder(cache_dir=tmp_dir) builder.download_and_prepare(try_from_hf_gcs=False, download_mode=DownloadMode.FORCE_REDOWNLOAD) self.assertTrue( os.path.exists( os.path.join( tmp_dir, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train.arrow" ) ) ) self.assertDictEqual(builder.info.features, Features({"text": Value("string")})) self.assertEqual(builder.info.splits["train"].num_examples, 100) self.assertTrue( os.path.exists(os.path.join(tmp_dir, builder.dataset_name, "default", "0.0.0", "dataset_info.json")) ) def test_download_and_prepare_checksum_computation(self): with tempfile.TemporaryDirectory() as tmp_dir: builder_no_verification = DummyBuilder(cache_dir=tmp_dir) builder_no_verification.download_and_prepare( try_from_hf_gcs=False, download_mode=DownloadMode.FORCE_REDOWNLOAD ) self.assertTrue( all(v["checksum"] is not None for _, v in builder_no_verification.info.download_checksums.items()) ) builder_with_verification = DummyBuilder(cache_dir=tmp_dir) builder_with_verification.download_and_prepare( try_from_hf_gcs=False, download_mode=DownloadMode.FORCE_REDOWNLOAD, verification_mode=VerificationMode.ALL_CHECKS, ) self.assertTrue( all(v["checksum"] is None for _, v in builder_with_verification.info.download_checksums.items()) ) def test_concurrent_download_and_prepare(self): with tempfile.TemporaryDirectory() as tmp_dir: processes = 2 with Pool(processes=processes) as pool: jobs = [ pool.apply_async(_run_concurrent_download_and_prepare, kwds={"tmp_dir": tmp_dir}) for _ in range(processes) ] builders = [job.get() for job in jobs] for builder in builders: self.assertTrue( os.path.exists( os.path.join( tmp_dir, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train.arrow", ) ) ) self.assertDictEqual(builder.info.features, Features({"text": Value("string")})) self.assertEqual(builder.info.splits["train"].num_examples, 100) self.assertTrue( os.path.exists( os.path.join(tmp_dir, builder.dataset_name, "default", "0.0.0", "dataset_info.json") ) ) def test_download_and_prepare_with_base_path(self): with tempfile.TemporaryDirectory() as tmp_dir: rel_path = "dummy1.data" abs_path = os.path.join(tmp_dir, "dummy2.data") # test relative path is missing builder = DummyBuilderWithDownload(cache_dir=tmp_dir, rel_path=rel_path) with self.assertRaises(FileNotFoundError): builder.download_and_prepare( try_from_hf_gcs=False, download_mode=DownloadMode.FORCE_REDOWNLOAD, base_path=tmp_dir ) # test absolute path is missing builder = DummyBuilderWithDownload(cache_dir=tmp_dir, abs_path=abs_path) with self.assertRaises(FileNotFoundError): builder.download_and_prepare( try_from_hf_gcs=False, download_mode=DownloadMode.FORCE_REDOWNLOAD, base_path=tmp_dir ) # test that they are both properly loaded when they exist open(os.path.join(tmp_dir, rel_path), "w") open(abs_path, "w") builder = DummyBuilderWithDownload(cache_dir=tmp_dir, rel_path=rel_path, abs_path=abs_path) builder.download_and_prepare( try_from_hf_gcs=False, download_mode=DownloadMode.FORCE_REDOWNLOAD, base_path=tmp_dir ) self.assertTrue( os.path.exists( os.path.join( tmp_dir, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train.arrow", ) ) ) def test_as_dataset_with_post_process(self): def _post_process(self, dataset, resources_paths): def char_tokenize(example): return {"tokens": list(example["text"])} return dataset.map(char_tokenize, cache_file_name=resources_paths["tokenized_dataset"]) def _post_processing_resources(self, split): return {"tokenized_dataset": f"tokenized_dataset-{split}.arrow"} with tempfile.TemporaryDirectory() as tmp_dir: builder = DummyBuilder(cache_dir=tmp_dir) builder.info.post_processed = PostProcessedInfo( features=Features({"text": Value("string"), "tokens": [Value("string")]}) ) builder._post_process = types.MethodType(_post_process, builder) builder._post_processing_resources = types.MethodType(_post_processing_resources, builder) os.makedirs(builder.cache_dir) builder.info.splits = SplitDict() builder.info.splits.add(SplitInfo("train", num_examples=10)) builder.info.splits.add(SplitInfo("test", num_examples=10)) for split in builder.info.splits: with ArrowWriter( path=os.path.join(builder.cache_dir, f"{builder.dataset_name}-{split}.arrow"), features=Features({"text": Value("string")}), ) as writer: writer.write_batch({"text": ["foo"] * 10}) writer.finalize() with ArrowWriter( path=os.path.join(builder.cache_dir, f"tokenized_dataset-{split}.arrow"), features=Features({"text": Value("string"), "tokens": [Value("string")]}), ) as writer: writer.write_batch({"text": ["foo"] * 10, "tokens": [list("foo")] * 10}) writer.finalize() dsets = builder.as_dataset() self.assertIsInstance(dsets, DatasetDict) self.assertListEqual(list(dsets.keys()), ["train", "test"]) self.assertEqual(len(dsets["train"]), 10) self.assertEqual(len(dsets["test"]), 10) self.assertDictEqual( dsets["train"].features, Features({"text": Value("string"), "tokens": [Value("string")]}) ) self.assertDictEqual( dsets["test"].features, Features({"text": Value("string"), "tokens": [Value("string")]}) ) self.assertListEqual(dsets["train"].column_names, ["text", "tokens"]) self.assertListEqual(dsets["test"].column_names, ["text", "tokens"]) del dsets dset = builder.as_dataset("train") self.assertIsInstance(dset, Dataset) self.assertEqual(dset.split, "train") self.assertEqual(len(dset), 10) self.assertDictEqual(dset.features, Features({"text": Value("string"), "tokens": [Value("string")]})) self.assertListEqual(dset.column_names, ["text", "tokens"]) self.assertGreater(builder.info.post_processing_size, 0) self.assertGreater( builder.info.post_processed.resources_checksums["train"]["tokenized_dataset"]["num_bytes"], 0 ) del dset dset = builder.as_dataset("train+test[:30%]") self.assertIsInstance(dset, Dataset) self.assertEqual(dset.split, "train+test[:30%]") self.assertEqual(len(dset), 13) self.assertDictEqual(dset.features, Features({"text": Value("string"), "tokens": [Value("string")]})) self.assertListEqual(dset.column_names, ["text", "tokens"]) del dset dset = builder.as_dataset("all") self.assertIsInstance(dset, Dataset) self.assertEqual(dset.split, "train+test") self.assertEqual(len(dset), 20) self.assertDictEqual(dset.features, Features({"text": Value("string"), "tokens": [Value("string")]})) self.assertListEqual(dset.column_names, ["text", "tokens"]) del dset def _post_process(self, dataset, resources_paths): return dataset.select([0, 1], keep_in_memory=True) with tempfile.TemporaryDirectory() as tmp_dir: builder = DummyBuilder(cache_dir=tmp_dir) builder._post_process = types.MethodType(_post_process, builder) os.makedirs(builder.cache_dir) builder.info.splits = SplitDict() builder.info.splits.add(SplitInfo("train", num_examples=10)) builder.info.splits.add(SplitInfo("test", num_examples=10)) for split in builder.info.splits: with ArrowWriter( path=os.path.join(builder.cache_dir, f"{builder.dataset_name}-{split}.arrow"), features=Features({"text": Value("string")}), ) as writer: writer.write_batch({"text": ["foo"] * 10}) writer.finalize() with ArrowWriter( path=os.path.join(builder.cache_dir, f"small_dataset-{split}.arrow"), features=Features({"text": Value("string")}), ) as writer: writer.write_batch({"text": ["foo"] * 2}) writer.finalize() dsets = builder.as_dataset() self.assertIsInstance(dsets, DatasetDict) self.assertListEqual(list(dsets.keys()), ["train", "test"]) self.assertEqual(len(dsets["train"]), 2) self.assertEqual(len(dsets["test"]), 2) self.assertDictEqual(dsets["train"].features, Features({"text": Value("string")})) self.assertDictEqual(dsets["test"].features, Features({"text": Value("string")})) self.assertListEqual(dsets["train"].column_names, ["text"]) self.assertListEqual(dsets["test"].column_names, ["text"]) del dsets dset = builder.as_dataset("train") self.assertIsInstance(dset, Dataset) self.assertEqual(dset.split, "train") self.assertEqual(len(dset), 2) self.assertDictEqual(dset.features, Features({"text": Value("string")})) self.assertListEqual(dset.column_names, ["text"]) del dset dset = builder.as_dataset("train+test[:30%]") self.assertIsInstance(dset, Dataset) self.assertEqual(dset.split, "train+test[:30%]") self.assertEqual(len(dset), 2) self.assertDictEqual(dset.features, Features({"text": Value("string")})) self.assertListEqual(dset.column_names, ["text"]) del dset @require_faiss def test_as_dataset_with_post_process_with_index(self): def _post_process(self, dataset, resources_paths): if os.path.exists(resources_paths["index"]): dataset.load_faiss_index("my_index", resources_paths["index"]) return dataset else: dataset.add_faiss_index_from_external_arrays( external_arrays=np.ones((len(dataset), 8)), string_factory="Flat", index_name="my_index" ) dataset.save_faiss_index("my_index", resources_paths["index"]) return dataset def _post_processing_resources(self, split): return {"index": f"Flat-{split}.faiss"} with tempfile.TemporaryDirectory() as tmp_dir: builder = DummyBuilder(cache_dir=tmp_dir) builder._post_process = types.MethodType(_post_process, builder) builder._post_processing_resources = types.MethodType(_post_processing_resources, builder) os.makedirs(builder.cache_dir) builder.info.splits = SplitDict() builder.info.splits.add(SplitInfo("train", num_examples=10)) builder.info.splits.add(SplitInfo("test", num_examples=10)) for split in builder.info.splits: with ArrowWriter( path=os.path.join(builder.cache_dir, f"{builder.dataset_name}-{split}.arrow"), features=Features({"text": Value("string")}), ) as writer: writer.write_batch({"text": ["foo"] * 10}) writer.finalize() with ArrowWriter( path=os.path.join(builder.cache_dir, f"small_dataset-{split}.arrow"), features=Features({"text": Value("string")}), ) as writer: writer.write_batch({"text": ["foo"] * 2}) writer.finalize() dsets = builder.as_dataset() self.assertIsInstance(dsets, DatasetDict) self.assertListEqual(list(dsets.keys()), ["train", "test"]) self.assertEqual(len(dsets["train"]), 10) self.assertEqual(len(dsets["test"]), 10) self.assertDictEqual(dsets["train"].features, Features({"text": Value("string")})) self.assertDictEqual(dsets["test"].features, Features({"text": Value("string")})) self.assertListEqual(dsets["train"].column_names, ["text"]) self.assertListEqual(dsets["test"].column_names, ["text"]) self.assertListEqual(dsets["train"].list_indexes(), ["my_index"]) self.assertListEqual(dsets["test"].list_indexes(), ["my_index"]) self.assertGreater(builder.info.post_processing_size, 0) self.assertGreater(builder.info.post_processed.resources_checksums["train"]["index"]["num_bytes"], 0) del dsets dset = builder.as_dataset("train") self.assertIsInstance(dset, Dataset) self.assertEqual(dset.split, "train") self.assertEqual(len(dset), 10) self.assertDictEqual(dset.features, Features({"text": Value("string")})) self.assertListEqual(dset.column_names, ["text"]) self.assertListEqual(dset.list_indexes(), ["my_index"]) del dset dset = builder.as_dataset("train+test[:30%]") self.assertIsInstance(dset, Dataset) self.assertEqual(dset.split, "train+test[:30%]") self.assertEqual(len(dset), 13) self.assertDictEqual(dset.features, Features({"text": Value("string")})) self.assertListEqual(dset.column_names, ["text"]) self.assertListEqual(dset.list_indexes(), ["my_index"]) del dset def test_download_and_prepare_with_post_process(self): def _post_process(self, dataset, resources_paths): def char_tokenize(example): return {"tokens": list(example["text"])} return dataset.map(char_tokenize, cache_file_name=resources_paths["tokenized_dataset"]) def _post_processing_resources(self, split): return {"tokenized_dataset": f"tokenized_dataset-{split}.arrow"} with tempfile.TemporaryDirectory() as tmp_dir: builder = DummyBuilder(cache_dir=tmp_dir) builder.info.post_processed = PostProcessedInfo( features=Features({"text": Value("string"), "tokens": [Value("string")]}) ) builder._post_process = types.MethodType(_post_process, builder) builder._post_processing_resources = types.MethodType(_post_processing_resources, builder) builder.download_and_prepare(try_from_hf_gcs=False, download_mode=DownloadMode.FORCE_REDOWNLOAD) self.assertTrue( os.path.exists( os.path.join( tmp_dir, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train.arrow" ) ) ) self.assertDictEqual(builder.info.features, Features({"text": Value("string")})) self.assertDictEqual( builder.info.post_processed.features, Features({"text": Value("string"), "tokens": [Value("string")]}), ) self.assertEqual(builder.info.splits["train"].num_examples, 100) self.assertTrue( os.path.exists(os.path.join(tmp_dir, builder.dataset_name, "default", "0.0.0", "dataset_info.json")) ) def _post_process(self, dataset, resources_paths): return dataset.select([0, 1], keep_in_memory=True) with tempfile.TemporaryDirectory() as tmp_dir: builder = DummyBuilder(cache_dir=tmp_dir) builder._post_process = types.MethodType(_post_process, builder) builder.download_and_prepare(try_from_hf_gcs=False, download_mode=DownloadMode.FORCE_REDOWNLOAD) self.assertTrue( os.path.exists( os.path.join( tmp_dir, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train.arrow" ) ) ) self.assertDictEqual(builder.info.features, Features({"text": Value("string")})) self.assertIsNone(builder.info.post_processed) self.assertEqual(builder.info.splits["train"].num_examples, 100) self.assertTrue( os.path.exists(os.path.join(tmp_dir, builder.dataset_name, "default", "0.0.0", "dataset_info.json")) ) def _post_process(self, dataset, resources_paths): if os.path.exists(resources_paths["index"]): dataset.load_faiss_index("my_index", resources_paths["index"]) return dataset else: dataset = dataset.add_faiss_index_from_external_arrays( external_arrays=np.ones((len(dataset), 8)), string_factory="Flat", index_name="my_index" ) dataset.save_faiss_index("my_index", resources_paths["index"]) return dataset def _post_processing_resources(self, split): return {"index": f"Flat-{split}.faiss"} with tempfile.TemporaryDirectory() as tmp_dir: builder = DummyBuilder(cache_dir=tmp_dir) builder._post_process = types.MethodType(_post_process, builder) builder._post_processing_resources = types.MethodType(_post_processing_resources, builder) builder.download_and_prepare(try_from_hf_gcs=False, download_mode=DownloadMode.FORCE_REDOWNLOAD) self.assertTrue( os.path.exists( os.path.join( tmp_dir, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train.arrow" ) ) ) self.assertDictEqual(builder.info.features, Features({"text": Value("string")})) self.assertIsNone(builder.info.post_processed) self.assertEqual(builder.info.splits["train"].num_examples, 100) self.assertTrue( os.path.exists(os.path.join(tmp_dir, builder.dataset_name, "default", "0.0.0", "dataset_info.json")) ) def test_error_download_and_prepare(self): def _prepare_split(self, split_generator, **kwargs): raise ValueError() with tempfile.TemporaryDirectory() as tmp_dir: builder = DummyBuilder(cache_dir=tmp_dir) builder._prepare_split = types.MethodType(_prepare_split, builder) self.assertRaises( ValueError, builder.download_and_prepare, try_from_hf_gcs=False, download_mode=DownloadMode.FORCE_REDOWNLOAD, ) self.assertRaises(FileNotFoundError, builder.as_dataset) def test_generator_based_download_and_prepare(self): with tempfile.TemporaryDirectory() as tmp_dir: builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir) builder.download_and_prepare(try_from_hf_gcs=False, download_mode=DownloadMode.FORCE_REDOWNLOAD) self.assertTrue( os.path.exists( os.path.join( tmp_dir, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train.arrow", ) ) ) self.assertDictEqual(builder.info.features, Features({"text": Value("string")})) self.assertEqual(builder.info.splits["train"].num_examples, 100) self.assertTrue( os.path.exists(os.path.join(tmp_dir, builder.dataset_name, "default", "0.0.0", "dataset_info.json")) ) # Test that duplicated keys are ignored if verification_mode is "no_checks" with tempfile.TemporaryDirectory() as tmp_dir: builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir) with patch("datasets.builder.ArrowWriter", side_effect=ArrowWriter) as mock_arrow_writer: builder.download_and_prepare( download_mode=DownloadMode.FORCE_REDOWNLOAD, verification_mode=VerificationMode.NO_CHECKS ) mock_arrow_writer.assert_called_once() args, kwargs = mock_arrow_writer.call_args_list[0] self.assertFalse(kwargs["check_duplicates"]) mock_arrow_writer.reset_mock() builder.download_and_prepare( download_mode=DownloadMode.FORCE_REDOWNLOAD, verification_mode=VerificationMode.BASIC_CHECKS ) mock_arrow_writer.assert_called_once() args, kwargs = mock_arrow_writer.call_args_list[0] self.assertTrue(kwargs["check_duplicates"]) def test_cache_dir_no_args(self): with tempfile.TemporaryDirectory() as tmp_dir: builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir, data_dir=None, data_files=None) relative_cache_dir_parts = Path(builder._relative_data_dir()).parts self.assertTupleEqual(relative_cache_dir_parts, (builder.dataset_name, "default", "0.0.0")) def test_cache_dir_for_data_files(self): with tempfile.TemporaryDirectory() as tmp_dir: dummy_data1 = os.path.join(tmp_dir, "dummy_data1.txt") with open(dummy_data1, "w", encoding="utf-8") as f: f.writelines("foo bar") dummy_data2 = os.path.join(tmp_dir, "dummy_data2.txt") with open(dummy_data2, "w", encoding="utf-8") as f: f.writelines("foo bar\n") builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir, data_files=dummy_data1) other_builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir, data_files=dummy_data1) self.assertEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir, data_files=[dummy_data1]) self.assertEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir, data_files={"train": dummy_data1}) self.assertEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir, data_files={Split.TRAIN: dummy_data1}) self.assertEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir, data_files={"train": [dummy_data1]}) self.assertEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir, data_files={"test": dummy_data1}) self.assertNotEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir, data_files=dummy_data2) self.assertNotEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir, data_files=[dummy_data2]) self.assertNotEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir, data_files=[dummy_data1, dummy_data2]) self.assertNotEqual(builder.cache_dir, other_builder.cache_dir) builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir, data_files=[dummy_data1, dummy_data2]) other_builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir, data_files=[dummy_data1, dummy_data2]) self.assertEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyGeneratorBasedBuilder(cache_dir=tmp_dir, data_files=[dummy_data2, dummy_data1]) self.assertNotEqual(builder.cache_dir, other_builder.cache_dir) builder = DummyGeneratorBasedBuilder( cache_dir=tmp_dir, data_files={"train": dummy_data1, "test": dummy_data2} ) other_builder = DummyGeneratorBasedBuilder( cache_dir=tmp_dir, data_files={"train": dummy_data1, "test": dummy_data2} ) self.assertEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyGeneratorBasedBuilder( cache_dir=tmp_dir, data_files={"train": [dummy_data1], "test": dummy_data2} ) self.assertEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyGeneratorBasedBuilder( cache_dir=tmp_dir, data_files={"test": dummy_data2, "train": dummy_data1} ) self.assertEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyGeneratorBasedBuilder( cache_dir=tmp_dir, data_files={"train": dummy_data1, "validation": dummy_data2} ) self.assertNotEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyGeneratorBasedBuilder( cache_dir=tmp_dir, data_files={"train": [dummy_data1, dummy_data2], "test": dummy_data2}, ) self.assertNotEqual(builder.cache_dir, other_builder.cache_dir) def test_cache_dir_for_features(self): with tempfile.TemporaryDirectory() as tmp_dir: f1 = Features({"id": Value("int8")}) f2 = Features({"id": Value("int32")}) builder = DummyGeneratorBasedBuilderWithIntegers(cache_dir=tmp_dir, features=f1) other_builder = DummyGeneratorBasedBuilderWithIntegers(cache_dir=tmp_dir, features=f1) self.assertEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyGeneratorBasedBuilderWithIntegers(cache_dir=tmp_dir, features=f2) self.assertNotEqual(builder.cache_dir, other_builder.cache_dir) def test_cache_dir_for_config_kwargs(self): with tempfile.TemporaryDirectory() as tmp_dir: # create config on the fly builder = DummyGeneratorBasedBuilderWithConfig(cache_dir=tmp_dir, content="foo", times=2) other_builder = DummyGeneratorBasedBuilderWithConfig(cache_dir=tmp_dir, times=2, content="foo") self.assertEqual(builder.cache_dir, other_builder.cache_dir) self.assertIn("content=foo", builder.cache_dir) self.assertIn("times=2", builder.cache_dir) other_builder = DummyGeneratorBasedBuilderWithConfig(cache_dir=tmp_dir, content="bar", times=2) self.assertNotEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyGeneratorBasedBuilderWithConfig(cache_dir=tmp_dir, content="foo") self.assertNotEqual(builder.cache_dir, other_builder.cache_dir) with tempfile.TemporaryDirectory() as tmp_dir: # overwrite an existing config builder = DummyBuilderWithMultipleConfigs(cache_dir=tmp_dir, config_name="a", content="foo", times=2) other_builder = DummyBuilderWithMultipleConfigs(cache_dir=tmp_dir, config_name="a", times=2, content="foo") self.assertEqual(builder.cache_dir, other_builder.cache_dir) self.assertIn("content=foo", builder.cache_dir) self.assertIn("times=2", builder.cache_dir) other_builder = DummyBuilderWithMultipleConfigs(cache_dir=tmp_dir, config_name="a", content="bar", times=2) self.assertNotEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyBuilderWithMultipleConfigs(cache_dir=tmp_dir, config_name="a", content="foo") self.assertNotEqual(builder.cache_dir, other_builder.cache_dir) def test_config_names(self): with tempfile.TemporaryDirectory() as tmp_dir: with self.assertRaises(ValueError) as error_context: DummyBuilderWithMultipleConfigs(cache_dir=tmp_dir, data_files=None, data_dir=None) self.assertIn("Please pick one among the available configs", str(error_context.exception)) builder = DummyBuilderWithMultipleConfigs(cache_dir=tmp_dir, config_name="a") self.assertEqual(builder.config.name, "a") builder = DummyBuilderWithMultipleConfigs(cache_dir=tmp_dir, config_name="b") self.assertEqual(builder.config.name, "b") with self.assertRaises(ValueError): DummyBuilderWithMultipleConfigs(cache_dir=tmp_dir) builder = DummyBuilderWithDefaultConfig(cache_dir=tmp_dir) self.assertEqual(builder.config.name, "a") def test_cache_dir_for_data_dir(self): with tempfile.TemporaryDirectory() as tmp_dir, tempfile.TemporaryDirectory() as data_dir: builder = DummyBuilderWithManualDownload(cache_dir=tmp_dir, config_name="a", data_dir=data_dir) other_builder = DummyBuilderWithManualDownload(cache_dir=tmp_dir, config_name="a", data_dir=data_dir) self.assertEqual(builder.cache_dir, other_builder.cache_dir) other_builder = DummyBuilderWithManualDownload(cache_dir=tmp_dir, config_name="a", data_dir=tmp_dir) self.assertNotEqual(builder.cache_dir, other_builder.cache_dir) def test_arrow_based_download_and_prepare(tmp_path): builder = DummyArrowBasedBuilder(cache_dir=tmp_path) builder.download_and_prepare() assert os.path.exists( os.path.join( tmp_path, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train.arrow", ) ) assert builder.info.features, Features({"text": Value("string")}) assert builder.info.splits["train"].num_examples == 100 assert os.path.exists(os.path.join(tmp_path, builder.dataset_name, "default", "0.0.0", "dataset_info.json")) @require_beam def test_beam_based_download_and_prepare(tmp_path): builder = DummyBeamBasedBuilder(cache_dir=tmp_path, beam_runner="DirectRunner") builder.download_and_prepare() assert os.path.exists( os.path.join( tmp_path, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train.arrow", ) ) assert builder.info.features, Features({"text": Value("string")}) assert builder.info.splits["train"].num_examples == 100 assert os.path.exists(os.path.join(tmp_path, builder.dataset_name, "default", "0.0.0", "dataset_info.json")) @require_beam def test_beam_based_as_dataset(tmp_path): builder = DummyBeamBasedBuilder(cache_dir=tmp_path, beam_runner="DirectRunner") builder.download_and_prepare() dataset = builder.as_dataset() assert dataset assert isinstance(dataset["train"], Dataset) assert len(dataset["train"]) > 0 @pytest.mark.parametrize( "split, expected_dataset_class, expected_dataset_length", [ (None, DatasetDict, 10), ("train", Dataset, 10), ("train+test[:30%]", Dataset, 13), ], ) @pytest.mark.parametrize("in_memory", [False, True]) def test_builder_as_dataset(split, expected_dataset_class, expected_dataset_length, in_memory, tmp_path): cache_dir = str(tmp_path) builder = DummyBuilder(cache_dir=cache_dir) os.makedirs(builder.cache_dir) builder.info.splits = SplitDict() builder.info.splits.add(SplitInfo("train", num_examples=10)) builder.info.splits.add(SplitInfo("test", num_examples=10)) for info_split in builder.info.splits: with ArrowWriter( path=os.path.join(builder.cache_dir, f"{builder.dataset_name}-{info_split}.arrow"), features=Features({"text": Value("string")}), ) as writer: writer.write_batch({"text": ["foo"] * 10}) writer.finalize() with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase(): dataset = builder.as_dataset(split=split, in_memory=in_memory) assert isinstance(dataset, expected_dataset_class) if isinstance(dataset, DatasetDict): assert list(dataset.keys()) == ["train", "test"] datasets = dataset.values() expected_splits = ["train", "test"] elif isinstance(dataset, Dataset): datasets = [dataset] expected_splits = [split] for dataset, expected_split in zip(datasets, expected_splits): assert dataset.split == expected_split assert len(dataset) == expected_dataset_length assert dataset.features == Features({"text": Value("string")}) dataset.column_names == ["text"] @pytest.mark.parametrize("in_memory", [False, True]) def test_generator_based_builder_as_dataset(in_memory, tmp_path): cache_dir = tmp_path / "data" cache_dir.mkdir() cache_dir = str(cache_dir) builder = DummyGeneratorBasedBuilder(cache_dir=cache_dir) builder.download_and_prepare(try_from_hf_gcs=False, download_mode=DownloadMode.FORCE_REDOWNLOAD) with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase(): dataset = builder.as_dataset("train", in_memory=in_memory) assert dataset.data.to_pydict() == {"text": ["foo"] * 100} @pytest.mark.parametrize( "writer_batch_size, default_writer_batch_size, expected_chunks", [(None, None, 1), (None, 5, 20), (10, None, 10)] ) def test_custom_writer_batch_size(tmp_path, writer_batch_size, default_writer_batch_size, expected_chunks): cache_dir = str(tmp_path) if default_writer_batch_size: DummyGeneratorBasedBuilder.DEFAULT_WRITER_BATCH_SIZE = default_writer_batch_size builder = DummyGeneratorBasedBuilder(cache_dir=cache_dir, writer_batch_size=writer_batch_size) assert builder._writer_batch_size == (writer_batch_size or default_writer_batch_size) builder.download_and_prepare(try_from_hf_gcs=False, download_mode=DownloadMode.FORCE_REDOWNLOAD) dataset = builder.as_dataset("train") assert len(dataset.data[0].chunks) == expected_chunks def test_builder_as_streaming_dataset(tmp_path): dummy_builder = DummyGeneratorBasedBuilder(cache_dir=str(tmp_path)) check_streaming(dummy_builder) dsets = dummy_builder.as_streaming_dataset() assert isinstance(dsets, IterableDatasetDict) assert isinstance(dsets["train"], IterableDataset) assert len(list(dsets["train"])) == 100 dset = dummy_builder.as_streaming_dataset(split="train") assert isinstance(dset, IterableDataset) assert len(list(dset)) == 100 @require_beam def test_beam_based_builder_as_streaming_dataset(tmp_path): builder = DummyBeamBasedBuilder(cache_dir=tmp_path) check_streaming(builder) with pytest.raises(DatasetNotOnHfGcsError): builder.as_streaming_dataset() def _run_test_builder_streaming_works_in_subprocesses(builder): check_streaming(builder) dset = builder.as_streaming_dataset(split="train") assert isinstance(dset, IterableDataset) assert len(list(dset)) == 100 def test_builder_streaming_works_in_subprocess(tmp_path): dummy_builder = DummyGeneratorBasedBuilder(cache_dir=str(tmp_path)) p = Process(target=_run_test_builder_streaming_works_in_subprocesses, args=(dummy_builder,)) p.start() p.join() class DummyBuilderWithVersion(GeneratorBasedBuilder): VERSION = "2.0.0" def _info(self): return DatasetInfo(features=Features({"text": Value("string")})) def _split_generators(self, dl_manager): pass def _generate_examples(self): pass class DummyBuilderWithBuilderConfigs(GeneratorBasedBuilder): BUILDER_CONFIGS = [BuilderConfig(name="custom", version="2.0.0")] def _info(self): return DatasetInfo(features=Features({"text": Value("string")})) def _split_generators(self, dl_manager): pass def _generate_examples(self): pass class CustomBuilderConfig(BuilderConfig): def __init__(self, date=None, language=None, version="2.0.0", **kwargs): name = f"{date}.{language}" super().__init__(name=name, version=version, **kwargs) self.date = date self.language = language class DummyBuilderWithCustomBuilderConfigs(GeneratorBasedBuilder): BUILDER_CONFIGS = [CustomBuilderConfig(date="20220501", language="en")] BUILDER_CONFIG_CLASS = CustomBuilderConfig def _info(self): return DatasetInfo(features=Features({"text": Value("string")})) def _split_generators(self, dl_manager): pass def _generate_examples(self): pass @pytest.mark.parametrize( "builder_class, kwargs", [ (DummyBuilderWithVersion, {}), (DummyBuilderWithBuilderConfigs, {"config_name": "custom"}), (DummyBuilderWithCustomBuilderConfigs, {"config_name": "20220501.en"}), (DummyBuilderWithCustomBuilderConfigs, {"date": "20220501", "language": "ca"}), ], ) def test_builder_config_version(builder_class, kwargs, tmp_path): cache_dir = str(tmp_path) builder = builder_class(cache_dir=cache_dir, **kwargs) assert builder.config.version == "2.0.0" def test_builder_download_and_prepare_with_absolute_output_dir(tmp_path): builder = DummyGeneratorBasedBuilder() output_dir = str(tmp_path) builder.download_and_prepare(output_dir) assert builder._output_dir.startswith(tmp_path.resolve().as_posix()) assert os.path.exists(os.path.join(output_dir, "dataset_info.json")) assert os.path.exists(os.path.join(output_dir, f"{builder.dataset_name}-train.arrow")) assert not os.path.exists(os.path.join(output_dir + ".incomplete")) def test_builder_download_and_prepare_with_relative_output_dir(): with set_current_working_directory_to_temp_dir(): builder = DummyGeneratorBasedBuilder() output_dir = "test-out" builder.download_and_prepare(output_dir) assert Path(builder._output_dir).resolve().as_posix().startswith(Path(output_dir).resolve().as_posix()) assert os.path.exists(os.path.join(output_dir, "dataset_info.json")) assert os.path.exists(os.path.join(output_dir, f"{builder.dataset_name}-train.arrow")) assert not os.path.exists(os.path.join(output_dir + ".incomplete")) def test_builder_with_filesystem_download_and_prepare(tmp_path, mockfs): builder = DummyGeneratorBasedBuilder(cache_dir=tmp_path) builder.download_and_prepare("mock://my_dataset", storage_options=mockfs.storage_options) assert builder._output_dir.startswith("mock://my_dataset") assert is_local_path(builder._cache_downloaded_dir) assert isinstance(builder._fs, type(mockfs)) assert builder._fs.storage_options == mockfs.storage_options assert mockfs.exists("my_dataset/dataset_info.json") assert mockfs.exists(f"my_dataset/{builder.dataset_name}-train.arrow") assert not mockfs.exists("my_dataset.incomplete") def test_builder_with_filesystem_download_and_prepare_reload(tmp_path, mockfs, caplog): builder = DummyGeneratorBasedBuilder(cache_dir=tmp_path) mockfs.makedirs("my_dataset") DatasetInfo().write_to_directory("mock://my_dataset", storage_options=mockfs.storage_options) mockfs.touch(f"my_dataset/{builder.dataset_name}-train.arrow") caplog.clear() with caplog.at_level(INFO, logger=get_logger().name): builder.download_and_prepare("mock://my_dataset", storage_options=mockfs.storage_options) assert "Found cached dataset" in caplog.text def test_generator_based_builder_download_and_prepare_as_parquet(tmp_path): builder = DummyGeneratorBasedBuilder(cache_dir=tmp_path) builder.download_and_prepare(file_format="parquet") assert builder.info.splits["train"].num_examples == 100 parquet_path = os.path.join( tmp_path, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train.parquet" ) assert os.path.exists(parquet_path) assert pq.ParquetFile(parquet_path) is not None def test_generator_based_builder_download_and_prepare_sharded(tmp_path): writer_batch_size = 25 builder = DummyGeneratorBasedBuilder(cache_dir=tmp_path, writer_batch_size=writer_batch_size) with patch("datasets.config.MAX_SHARD_SIZE", 1): # one batch per shard builder.download_and_prepare(file_format="parquet") expected_num_shards = 100 // writer_batch_size assert builder.info.splits["train"].num_examples == 100 parquet_path = os.path.join( tmp_path, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train-00000-of-{expected_num_shards:05d}.parquet", ) assert os.path.exists(parquet_path) parquet_files = [ pq.ParquetFile(parquet_path) for parquet_path in Path(tmp_path).rglob( f"{builder.dataset_name}-train-*-of-{expected_num_shards:05d}.parquet" ) ] assert len(parquet_files) == expected_num_shards assert sum(parquet_file.metadata.num_rows for parquet_file in parquet_files) == 100 def test_generator_based_builder_download_and_prepare_with_max_shard_size(tmp_path): writer_batch_size = 25 builder = DummyGeneratorBasedBuilder(cache_dir=tmp_path, writer_batch_size=writer_batch_size) builder.download_and_prepare(file_format="parquet", max_shard_size=1) # one batch per shard expected_num_shards = 100 // writer_batch_size assert builder.info.splits["train"].num_examples == 100 parquet_path = os.path.join( tmp_path, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train-00000-of-{expected_num_shards:05d}.parquet", ) assert os.path.exists(parquet_path) parquet_files = [ pq.ParquetFile(parquet_path) for parquet_path in Path(tmp_path).rglob( f"{builder.dataset_name}-train-*-of-{expected_num_shards:05d}.parquet" ) ] assert len(parquet_files) == expected_num_shards assert sum(parquet_file.metadata.num_rows for parquet_file in parquet_files) == 100 def test_generator_based_builder_download_and_prepare_with_num_proc(tmp_path): builder = DummyGeneratorBasedBuilderWithShards(cache_dir=tmp_path) builder.download_and_prepare(num_proc=2) expected_num_shards = 2 assert builder.info.splits["train"].num_examples == 400 assert builder.info.splits["train"].shard_lengths == [200, 200] arrow_path = os.path.join( tmp_path, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train-00000-of-{expected_num_shards:05d}.arrow", ) assert os.path.exists(arrow_path) ds = builder.as_dataset("train") assert len(ds) == 400 assert ds.to_dict() == { "id": [i for _ in range(4) for i in range(100)], "filepath": [f"data{i}.txt" for i in range(4) for _ in range(100)], } @pytest.mark.parametrize( "num_proc, expectation", [(None, does_not_raise()), (1, does_not_raise()), (2, pytest.raises(RuntimeError))] ) def test_generator_based_builder_download_and_prepare_with_ambiguous_shards(num_proc, expectation, tmp_path): builder = DummyGeneratorBasedBuilderWithAmbiguousShards(cache_dir=tmp_path) with expectation: builder.download_and_prepare(num_proc=num_proc) def test_arrow_based_builder_download_and_prepare_as_parquet(tmp_path): builder = DummyArrowBasedBuilder(cache_dir=tmp_path) builder.download_and_prepare(file_format="parquet") assert builder.info.splits["train"].num_examples == 100 parquet_path = os.path.join( tmp_path, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train.parquet" ) assert os.path.exists(parquet_path) assert pq.ParquetFile(parquet_path) is not None def test_arrow_based_builder_download_and_prepare_sharded(tmp_path): builder = DummyArrowBasedBuilder(cache_dir=tmp_path) with patch("datasets.config.MAX_SHARD_SIZE", 1): # one batch per shard builder.download_and_prepare(file_format="parquet") expected_num_shards = 10 assert builder.info.splits["train"].num_examples == 100 parquet_path = os.path.join( tmp_path, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train-00000-of-{expected_num_shards:05d}.parquet", ) assert os.path.exists(parquet_path) parquet_files = [ pq.ParquetFile(parquet_path) for parquet_path in Path(tmp_path).rglob( f"{builder.dataset_name}-train-*-of-{expected_num_shards:05d}.parquet" ) ] assert len(parquet_files) == expected_num_shards assert sum(parquet_file.metadata.num_rows for parquet_file in parquet_files) == 100 def test_arrow_based_builder_download_and_prepare_with_max_shard_size(tmp_path): builder = DummyArrowBasedBuilder(cache_dir=tmp_path) builder.download_and_prepare(file_format="parquet", max_shard_size=1) # one table per shard expected_num_shards = 10 assert builder.info.splits["train"].num_examples == 100 parquet_path = os.path.join( tmp_path, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train-00000-of-{expected_num_shards:05d}.parquet", ) assert os.path.exists(parquet_path) parquet_files = [ pq.ParquetFile(parquet_path) for parquet_path in Path(tmp_path).rglob( f"{builder.dataset_name}-train-*-of-{expected_num_shards:05d}.parquet" ) ] assert len(parquet_files) == expected_num_shards assert sum(parquet_file.metadata.num_rows for parquet_file in parquet_files) == 100 def test_arrow_based_builder_download_and_prepare_with_num_proc(tmp_path): builder = DummyArrowBasedBuilderWithShards(cache_dir=tmp_path) builder.download_and_prepare(num_proc=2) expected_num_shards = 2 assert builder.info.splits["train"].num_examples == 400 assert builder.info.splits["train"].shard_lengths == [200, 200] arrow_path = os.path.join( tmp_path, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train-00000-of-{expected_num_shards:05d}.arrow", ) assert os.path.exists(arrow_path) ds = builder.as_dataset("train") assert len(ds) == 400 assert ds.to_dict() == { "id": [i for _ in range(4) for i in range(100)], "filepath": [f"data{i}.txt" for i in range(4) for _ in range(100)], } @pytest.mark.parametrize( "num_proc, expectation", [(None, does_not_raise()), (1, does_not_raise()), (2, pytest.raises(RuntimeError))] ) def test_arrow_based_builder_download_and_prepare_with_ambiguous_shards(num_proc, expectation, tmp_path): builder = DummyArrowBasedBuilderWithAmbiguousShards(cache_dir=tmp_path) with expectation: builder.download_and_prepare(num_proc=num_proc) @require_beam def test_beam_based_builder_download_and_prepare_as_parquet(tmp_path): builder = DummyBeamBasedBuilder(cache_dir=tmp_path, beam_runner="DirectRunner") builder.download_and_prepare(file_format="parquet") assert builder.info.splits["train"].num_examples == 100 parquet_path = os.path.join( tmp_path, builder.dataset_name, "default", "0.0.0", f"{builder.dataset_name}-train.parquet" ) assert os.path.exists(parquet_path) assert pq.ParquetFile(parquet_path) is not None
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_data_files.py
import os from pathlib import Path, PurePath from typing import List from unittest.mock import patch import fsspec import pytest from fsspec.registry import _registry as _fsspec_registry from fsspec.spec import AbstractFileSystem from datasets.data_files import ( DataFilesDict, DataFilesList, _get_data_files_patterns, _get_metadata_files_patterns, _is_inside_unrequested_special_dir, _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir, resolve_pattern, ) from datasets.fingerprint import Hasher _TEST_PATTERNS = ["*", "**", "**/*", "*.txt", "data/*", "**/*.txt", "**/train.txt"] _FILES_TO_IGNORE = {".dummy", "README.md", "dummy_data.zip", "dataset_infos.json"} _DIRS_TO_IGNORE = {"data/.dummy_subdir", "__pycache__"} _TEST_PATTERNS_SIZES = { "*": 0, "**": 4, "**/*": 4, "*.txt": 0, "data/*": 2, "data/**": 4, "**/*.txt": 4, "**/train.txt": 2, } _TEST_URL = "https://raw.githubusercontent.com/huggingface/datasets/9675a5a1e7b99a86f9c250f6ea5fa5d1e6d5cc7d/setup.py" @pytest.fixture def complex_data_dir(tmp_path): data_dir = tmp_path / "complex_data_dir" data_dir.mkdir() (data_dir / "data").mkdir() with open(data_dir / "data" / "train.txt", "w") as f: f.write("foo\n" * 10) with open(data_dir / "data" / "test.txt", "w") as f: f.write("bar\n" * 10) with open(data_dir / "README.md", "w") as f: f.write("This is a readme") with open(data_dir / ".dummy", "w") as f: f.write("this is a dummy file that is not a data file") (data_dir / "data" / "subdir").mkdir() with open(data_dir / "data" / "subdir" / "train.txt", "w") as f: f.write("foo\n" * 10) with open(data_dir / "data" / "subdir" / "test.txt", "w") as f: f.write("bar\n" * 10) (data_dir / "data" / ".dummy_subdir").mkdir() with open(data_dir / "data" / ".dummy_subdir" / "train.txt", "w") as f: f.write("foo\n" * 10) with open(data_dir / "data" / ".dummy_subdir" / "test.txt", "w") as f: f.write("bar\n" * 10) (data_dir / "__pycache__").mkdir() with open(data_dir / "__pycache__" / "script.py", "w") as f: f.write("foo\n" * 10) return str(data_dir) def is_relative_to(path, *other): # A built-in method in Python 3.9+ try: path.relative_to(*other) return True except ValueError: return False @pytest.fixture def pattern_results(complex_data_dir): # We use fsspec glob as a reference for data files resolution from patterns. # This is the same as dask for example. # # /!\ Here are some behaviors specific to fsspec glob that are different from glob.glob, Path.glob, Path.match or fnmatch: # - '*' matches only first level items # - '**' matches all items # - '**/*' matches all at least second level items # # More generally: # - '*' matches any character except a forward-slash (to match just the file or directory name) # - '**' matches any character including a forward-slash / return { pattern: sorted( Path(os.path.abspath(path)).as_posix() for path in fsspec.filesystem("file").glob(os.path.join(complex_data_dir, pattern)) if Path(path).name not in _FILES_TO_IGNORE and not any( is_relative_to(Path(path), os.path.join(complex_data_dir, dir_path)) for dir_path in _DIRS_TO_IGNORE ) and Path(path).is_file() ) for pattern in _TEST_PATTERNS } @pytest.fixture def hub_dataset_repo_path(tmpfs, complex_data_dir): for path in Path(complex_data_dir).rglob("*"): if path.is_file(): with tmpfs.open(path.relative_to(complex_data_dir).as_posix(), "wb") as f: f.write(path.read_bytes()) yield "tmp://" @pytest.fixture def hub_dataset_repo_patterns_results(hub_dataset_repo_path, complex_data_dir, pattern_results): return { pattern: [ hub_dataset_repo_path + Path(path).relative_to(complex_data_dir).as_posix() for path in pattern_results[pattern] ] for pattern in pattern_results } def test_is_inside_unrequested_special_dir(complex_data_dir, pattern_results): # usual patterns outside special dir work fine for pattern, result in pattern_results.items(): if result: matched_rel_path = str(Path(result[0]).relative_to(complex_data_dir)) assert _is_inside_unrequested_special_dir(matched_rel_path, pattern) is False # check behavior for special dir f = _is_inside_unrequested_special_dir assert f("__pycache__/b.txt", "**") is True assert f("__pycache__/b.txt", "*/b.txt") is True assert f("__pycache__/b.txt", "__pycache__/*") is False assert f("__pycache__/__b.txt", "__pycache__/*") is False assert f("__pycache__/__b.txt", "__*/*") is False assert f("__b.txt", "*") is False def test_is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(complex_data_dir, pattern_results): # usual patterns outside hidden dir work fine for pattern, result in pattern_results.items(): if result: matched_rel_path = str(Path(result[0]).relative_to(complex_data_dir)) assert _is_inside_unrequested_special_dir(matched_rel_path, pattern) is False # check behavior for hidden dir and file f = _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir assert f(".hidden_file.txt", "**") is True assert f(".hidden_file.txt", ".*") is False assert f(".hidden_dir/a.txt", "**") is True assert f(".hidden_dir/a.txt", ".*/*") is False assert f(".hidden_dir/a.txt", ".hidden_dir/*") is False assert f(".hidden_dir/.hidden_file.txt", "**") is True assert f(".hidden_dir/.hidden_file.txt", ".*/*") is True assert f(".hidden_dir/.hidden_file.txt", ".*/.*") is False assert f(".hidden_dir/.hidden_file.txt", ".hidden_dir/*") is True assert f(".hidden_dir/.hidden_file.txt", ".hidden_dir/.*") is False @pytest.mark.parametrize("pattern", _TEST_PATTERNS) def test_pattern_results_fixture(pattern_results, pattern): assert len(pattern_results[pattern]) == _TEST_PATTERNS_SIZES[pattern] assert all(Path(path).is_file() for path in pattern_results[pattern]) @pytest.mark.parametrize("pattern", _TEST_PATTERNS) def test_resolve_pattern_locally(complex_data_dir, pattern, pattern_results): try: resolved_data_files = resolve_pattern(pattern, complex_data_dir) assert sorted(str(f) for f in resolved_data_files) == pattern_results[pattern] except FileNotFoundError: assert len(pattern_results[pattern]) == 0 def test_resolve_pattern_locally_with_dot_in_base_path(complex_data_dir): base_path_with_dot = os.path.join(complex_data_dir, "data", ".dummy_subdir") resolved_data_files = resolve_pattern(os.path.join(base_path_with_dot, "train.txt"), base_path_with_dot) assert len(resolved_data_files) == 1 def test_resolve_pattern_locally_with_absolute_path(tmp_path, complex_data_dir): abs_path = os.path.join(complex_data_dir, "data", "train.txt") resolved_data_files = resolve_pattern(abs_path, str(tmp_path / "blabla")) assert len(resolved_data_files) == 1 def test_resolve_pattern_locally_with_double_dots(tmp_path, complex_data_dir): path_with_double_dots = os.path.join(complex_data_dir, "data", "subdir", "..", "train.txt") resolved_data_files = resolve_pattern(path_with_double_dots, str(tmp_path / "blabla")) assert len(resolved_data_files) == 1 def test_resolve_pattern_locally_returns_hidden_file_only_if_requested(complex_data_dir): with pytest.raises(FileNotFoundError): resolve_pattern("*dummy", complex_data_dir) resolved_data_files = resolve_pattern(".dummy", complex_data_dir) assert len(resolved_data_files) == 1 def test_resolve_pattern_locally_hidden_base_path(tmp_path): hidden = tmp_path / ".test_hidden_base_path" hidden.mkdir() (tmp_path / ".test_hidden_base_path" / "a.txt").touch() resolved_data_files = resolve_pattern("*", str(hidden)) assert len(resolved_data_files) == 1 def test_resolve_pattern_locallyreturns_hidden_dir_only_if_requested(complex_data_dir): with pytest.raises(FileNotFoundError): resolve_pattern("data/*dummy_subdir/train.txt", complex_data_dir) resolved_data_files = resolve_pattern("data/.dummy_subdir/train.txt", complex_data_dir) assert len(resolved_data_files) == 1 resolved_data_files = resolve_pattern("*/.dummy_subdir/train.txt", complex_data_dir) assert len(resolved_data_files) == 1 def test_resolve_pattern_locally_returns_special_dir_only_if_requested(complex_data_dir): with pytest.raises(FileNotFoundError): resolve_pattern("data/*dummy_subdir/train.txt", complex_data_dir) resolved_data_files = resolve_pattern("data/.dummy_subdir/train.txt", complex_data_dir) assert len(resolved_data_files) == 1 resolved_data_files = resolve_pattern("*/.dummy_subdir/train.txt", complex_data_dir) assert len(resolved_data_files) == 1 def test_resolve_pattern_locally_special_base_path(tmp_path): special = tmp_path / "__test_special_base_path__" special.mkdir() (tmp_path / "__test_special_base_path__" / "a.txt").touch() resolved_data_files = resolve_pattern("*", str(special)) assert len(resolved_data_files) == 1 @pytest.mark.parametrize("pattern,size,extensions", [("**", 4, [".txt"]), ("**", 4, None), ("**", 0, [".blablabla"])]) def test_resolve_pattern_locally_with_extensions(complex_data_dir, pattern, size, extensions): if size > 0: resolved_data_files = resolve_pattern(pattern, complex_data_dir, allowed_extensions=extensions) assert len(resolved_data_files) == size else: with pytest.raises(FileNotFoundError): resolve_pattern(pattern, complex_data_dir, allowed_extensions=extensions) def test_fail_resolve_pattern_locally(complex_data_dir): with pytest.raises(FileNotFoundError): resolve_pattern(complex_data_dir, ["blablabla"]) @pytest.mark.skipif(os.name == "nt", reason="Windows does not support symlinks in the default mode") def test_resolve_pattern_locally_does_not_resolve_symbolic_links(tmp_path, complex_data_dir): (tmp_path / "train_data_symlink.txt").symlink_to(os.path.join(complex_data_dir, "data", "train.txt")) resolved_data_files = resolve_pattern("train_data_symlink.txt", str(tmp_path)) assert len(resolved_data_files) == 1 assert Path(resolved_data_files[0]) == tmp_path / "train_data_symlink.txt" def test_resolve_pattern_locally_sorted_files(tmp_path_factory): path = str(tmp_path_factory.mktemp("unsorted_text_files")) unsorted_names = ["0.txt", "2.txt", "3.txt"] for name in unsorted_names: with open(os.path.join(path, name), "w"): pass resolved_data_files = resolve_pattern("*", path) resolved_names = [os.path.basename(data_file) for data_file in resolved_data_files] assert resolved_names == sorted(unsorted_names) @pytest.mark.parametrize("pattern", _TEST_PATTERNS) def test_resolve_pattern_in_dataset_repository(hub_dataset_repo_path, pattern, hub_dataset_repo_patterns_results): try: resolved_data_files = resolve_pattern(pattern, hub_dataset_repo_path) assert sorted(str(f) for f in resolved_data_files) == hub_dataset_repo_patterns_results[pattern] except FileNotFoundError: assert len(hub_dataset_repo_patterns_results[pattern]) == 0 @pytest.mark.parametrize( "pattern,size,base_path", [("**", 4, None), ("**", 4, "data"), ("**", 2, "data/subdir"), ("**", 0, "data/subdir2")] ) def test_resolve_pattern_in_dataset_repository_with_base_path(hub_dataset_repo_path, pattern, size, base_path): base_path = hub_dataset_repo_path + (base_path or "") if size > 0: resolved_data_files = resolve_pattern(pattern, base_path) assert len(resolved_data_files) == size else: with pytest.raises(FileNotFoundError): resolve_pattern(pattern, base_path) @pytest.mark.parametrize("pattern,size,extensions", [("**", 4, [".txt"]), ("**", 4, None), ("**", 0, [".blablabla"])]) def test_resolve_pattern_in_dataset_repository_with_extensions(hub_dataset_repo_path, pattern, size, extensions): if size > 0: resolved_data_files = resolve_pattern(pattern, hub_dataset_repo_path, allowed_extensions=extensions) assert len(resolved_data_files) == size else: with pytest.raises(FileNotFoundError): resolved_data_files = resolve_pattern(pattern, hub_dataset_repo_path, allowed_extensions=extensions) def test_fail_resolve_pattern_in_dataset_repository(hub_dataset_repo_path): with pytest.raises(FileNotFoundError): resolve_pattern("blablabla", hub_dataset_repo_path) def test_resolve_pattern_in_dataset_repository_returns_hidden_file_only_if_requested(hub_dataset_repo_path): with pytest.raises(FileNotFoundError): resolve_pattern("*dummy", hub_dataset_repo_path) resolved_data_files = resolve_pattern(".dummy", hub_dataset_repo_path) assert len(resolved_data_files) == 1 def test_resolve_pattern_in_dataset_repository_hidden_base_path(tmpfs): tmpfs.touch(".hidden/a.txt") resolved_data_files = resolve_pattern("*", base_path="tmp://.hidden") assert len(resolved_data_files) == 1 def test_resolve_pattern_in_dataset_repository_returns_hidden_dir_only_if_requested(hub_dataset_repo_path): with pytest.raises(FileNotFoundError): resolve_pattern("data/*dummy_subdir/train.txt", hub_dataset_repo_path) resolved_data_files = resolve_pattern("data/.dummy_subdir/train.txt", hub_dataset_repo_path) assert len(resolved_data_files) == 1 resolved_data_files = resolve_pattern("*/.dummy_subdir/train.txt", hub_dataset_repo_path) assert len(resolved_data_files) == 1 def test_resolve_pattern_in_dataset_repository_returns_special_dir_only_if_requested(hub_dataset_repo_path): with pytest.raises(FileNotFoundError): resolve_pattern("data/*dummy_subdir/train.txt", hub_dataset_repo_path) resolved_data_files = resolve_pattern("data/.dummy_subdir/train.txt", hub_dataset_repo_path) assert len(resolved_data_files) == 1 resolved_data_files = resolve_pattern("*/.dummy_subdir/train.txt", hub_dataset_repo_path) assert len(resolved_data_files) == 1 def test_resolve_pattern_in_dataset_repository_special_base_path(tmpfs): tmpfs.touch("__special__/a.txt") resolved_data_files = resolve_pattern("*", base_path="tmp://__special__") assert len(resolved_data_files) == 1 @pytest.fixture def dummy_fs(): DummyTestFS = mock_fs(["train.txt", "test.txt"]) _fsspec_registry["mock"] = DummyTestFS _fsspec_registry["dummy"] = DummyTestFS yield del _fsspec_registry["mock"] del _fsspec_registry["dummy"] def test_resolve_pattern_fs(dummy_fs): resolved_data_files = resolve_pattern("mock://train.txt", base_path="") assert resolved_data_files == ["mock://train.txt"] @pytest.mark.parametrize("pattern", _TEST_PATTERNS) def test_DataFilesList_from_patterns_in_dataset_repository_( hub_dataset_repo_path, hub_dataset_repo_patterns_results, pattern ): try: data_files_list = DataFilesList.from_patterns([pattern], hub_dataset_repo_path) assert sorted(data_files_list) == hub_dataset_repo_patterns_results[pattern] assert len(data_files_list.origin_metadata) == len(data_files_list) except FileNotFoundError: assert len(hub_dataset_repo_patterns_results[pattern]) == 0 def test_DataFilesList_from_patterns_locally_with_extra_files(complex_data_dir, text_file): data_files_list = DataFilesList.from_patterns([_TEST_URL, text_file.as_posix()], complex_data_dir) assert list(data_files_list) == [_TEST_URL, text_file.as_posix()] assert len(data_files_list.origin_metadata) == 2 @pytest.mark.parametrize("pattern", _TEST_PATTERNS) def test_DataFilesDict_from_patterns_in_dataset_repository( hub_dataset_repo_path, hub_dataset_repo_patterns_results, pattern ): split_name = "train" try: data_files = DataFilesDict.from_patterns({split_name: [pattern]}, hub_dataset_repo_path) assert all(isinstance(data_files_list, DataFilesList) for data_files_list in data_files.values()) assert sorted(data_files[split_name]) == hub_dataset_repo_patterns_results[pattern] except FileNotFoundError: assert len(hub_dataset_repo_patterns_results[pattern]) == 0 @pytest.mark.parametrize( "pattern,size,base_path,split_name", [ ("**", 4, None, "train"), ("**", 4, "data", "train"), ("**", 2, "data/subdir", "train"), ("**train*", 1, "data/subdir", "train"), ("**test*", 1, "data/subdir", "test"), ("**", 0, "data/subdir2", "train"), ], ) def test_DataFilesDict_from_patterns_in_dataset_repository_with_base_path( hub_dataset_repo_path, pattern, size, base_path, split_name ): base_path = hub_dataset_repo_path + (base_path or "") if size > 0: data_files = DataFilesDict.from_patterns({split_name: [pattern]}, base_path=base_path) assert len(data_files[split_name]) == size else: with pytest.raises(FileNotFoundError): resolve_pattern(pattern, base_path) @pytest.mark.parametrize("pattern", _TEST_PATTERNS) def test_DataFilesDict_from_patterns_locally(complex_data_dir, pattern_results, pattern): split_name = "train" try: data_files = DataFilesDict.from_patterns({split_name: [pattern]}, complex_data_dir) assert all(isinstance(data_files_list, DataFilesList) for data_files_list in data_files.values()) assert sorted(data_files[split_name]) == pattern_results[pattern] except FileNotFoundError: assert len(pattern_results[pattern]) == 0 def test_DataFilesDict_from_patterns_in_dataset_repository_hashing(hub_dataset_repo_path): patterns = {"train": ["**/train.txt"], "test": ["**/test.txt"]} data_files1 = DataFilesDict.from_patterns(patterns, hub_dataset_repo_path) data_files2 = DataFilesDict.from_patterns(patterns, hub_dataset_repo_path) assert Hasher.hash(data_files1) == Hasher.hash(data_files2) data_files2 = DataFilesDict(sorted(data_files1.items(), reverse=True)) assert Hasher.hash(data_files1) == Hasher.hash(data_files2) patterns2 = {"train": ["data/**train.txt"], "test": ["data/**test.txt"]} data_files2 = DataFilesDict.from_patterns(patterns2, hub_dataset_repo_path) assert Hasher.hash(data_files1) == Hasher.hash(data_files2) patterns2 = {"train": ["data/**train.txt"], "test": ["data/**train.txt"]} data_files2 = DataFilesDict.from_patterns(patterns2, hub_dataset_repo_path) assert Hasher.hash(data_files1) != Hasher.hash(data_files2) # the tmpfs used to mock the hub repo is based on a local directory # therefore os.stat is used to get the mtime of the data files with patch("os.stat", return_value=os.stat(__file__)): data_files2 = DataFilesDict.from_patterns(patterns, hub_dataset_repo_path) assert Hasher.hash(data_files1) != Hasher.hash(data_files2) def test_DataFilesDict_from_patterns_locally_or_remote_hashing(text_file): patterns = {"train": [_TEST_URL], "test": [str(text_file)]} data_files1 = DataFilesDict.from_patterns(patterns) data_files2 = DataFilesDict.from_patterns(patterns) assert Hasher.hash(data_files1) == Hasher.hash(data_files2) data_files2 = DataFilesDict(sorted(data_files1.items(), reverse=True)) assert Hasher.hash(data_files1) == Hasher.hash(data_files2) patterns2 = {"train": [_TEST_URL], "test": [_TEST_URL]} data_files2 = DataFilesDict.from_patterns(patterns2) assert Hasher.hash(data_files1) != Hasher.hash(data_files2) with patch("fsspec.implementations.http._file_info", return_value={}): data_files2 = DataFilesDict.from_patterns(patterns) assert Hasher.hash(data_files1) != Hasher.hash(data_files2) with patch("os.stat", return_value=os.stat(__file__)): data_files2 = DataFilesDict.from_patterns(patterns) assert Hasher.hash(data_files1) != Hasher.hash(data_files2) def mock_fs(file_paths: List[str]): """ Set up a mock filesystem for fsspec containing the provided files Example: ```py >>> fs = mock_fs(["data/train.txt", "data.test.txt"]) >>> assert fsspec.get_filesystem_class("mock").__name__ == "DummyTestFS" >>> assert type(fs).__name__ == "DummyTestFS" >>> print(fs.glob("**")) ["data", "data/train.txt", "data.test.txt"] ``` """ dir_paths = {file_path.rsplit("/")[0] for file_path in file_paths if "/" in file_path} fs_contents = [{"name": dir_path, "type": "directory"} for dir_path in dir_paths] + [ {"name": file_path, "type": "file", "size": 10} for file_path in file_paths ] class DummyTestFS(AbstractFileSystem): protocol = ("mock", "dummy") _fs_contents = fs_contents def ls(self, path, detail=True, refresh=True, **kwargs): if kwargs.pop("strip_proto", True): path = self._strip_protocol(path) files = not refresh and self._ls_from_cache(path) if not files: files = [file for file in self._fs_contents if path == self._parent(file["name"])] files.sort(key=lambda file: file["name"]) self.dircache[path.rstrip("/")] = files if detail: return files return [file["name"] for file in files] return DummyTestFS @pytest.mark.parametrize( "data_file_per_split", [ # === Main cases === # file named after split at the root {"train": "train.txt", "validation": "valid.txt", "test": "test.txt"}, # file named after split in a directory { "train": "data/train.txt", "validation": "data/valid.txt", "test": "data/test.txt", }, # directory named after split { "train": "train/split.txt", "validation": "valid/split.txt", "test": "test/split.txt", }, # sharded splits { "train": [f"data/train_{i}.txt" for i in range(3)], "validation": [f"data/validation_{i}.txt" for i in range(3)], "test": [f"data/test_{i}.txt" for i in range(3)], }, # sharded splits with standard format (+ custom split name) { "train": [f"data/train-0000{i}-of-00003.txt" for i in range(3)], "validation": [f"data/validation-0000{i}-of-00003.txt" for i in range(3)], "test": [f"data/test-0000{i}-of-00003.txt" for i in range(3)], "random": [f"data/random-0000{i}-of-00003.txt" for i in range(3)], }, # === Secondary cases === # Default to train split {"train": "dataset.txt"}, {"train": "data/dataset.txt"}, {"train": ["data/image.jpg", "metadata.jsonl"]}, {"train": ["data/image.jpg", "metadata.csv"]}, # With prefix or suffix in directory or file names {"train": "my_train_dir/dataset.txt"}, {"train": "data/my_train_file.txt"}, {"test": "my_test_dir/dataset.txt"}, {"test": "data/my_test_file.txt"}, {"validation": "my_validation_dir/dataset.txt"}, {"validation": "data/my_validation_file.txt"}, # With test<>eval aliases {"test": "eval.txt"}, {"test": "data/eval.txt"}, {"test": "eval/dataset.txt"}, # With valid<>dev aliases {"validation": "dev.txt"}, {"validation": "data/dev.txt"}, {"validation": "dev/dataset.txt"}, # With valid<>val aliases {"validation": "val.txt"}, {"validation": "data/val.txt"}, # With other extensions {"train": "train.parquet", "validation": "valid.parquet", "test": "test.parquet"}, # With "dev" or "eval" without separators {"train": "developers_list.txt"}, {"train": "data/seqeval_results.txt"}, {"train": "contest.txt"}, # With supported separators {"test": "my.test.file.txt"}, {"test": "my-test-file.txt"}, {"test": "my_test_file.txt"}, {"test": "my test file.txt"}, {"test": "test00001.txt"}, ], ) def test_get_data_files_patterns(data_file_per_split): data_file_per_split = {k: v if isinstance(v, list) else [v] for k, v in data_file_per_split.items()} file_paths = [file_path for split_file_paths in data_file_per_split.values() for file_path in split_file_paths] DummyTestFS = mock_fs(file_paths) fs = DummyTestFS() def resolver(pattern): return [file_path for file_path in fs.glob(pattern) if fs.isfile(file_path)] patterns_per_split = _get_data_files_patterns(resolver) assert list(patterns_per_split.keys()) == list(data_file_per_split.keys()) # Test split order with list() for split, patterns in patterns_per_split.items(): matched = [file_path for pattern in patterns for file_path in resolver(pattern)] assert matched == data_file_per_split[split] @pytest.mark.parametrize( "metadata_files", [ # metadata files at the root ["metadata.jsonl"], ["metadata.csv"], # nested metadata files ["data/metadata.jsonl", "data/train/metadata.jsonl"], ["data/metadata.csv", "data/train/metadata.csv"], ], ) def test_get_metadata_files_patterns(metadata_files): def resolver(pattern): return [PurePath(path) for path in set(metadata_files) if PurePath(path).match(pattern)] patterns = _get_metadata_files_patterns(resolver) matched = [path for path in metadata_files for pattern in patterns if PurePath(path).match(pattern)] # Use set to remove the difference between in behavior between PurePath.match and mathcing via fsspec.glob assert len(set(matched)) == len(metadata_files) assert sorted(set(matched)) == sorted(metadata_files)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_dataset_dict.py
import os import tempfile from unittest import TestCase import numpy as np import pandas as pd import pytest from datasets import load_from_disk from datasets.arrow_dataset import Dataset from datasets.dataset_dict import DatasetDict, IterableDatasetDict from datasets.features import ClassLabel, Features, Sequence, Value from datasets.iterable_dataset import IterableDataset from datasets.splits import NamedSplit from .utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_tf, require_torch class DatasetDictTest(TestCase): def _create_dummy_dataset(self, multiple_columns=False): if multiple_columns: data = {"col_1": [3, 2, 1, 0], "col_2": ["a", "b", "c", "d"]} dset = Dataset.from_dict(data) else: dset = Dataset.from_dict( {"filename": ["my_name-train" + "_" + f"{x:03d}" for x in np.arange(30).tolist()]} ) return dset def _create_dummy_dataset_dict(self, multiple_columns=False) -> DatasetDict: return DatasetDict( { "train": self._create_dummy_dataset(multiple_columns=multiple_columns), "test": self._create_dummy_dataset(multiple_columns=multiple_columns), } ) def _create_dummy_iterable_dataset(self, multiple_columns=False) -> IterableDataset: def gen(): if multiple_columns: data = {"col_1": [3, 2, 1, 0], "col_2": ["a", "b", "c", "d"]} for v1, v2 in zip(data["col_1"], data["col_2"]): yield {"col_1": v1, "col_2": v2} else: for x in range(30): yield {"filename": "my_name-train" + "_" + f"{x:03d}"} return IterableDataset.from_generator(gen) def _create_dummy_iterable_dataset_dict(self, multiple_columns=False) -> IterableDatasetDict: return IterableDatasetDict( { "train": self._create_dummy_iterable_dataset(multiple_columns=multiple_columns), "test": self._create_dummy_iterable_dataset(multiple_columns=multiple_columns), } ) def test_flatten(self): dset_split = Dataset.from_dict( {"a": [{"b": {"c": ["text"]}}] * 10, "foo": [1] * 10}, features=Features({"a": {"b": Sequence({"c": Value("string")})}, "foo": Value("int64")}), ) dset = DatasetDict({"train": dset_split, "test": dset_split}) dset = dset.flatten() self.assertDictEqual(dset.column_names, {"train": ["a.b.c", "foo"], "test": ["a.b.c", "foo"]}) self.assertListEqual(sorted(dset["train"].features.keys()), ["a.b.c", "foo"]) self.assertDictEqual( dset["train"].features, Features({"a.b.c": Sequence(Value("string")), "foo": Value("int64")}) ) del dset def test_set_format_numpy(self): dset = self._create_dummy_dataset_dict(multiple_columns=True) dset.set_format(type="numpy", columns=["col_1"]) for dset_split in dset.values(): self.assertEqual(len(dset_split[0]), 1) self.assertIsInstance(dset_split[0]["col_1"], np.int64) self.assertEqual(dset_split[0]["col_1"].item(), 3) dset.reset_format() with dset.formatted_as(type="numpy", columns=["col_1"]): for dset_split in dset.values(): self.assertEqual(len(dset_split[0]), 1) self.assertIsInstance(dset_split[0]["col_1"], np.int64) self.assertEqual(dset_split[0]["col_1"].item(), 3) for dset_split in dset.values(): self.assertEqual(dset_split.format["type"], None) self.assertEqual(dset_split.format["format_kwargs"], {}) self.assertEqual(dset_split.format["columns"], dset_split.column_names) self.assertEqual(dset_split.format["output_all_columns"], False) dset.set_format(type="numpy", columns=["col_1"], output_all_columns=True) for dset_split in dset.values(): self.assertEqual(len(dset_split[0]), 2) self.assertIsInstance(dset_split[0]["col_2"], str) self.assertEqual(dset_split[0]["col_2"], "a") dset.set_format(type="numpy", columns=["col_1", "col_2"]) for dset_split in dset.values(): self.assertEqual(len(dset_split[0]), 2) self.assertIsInstance(dset_split[0]["col_2"], np.str_) self.assertEqual(dset_split[0]["col_2"].item(), "a") del dset @require_torch def test_set_format_torch(self): import torch dset = self._create_dummy_dataset_dict(multiple_columns=True) dset.set_format(type="torch", columns=["col_1"]) for dset_split in dset.values(): self.assertEqual(len(dset_split[0]), 1) self.assertIsInstance(dset_split[0]["col_1"], torch.Tensor) self.assertListEqual(list(dset_split[0]["col_1"].shape), []) self.assertEqual(dset_split[0]["col_1"].item(), 3) dset.set_format(type="torch", columns=["col_1"], output_all_columns=True) for dset_split in dset.values(): self.assertEqual(len(dset_split[0]), 2) self.assertIsInstance(dset_split[0]["col_2"], str) self.assertEqual(dset_split[0]["col_2"], "a") dset.set_format(type="torch") for dset_split in dset.values(): self.assertEqual(len(dset_split[0]), 2) self.assertIsInstance(dset_split[0]["col_1"], torch.Tensor) self.assertListEqual(list(dset_split[0]["col_1"].shape), []) self.assertEqual(dset_split[0]["col_1"].item(), 3) self.assertIsInstance(dset_split[0]["col_2"], str) self.assertEqual(dset_split[0]["col_2"], "a") del dset @require_tf def test_set_format_tf(self): import tensorflow as tf dset = self._create_dummy_dataset_dict(multiple_columns=True) dset.set_format(type="tensorflow", columns=["col_1"]) for dset_split in dset.values(): self.assertEqual(len(dset_split[0]), 1) self.assertIsInstance(dset_split[0]["col_1"], tf.Tensor) self.assertListEqual(list(dset_split[0]["col_1"].shape), []) self.assertEqual(dset_split[0]["col_1"].numpy().item(), 3) dset.set_format(type="tensorflow", columns=["col_1"], output_all_columns=True) for dset_split in dset.values(): self.assertEqual(len(dset_split[0]), 2) self.assertIsInstance(dset_split[0]["col_2"], str) self.assertEqual(dset_split[0]["col_2"], "a") dset.set_format(type="tensorflow", columns=["col_1", "col_2"]) for dset_split in dset.values(): self.assertEqual(len(dset_split[0]), 2) self.assertEqual(dset_split[0]["col_2"].numpy().decode("utf-8"), "a") del dset def test_set_format_pandas(self): dset = self._create_dummy_dataset_dict(multiple_columns=True) dset.set_format(type="pandas", columns=["col_1"]) for dset_split in dset.values(): self.assertEqual(len(dset_split[0].columns), 1) self.assertIsInstance(dset_split[0], pd.DataFrame) self.assertListEqual(list(dset_split[0].shape), [1, 1]) self.assertEqual(dset_split[0]["col_1"].item(), 3) dset.set_format(type="pandas", columns=["col_1", "col_2"]) for dset_split in dset.values(): self.assertEqual(len(dset_split[0].columns), 2) self.assertEqual(dset_split[0]["col_2"].item(), "a") del dset def test_set_transform(self): def transform(batch): return {k: [str(i).upper() for i in v] for k, v in batch.items()} dset = self._create_dummy_dataset_dict(multiple_columns=True) dset.set_transform(transform=transform, columns=["col_1"]) for dset_split in dset.values(): self.assertEqual(dset_split.format["type"], "custom") self.assertEqual(len(dset_split[0].keys()), 1) self.assertEqual(dset_split[0]["col_1"], "3") self.assertEqual(dset_split[:2]["col_1"], ["3", "2"]) self.assertEqual(dset_split["col_1"][:2], ["3", "2"]) prev_format = dset[list(dset.keys())[0]].format for dset_split in dset.values(): dset_split.set_format(**dset_split.format) self.assertEqual(prev_format, dset_split.format) dset.set_transform(transform=transform, columns=["col_1", "col_2"]) for dset_split in dset.values(): self.assertEqual(len(dset_split[0].keys()), 2) self.assertEqual(dset_split[0]["col_2"], "A") del dset def test_with_format(self): dset = self._create_dummy_dataset_dict(multiple_columns=True) dset2 = dset.with_format("numpy", columns=["col_1"]) dset.set_format("numpy", columns=["col_1"]) for dset_split, dset_split2 in zip(dset.values(), dset2.values()): self.assertDictEqual(dset_split.format, dset_split2.format) del dset, dset2 def test_with_transform(self): def transform(batch): return {k: [str(i).upper() for i in v] for k, v in batch.items()} dset = self._create_dummy_dataset_dict(multiple_columns=True) dset2 = dset.with_transform(transform, columns=["col_1"]) dset.set_transform(transform, columns=["col_1"]) for dset_split, dset_split2 in zip(dset.values(), dset2.values()): self.assertDictEqual(dset_split.format, dset_split2.format) del dset, dset2 def test_cast(self): dset = self._create_dummy_dataset_dict(multiple_columns=True) features = dset["train"].features features["col_1"] = Value("float64") dset = dset.cast(features) for dset_split in dset.values(): self.assertEqual(dset_split.num_columns, 2) self.assertEqual(dset_split.features["col_1"], Value("float64")) self.assertIsInstance(dset_split[0]["col_1"], float) del dset def test_remove_columns(self): dset = self._create_dummy_dataset_dict(multiple_columns=True) dset = dset.remove_columns(column_names="col_1") for dset_split in dset.values(): self.assertEqual(dset_split.num_columns, 1) self.assertListEqual(list(dset_split.column_names), ["col_2"]) dset = self._create_dummy_dataset_dict(multiple_columns=True) dset = dset.remove_columns(column_names=["col_1", "col_2"]) for dset_split in dset.values(): self.assertEqual(dset_split.num_columns, 0) dset = self._create_dummy_dataset_dict(multiple_columns=True) for dset_split in dset.values(): dset_split._format_columns = ["col_1", "col_2"] dset = dset.remove_columns(column_names=["col_1"]) for dset_split in dset.values(): self.assertListEqual(dset_split._format_columns, ["col_2"]) self.assertEqual(dset_split.num_columns, 1) self.assertListEqual(list(dset_split.column_names), ["col_2"]) del dset def test_rename_column(self): dset = self._create_dummy_dataset_dict(multiple_columns=True) dset = dset.rename_column(original_column_name="col_1", new_column_name="new_name") for dset_split in dset.values(): self.assertEqual(dset_split.num_columns, 2) self.assertListEqual(list(dset_split.column_names), ["new_name", "col_2"]) del dset def test_select_columns(self): dset = self._create_dummy_dataset_dict(multiple_columns=True) dset = dset.select_columns(column_names=[]) for dset_split in dset.values(): self.assertEqual(dset_split.num_columns, 0) dset = self._create_dummy_dataset_dict(multiple_columns=True) dset = dset.select_columns(column_names="col_1") for dset_split in dset.values(): self.assertEqual(dset_split.num_columns, 1) self.assertListEqual(list(dset_split.column_names), ["col_1"]) dset = self._create_dummy_dataset_dict(multiple_columns=True) dset = dset.select_columns(column_names=["col_1", "col_2"]) for dset_split in dset.values(): self.assertEqual(dset_split.num_columns, 2) dset = self._create_dummy_dataset_dict(multiple_columns=True) for dset_split in dset.values(): dset_split._format_columns = ["col_1", "col_2"] dset = dset.select_columns(column_names=["col_1"]) for dset_split in dset.values(): self.assertEqual(dset_split.num_columns, 1) self.assertListEqual(list(dset_split.column_names), ["col_1"]) self.assertListEqual(dset_split._format_columns, ["col_1"]) def test_map(self): with tempfile.TemporaryDirectory() as tmp_dir: dsets = self._create_dummy_dataset_dict() mapped_dsets_1: DatasetDict = dsets.map(lambda ex: {"foo": ["bar"] * len(ex["filename"])}, batched=True) self.assertListEqual(list(dsets.keys()), list(mapped_dsets_1.keys())) self.assertListEqual(mapped_dsets_1["train"].column_names, ["filename", "foo"]) cache_file_names = { "train": os.path.join(tmp_dir, "train.arrow"), "test": os.path.join(tmp_dir, "test.arrow"), } mapped_dsets_2: DatasetDict = mapped_dsets_1.map( lambda ex: {"bar": ["foo"] * len(ex["filename"])}, batched=True, cache_file_names=cache_file_names ) self.assertListEqual(list(dsets.keys()), list(mapped_dsets_2.keys())) self.assertListEqual(sorted(mapped_dsets_2["train"].column_names), sorted(["filename", "foo", "bar"])) del dsets, mapped_dsets_1, mapped_dsets_2 def test_iterable_map(self): dsets = self._create_dummy_iterable_dataset_dict() fn_kwargs = {"n": 3} mapped_dsets: IterableDatasetDict = dsets.map( lambda x, n: {"foo": [n] * len(x["filename"])}, batched=True, fn_kwargs=fn_kwargs, ) mapped_example = next(iter(mapped_dsets["train"])) self.assertListEqual(sorted(mapped_example.keys()), sorted(["filename", "foo"])) self.assertLessEqual(mapped_example["foo"], 3) del dsets, mapped_dsets def test_filter(self): with tempfile.TemporaryDirectory() as tmp_dir: dsets = self._create_dummy_dataset_dict() filtered_dsets_1: DatasetDict = dsets.filter(lambda ex: int(ex["filename"].split("_")[-1]) < 10) self.assertListEqual(list(dsets.keys()), list(filtered_dsets_1.keys())) self.assertEqual(len(filtered_dsets_1["train"]), 10) cache_file_names = { "train": os.path.join(tmp_dir, "train.arrow"), "test": os.path.join(tmp_dir, "test.arrow"), } filtered_dsets_2: DatasetDict = filtered_dsets_1.filter( lambda ex: int(ex["filename"].split("_")[-1]) < 5, cache_file_names=cache_file_names ) self.assertListEqual(list(dsets.keys()), list(filtered_dsets_2.keys())) self.assertEqual(len(filtered_dsets_2["train"]), 5) filtered_dsets_3: DatasetDict = dsets.filter( lambda examples: [int(ex.split("_")[-1]) < 10 for ex in examples["filename"]], batched=True ) self.assertListEqual(list(dsets.keys()), list(filtered_dsets_3.keys())) self.assertEqual(len(filtered_dsets_3["train"]), 10) del dsets, filtered_dsets_1, filtered_dsets_2, filtered_dsets_3 def test_iterable_filter(self): dsets = self._create_dummy_iterable_dataset_dict() example = next(iter(dsets["train"])) fn_kwargs = {"n": 3} filtered_dsets: IterableDatasetDict = dsets.filter( lambda ex, n: n < int(ex["filename"].split("_")[-1]), fn_kwargs=fn_kwargs ) filtered_example = next(iter(filtered_dsets["train"])) self.assertListEqual(list(example.keys()), list(filtered_example.keys())) self.assertEqual(int(filtered_example["filename"].split("_")[-1]), 4) # id starts from 3 del dsets, filtered_dsets def test_sort(self): with tempfile.TemporaryDirectory() as tmp_dir: dsets = self._create_dummy_dataset_dict() sorted_dsets_1: DatasetDict = dsets.sort("filename") self.assertListEqual(list(dsets.keys()), list(sorted_dsets_1.keys())) self.assertListEqual( [f.split("_")[-1] for f in sorted_dsets_1["train"]["filename"]], sorted(f"{x:03d}" for x in range(30)), ) indices_cache_file_names = { "train": os.path.join(tmp_dir, "train.arrow"), "test": os.path.join(tmp_dir, "test.arrow"), } sorted_dsets_2: DatasetDict = sorted_dsets_1.sort( "filename", indices_cache_file_names=indices_cache_file_names, reverse=True ) self.assertListEqual(list(dsets.keys()), list(sorted_dsets_2.keys())) self.assertListEqual( [f.split("_")[-1] for f in sorted_dsets_2["train"]["filename"]], sorted((f"{x:03d}" for x in range(30)), reverse=True), ) del dsets, sorted_dsets_1, sorted_dsets_2 def test_shuffle(self): with tempfile.TemporaryDirectory() as tmp_dir: dsets = self._create_dummy_dataset_dict() indices_cache_file_names = { "train": os.path.join(tmp_dir, "train.arrow"), "test": os.path.join(tmp_dir, "test.arrow"), } seeds = { "train": 1234, "test": 1234, } dsets_shuffled = dsets.shuffle( seeds=seeds, indices_cache_file_names=indices_cache_file_names, load_from_cache_file=False ) self.assertListEqual(dsets_shuffled["train"]["filename"], dsets_shuffled["test"]["filename"]) self.assertEqual(len(dsets_shuffled["train"]), 30) self.assertEqual(dsets_shuffled["train"][0]["filename"], "my_name-train_028") self.assertEqual(dsets_shuffled["train"][2]["filename"], "my_name-train_010") self.assertDictEqual(dsets["train"].features, Features({"filename": Value("string")})) self.assertDictEqual(dsets_shuffled["train"].features, Features({"filename": Value("string")})) # Reproducibility indices_cache_file_names_2 = { "train": os.path.join(tmp_dir, "train_2.arrow"), "test": os.path.join(tmp_dir, "test_2.arrow"), } dsets_shuffled_2 = dsets.shuffle( seeds=seeds, indices_cache_file_names=indices_cache_file_names_2, load_from_cache_file=False ) self.assertListEqual(dsets_shuffled["train"]["filename"], dsets_shuffled_2["train"]["filename"]) seeds = { "train": 1234, "test": 1, } indices_cache_file_names_3 = { "train": os.path.join(tmp_dir, "train_3.arrow"), "test": os.path.join(tmp_dir, "test_3.arrow"), } dsets_shuffled_3 = dsets.shuffle( seeds=seeds, indices_cache_file_names=indices_cache_file_names_3, load_from_cache_file=False ) self.assertNotEqual(dsets_shuffled_3["train"]["filename"], dsets_shuffled_3["test"]["filename"]) # other input types dsets_shuffled_int = dsets.shuffle(42) dsets_shuffled_alias = dsets.shuffle(seed=42) dsets_shuffled_none = dsets.shuffle() self.assertEqual(len(dsets_shuffled_int["train"]), 30) self.assertEqual(len(dsets_shuffled_alias["train"]), 30) self.assertEqual(len(dsets_shuffled_none["train"]), 30) del dsets, dsets_shuffled, dsets_shuffled_2, dsets_shuffled_3 del dsets_shuffled_int, dsets_shuffled_alias, dsets_shuffled_none def test_flatten_indices(self): with tempfile.TemporaryDirectory() as tmp_dir: dsets = self._create_dummy_dataset_dict() indices_cache_file_names = { "train": os.path.join(tmp_dir, "train.arrow"), "test": os.path.join(tmp_dir, "test.arrow"), } dsets_shuffled = dsets.shuffle( seed=42, indices_cache_file_names=indices_cache_file_names, load_from_cache_file=False ) self.assertIsNotNone(dsets_shuffled["train"]._indices) self.assertIsNotNone(dsets_shuffled["test"]._indices) dsets_flat = dsets_shuffled.flatten_indices() self.assertIsNone(dsets_flat["train"]._indices) self.assertIsNone(dsets_flat["test"]._indices) del dsets, dsets_shuffled, dsets_flat def test_check_values_type(self): dsets = self._create_dummy_dataset_dict() dsets["bad_split"] = None self.assertRaises(TypeError, dsets.map, lambda x: x) self.assertRaises(TypeError, dsets.filter, lambda x: True) self.assertRaises(TypeError, dsets.shuffle) self.assertRaises(TypeError, dsets.sort, "filename") del dsets def test_serialization(self): with tempfile.TemporaryDirectory() as tmp_dir: dsets = self._create_dummy_dataset_dict() dsets.save_to_disk(tmp_dir) reloaded_dsets = DatasetDict.load_from_disk(tmp_dir) self.assertListEqual(sorted(reloaded_dsets), ["test", "train"]) self.assertEqual(len(reloaded_dsets["train"]), 30) self.assertListEqual(reloaded_dsets["train"].column_names, ["filename"]) self.assertEqual(len(reloaded_dsets["test"]), 30) self.assertListEqual(reloaded_dsets["test"].column_names, ["filename"]) del reloaded_dsets del dsets["test"] dsets.save_to_disk(tmp_dir) reloaded_dsets = DatasetDict.load_from_disk(tmp_dir) self.assertListEqual(sorted(reloaded_dsets), ["train"]) self.assertEqual(len(reloaded_dsets["train"]), 30) self.assertListEqual(reloaded_dsets["train"].column_names, ["filename"]) del dsets, reloaded_dsets dsets = self._create_dummy_dataset_dict() dsets.save_to_disk(tmp_dir, num_shards={"train": 3, "test": 2}) reloaded_dsets = DatasetDict.load_from_disk(tmp_dir) self.assertListEqual(sorted(reloaded_dsets), ["test", "train"]) self.assertEqual(len(reloaded_dsets["train"]), 30) self.assertListEqual(reloaded_dsets["train"].column_names, ["filename"]) self.assertEqual(len(reloaded_dsets["train"].cache_files), 3) self.assertEqual(len(reloaded_dsets["test"]), 30) self.assertListEqual(reloaded_dsets["test"].column_names, ["filename"]) self.assertEqual(len(reloaded_dsets["test"].cache_files), 2) del reloaded_dsets dsets = self._create_dummy_dataset_dict() dsets.save_to_disk(tmp_dir, num_proc=2) reloaded_dsets = DatasetDict.load_from_disk(tmp_dir) self.assertListEqual(sorted(reloaded_dsets), ["test", "train"]) self.assertEqual(len(reloaded_dsets["train"]), 30) self.assertListEqual(reloaded_dsets["train"].column_names, ["filename"]) self.assertEqual(len(reloaded_dsets["train"].cache_files), 2) self.assertEqual(len(reloaded_dsets["test"]), 30) self.assertListEqual(reloaded_dsets["test"].column_names, ["filename"]) self.assertEqual(len(reloaded_dsets["test"].cache_files), 2) del reloaded_dsets def test_load_from_disk(self): with tempfile.TemporaryDirectory() as tmp_dir: dsets = self._create_dummy_dataset_dict() dsets.save_to_disk(tmp_dir) del dsets dsets = load_from_disk(tmp_dir) self.assertListEqual(sorted(dsets), ["test", "train"]) self.assertEqual(len(dsets["train"]), 30) self.assertListEqual(dsets["train"].column_names, ["filename"]) self.assertEqual(len(dsets["test"]), 30) self.assertListEqual(dsets["test"].column_names, ["filename"]) del dsets def test_align_labels_with_mapping(self): train_features = Features( { "input_text": Value("string"), "input_labels": ClassLabel(num_classes=3, names=["entailment", "neutral", "contradiction"]), } ) test_features = Features( { "input_text": Value("string"), "input_labels": ClassLabel(num_classes=3, names=["entailment", "contradiction", "neutral"]), } ) train_data = {"input_text": ["a", "a", "b", "b", "c", "c"], "input_labels": [0, 0, 1, 1, 2, 2]} test_data = {"input_text": ["a", "a", "c", "c", "b", "b"], "input_labels": [0, 0, 1, 1, 2, 2]} label2id = {"CONTRADICTION": 0, "ENTAILMENT": 2, "NEUTRAL": 1} id2label = {v: k for k, v in label2id.items()} train_expected_labels = [2, 2, 1, 1, 0, 0] test_expected_labels = [2, 2, 0, 0, 1, 1] train_expected_label_names = [id2label[idx] for idx in train_expected_labels] test_expected_label_names = [id2label[idx] for idx in test_expected_labels] dsets = DatasetDict( { "train": Dataset.from_dict(train_data, features=train_features), "test": Dataset.from_dict(test_data, features=test_features), } ) dsets = dsets.align_labels_with_mapping(label2id, "input_labels") self.assertListEqual(train_expected_labels, dsets["train"]["input_labels"]) self.assertListEqual(test_expected_labels, dsets["test"]["input_labels"]) train_aligned_label_names = [ dsets["train"].features["input_labels"].int2str(idx) for idx in dsets["train"]["input_labels"] ] test_aligned_label_names = [ dsets["test"].features["input_labels"].int2str(idx) for idx in dsets["test"]["input_labels"] ] self.assertListEqual(train_expected_label_names, train_aligned_label_names) self.assertListEqual(test_expected_label_names, test_aligned_label_names) def test_dummy_datasetdict_serialize_fs(mockfs): dataset_dict = DatasetDict( { "train": Dataset.from_dict({"a": range(30)}), "test": Dataset.from_dict({"a": range(10)}), } ) dataset_path = "mock://my_dataset" dataset_dict.save_to_disk(dataset_path, storage_options=mockfs.storage_options) assert mockfs.isdir(dataset_path) assert mockfs.glob(dataset_path + "/*") reloaded = dataset_dict.load_from_disk(dataset_path, storage_options=mockfs.storage_options) assert list(reloaded) == list(dataset_dict) for k in dataset_dict: assert reloaded[k].features == dataset_dict[k].features assert reloaded[k].to_dict() == dataset_dict[k].to_dict() def _check_csv_datasetdict(dataset_dict, expected_features, splits=("train",)): assert isinstance(dataset_dict, DatasetDict) for split in splits: dataset = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_datasetdict_from_csv_keep_in_memory(keep_in_memory, csv_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "int64", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = DatasetDict.from_csv({"train": csv_path}, cache_dir=cache_dir, keep_in_memory=keep_in_memory) _check_csv_datasetdict(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ], ) def test_datasetdict_from_csv_features(features, csv_path, tmp_path): cache_dir = tmp_path / "cache" # CSV file loses col_1 string dtype information: default now is "int64" instead of "string" default_expected_features = {"col_1": "int64", "col_2": "int64", "col_3": "float64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = DatasetDict.from_csv({"train": csv_path}, features=features, cache_dir=cache_dir) _check_csv_datasetdict(dataset, expected_features) @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_datasetdict_from_csv_split(split, csv_path, tmp_path): if split: path = {split: csv_path} else: split = "train" path = {"train": csv_path, "test": csv_path} cache_dir = tmp_path / "cache" expected_features = {"col_1": "int64", "col_2": "int64", "col_3": "float64"} dataset = DatasetDict.from_csv(path, cache_dir=cache_dir) _check_csv_datasetdict(dataset, expected_features, splits=list(path.keys())) assert all(dataset[split].split == split for split in path.keys()) def _check_json_datasetdict(dataset_dict, expected_features, splits=("train",)): assert isinstance(dataset_dict, DatasetDict) for split in splits: dataset = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_datasetdict_from_json_keep_in_memory(keep_in_memory, jsonl_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = DatasetDict.from_json({"train": jsonl_path}, cache_dir=cache_dir, keep_in_memory=keep_in_memory) _check_json_datasetdict(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ], ) def test_datasetdict_from_json_features(features, jsonl_path, tmp_path): cache_dir = tmp_path / "cache" default_expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = DatasetDict.from_json({"train": jsonl_path}, features=features, cache_dir=cache_dir) _check_json_datasetdict(dataset, expected_features) @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_datasetdict_from_json_splits(split, jsonl_path, tmp_path): if split: path = {split: jsonl_path} else: split = "train" path = {"train": jsonl_path, "test": jsonl_path} cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} dataset = DatasetDict.from_json(path, cache_dir=cache_dir) _check_json_datasetdict(dataset, expected_features, splits=list(path.keys())) assert all(dataset[split].split == split for split in path.keys()) def _check_parquet_datasetdict(dataset_dict, expected_features, splits=("train",)): assert isinstance(dataset_dict, DatasetDict) for split in splits: dataset = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_datasetdict_from_parquet_keep_in_memory(keep_in_memory, parquet_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = DatasetDict.from_parquet({"train": parquet_path}, cache_dir=cache_dir, keep_in_memory=keep_in_memory) _check_parquet_datasetdict(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ], ) def test_datasetdict_from_parquet_features(features, parquet_path, tmp_path): cache_dir = tmp_path / "cache" default_expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = DatasetDict.from_parquet({"train": parquet_path}, features=features, cache_dir=cache_dir) _check_parquet_datasetdict(dataset, expected_features) @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_datasetdict_from_parquet_split(split, parquet_path, tmp_path): if split: path = {split: parquet_path} else: split = "train" path = {"train": parquet_path, "test": parquet_path} cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} dataset = DatasetDict.from_parquet(path, cache_dir=cache_dir) _check_parquet_datasetdict(dataset, expected_features, splits=list(path.keys())) assert all(dataset[split].split == split for split in path.keys()) def _check_text_datasetdict(dataset_dict, expected_features, splits=("train",)): assert isinstance(dataset_dict, DatasetDict) for split in splits: dataset = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_datasetdict_from_text_keep_in_memory(keep_in_memory, text_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"text": "string"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = DatasetDict.from_text({"train": text_path}, cache_dir=cache_dir, keep_in_memory=keep_in_memory) _check_text_datasetdict(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"text": "string"}, {"text": "int32"}, {"text": "float32"}, ], ) def test_datasetdict_from_text_features(features, text_path, tmp_path): cache_dir = tmp_path / "cache" default_expected_features = {"text": "string"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = DatasetDict.from_text({"train": text_path}, features=features, cache_dir=cache_dir) _check_text_datasetdict(dataset, expected_features) @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_datasetdict_from_text_split(split, text_path, tmp_path): if split: path = {split: text_path} else: split = "train" path = {"train": text_path, "test": text_path} cache_dir = tmp_path / "cache" expected_features = {"text": "string"} dataset = DatasetDict.from_text(path, cache_dir=cache_dir) _check_text_datasetdict(dataset, expected_features, splits=list(path.keys())) assert all(dataset[split].split == split for split in path.keys())
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_dataset_list.py
from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class DatasetListTest(TestCase): def _create_example_records(self): return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def _create_example_dict(self): data = {"col_1": [3, 2, 1, 0], "col_2": ["a", "b", "c", "d"]} return Dataset.from_dict(data) def test_create(self): example_records = self._create_example_records() dset = Dataset.from_list(example_records) self.assertListEqual(dset.column_names, ["col_1", "col_2"]) for i, r in enumerate(dset): self.assertDictEqual(r, example_records[i]) def test_list_dict_equivalent(self): example_records = self._create_example_records() dset = Dataset.from_list(example_records) dset_from_dict = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]}) self.assertEqual(dset.info, dset_from_dict.info) def test_uneven_records(self): # checks what happens with missing columns uneven_records = [{"col_1": 1}, {"col_2": "x"}] dset = Dataset.from_list(uneven_records) self.assertDictEqual(dset[0], {"col_1": 1}) self.assertDictEqual(dset[1], {"col_1": None}) # NB: first record is used for columns def test_variable_list_records(self): # checks if the type can be inferred from the second record list_records = [{"col_1": []}, {"col_1": [1, 2]}] dset = Dataset.from_list(list_records) self.assertEqual(dset.info.features["col_1"], Sequence(Value("int64"))) def test_create_empty(self): dset = Dataset.from_list([]) self.assertEqual(len(dset), 0) self.assertListEqual(dset.column_names, [])
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_distributed.py
import os import sys from pathlib import Path import pytest from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node from .utils import execute_subprocess_async, get_torch_dist_unique_port, require_torch def test_split_dataset_by_node_map_style(): full_ds = Dataset.from_dict({"i": range(17)}) full_size = len(full_ds) world_size = 3 datasets_per_rank = [ split_dataset_by_node(full_ds, rank=rank, world_size=world_size) for rank in range(world_size) ] assert sum(len(ds) for ds in datasets_per_rank) == full_size assert len({tuple(x.values()) for ds in datasets_per_rank for x in ds}) == full_size def test_split_dataset_by_node_iterable(): def gen(): return ({"i": i} for i in range(17)) world_size = 3 full_ds = IterableDataset.from_generator(gen) full_size = len(list(full_ds)) datasets_per_rank = [ split_dataset_by_node(full_ds, rank=rank, world_size=world_size) for rank in range(world_size) ] assert sum(len(list(ds)) for ds in datasets_per_rank) == full_size assert len({tuple(x.values()) for ds in datasets_per_rank for x in ds}) == full_size @pytest.mark.parametrize("shards_per_node", [1, 2, 3]) def test_split_dataset_by_node_iterable_sharded(shards_per_node): def gen(shards): for shard in shards: yield from ({"i": i, "shard": shard} for i in range(17)) world_size = 3 num_shards = shards_per_node * world_size gen_kwargs = {"shards": [f"shard_{shard_idx}.txt" for shard_idx in range(num_shards)]} full_ds = IterableDataset.from_generator(gen, gen_kwargs=gen_kwargs) full_size = len(list(full_ds)) assert full_ds.n_shards == world_size * shards_per_node datasets_per_rank = [ split_dataset_by_node(full_ds, rank=rank, world_size=world_size) for rank in range(world_size) ] assert [ds.n_shards for ds in datasets_per_rank] == [shards_per_node] * world_size assert sum(len(list(ds)) for ds in datasets_per_rank) == full_size assert len({tuple(x.values()) for ds in datasets_per_rank for x in ds}) == full_size def test_distributed_shuffle_iterable(): def gen(): return ({"i": i} for i in range(17)) world_size = 2 full_ds = IterableDataset.from_generator(gen) full_size = len(list(full_ds)) ds_rank0 = split_dataset_by_node(full_ds, rank=0, world_size=world_size).shuffle(seed=42) assert len(list(ds_rank0)) == 1 + full_size // world_size with pytest.raises(RuntimeError): split_dataset_by_node(full_ds, rank=0, world_size=world_size).shuffle() ds_rank0 = split_dataset_by_node(full_ds.shuffle(seed=42), rank=0, world_size=world_size) assert len(list(ds_rank0)) == 1 + full_size // world_size with pytest.raises(RuntimeError): split_dataset_by_node(full_ds.shuffle(), rank=0, world_size=world_size) @pytest.mark.parametrize("streaming", [False, True]) @require_torch @pytest.mark.skipif(os.name == "nt", reason="execute_subprocess_async doesn't support windows") @pytest.mark.integration def test_torch_distributed_run(streaming): nproc_per_node = 2 master_port = get_torch_dist_unique_port() test_script = Path(__file__).resolve().parent / "distributed_scripts" / "run_torch_distributed.py" distributed_args = f""" -m torch.distributed.run --nproc_per_node={nproc_per_node} --master_port={master_port} {test_script} """.split() args = f""" --streaming={streaming} """.split() cmd = [sys.executable] + distributed_args + args execute_subprocess_async(cmd, env=os.environ.copy()) @pytest.mark.parametrize( "nproc_per_node, num_workers", [ (2, 2), # each node has 2 shards and each worker has 1 shards (3, 2), # each node uses all the shards but skips examples, and each worker has 2 shards ], ) @require_torch @pytest.mark.skipif(os.name == "nt", reason="execute_subprocess_async doesn't support windows") @pytest.mark.integration def test_torch_distributed_run_streaming_with_num_workers(nproc_per_node, num_workers): streaming = True master_port = get_torch_dist_unique_port() test_script = Path(__file__).resolve().parent / "distributed_scripts" / "run_torch_distributed.py" distributed_args = f""" -m torch.distributed.run --nproc_per_node={nproc_per_node} --master_port={master_port} {test_script} """.split() args = f""" --streaming={streaming} --num_workers={num_workers} """.split() cmd = [sys.executable] + distributed_args + args execute_subprocess_async(cmd, env=os.environ.copy())
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_download_manager.py
import json import os from pathlib import Path import pytest from datasets.download.download_config import DownloadConfig from datasets.download.download_manager import DownloadManager from datasets.utils.file_utils import hash_url_to_filename URL = "http://www.mocksite.com/file1.txt" CONTENT = '"text": ["foo", "foo"]' HASH = "6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8" class MockResponse: status_code = 200 headers = {"Content-Length": "100"} cookies = {} def iter_content(self, **kwargs): return [bytes(CONTENT, "utf-8")] def mock_request(*args, **kwargs): return MockResponse() @pytest.mark.parametrize("urls_type", [str, list, dict]) def test_download_manager_download(urls_type, tmp_path, monkeypatch): import requests monkeypatch.setattr(requests, "request", mock_request) url = URL if issubclass(urls_type, str): urls = url elif issubclass(urls_type, list): urls = [url] elif issubclass(urls_type, dict): urls = {"train": url} dataset_name = "dummy" cache_subdir = "downloads" cache_dir_root = tmp_path download_config = DownloadConfig( cache_dir=os.path.join(cache_dir_root, cache_subdir), use_etag=False, ) dl_manager = DownloadManager(dataset_name=dataset_name, download_config=download_config) downloaded_paths = dl_manager.download(urls) input_urls = urls for downloaded_paths in [downloaded_paths]: if isinstance(urls, str): downloaded_paths = [downloaded_paths] input_urls = [urls] elif isinstance(urls, dict): assert "train" in downloaded_paths.keys() downloaded_paths = downloaded_paths.values() input_urls = urls.values() assert downloaded_paths for downloaded_path, input_url in zip(downloaded_paths, input_urls): assert downloaded_path == dl_manager.downloaded_paths[input_url] downloaded_path = Path(downloaded_path) parts = downloaded_path.parts assert parts[-1] == HASH assert parts[-2] == cache_subdir assert downloaded_path.exists() content = downloaded_path.read_text() assert content == CONTENT metadata_downloaded_path = downloaded_path.with_suffix(".json") assert metadata_downloaded_path.exists() metadata_content = json.loads(metadata_downloaded_path.read_text()) assert metadata_content == {"url": URL, "etag": None} @pytest.mark.parametrize("paths_type", [str, list, dict]) def test_download_manager_extract(paths_type, xz_file, text_file): filename = str(xz_file) if issubclass(paths_type, str): paths = filename elif issubclass(paths_type, list): paths = [filename] elif issubclass(paths_type, dict): paths = {"train": filename} dataset_name = "dummy" cache_dir = xz_file.parent extracted_subdir = "extracted" download_config = DownloadConfig( cache_dir=cache_dir, use_etag=False, ) dl_manager = DownloadManager(dataset_name=dataset_name, download_config=download_config) extracted_paths = dl_manager.extract(paths) input_paths = paths for extracted_paths in [extracted_paths]: if isinstance(paths, str): extracted_paths = [extracted_paths] input_paths = [paths] elif isinstance(paths, dict): assert "train" in extracted_paths.keys() extracted_paths = extracted_paths.values() input_paths = paths.values() assert extracted_paths for extracted_path, input_path in zip(extracted_paths, input_paths): assert extracted_path == dl_manager.extracted_paths[input_path] extracted_path = Path(extracted_path) parts = extracted_path.parts assert parts[-1] == hash_url_to_filename(input_path, etag=None) assert parts[-2] == extracted_subdir assert extracted_path.exists() extracted_file_content = extracted_path.read_text() expected_file_content = text_file.read_text() assert extracted_file_content == expected_file_content def _test_jsonl(path, file): assert path.endswith(".jsonl") for num_items, line in enumerate(file, start=1): item = json.loads(line.decode("utf-8")) assert item.keys() == {"col_1", "col_2", "col_3"} assert num_items == 4 @pytest.mark.parametrize("archive_jsonl", ["tar_jsonl_path", "zip_jsonl_path"]) def test_iter_archive_path(archive_jsonl, request): archive_jsonl_path = request.getfixturevalue(archive_jsonl) dl_manager = DownloadManager() for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(archive_jsonl_path), start=1): _test_jsonl(path, file) assert num_jsonl == 2 @pytest.mark.parametrize("archive_nested_jsonl", ["tar_nested_jsonl_path", "zip_nested_jsonl_path"]) def test_iter_archive_file(archive_nested_jsonl, request): archive_nested_jsonl_path = request.getfixturevalue(archive_nested_jsonl) dl_manager = DownloadManager() for num_tar, (path, file) in enumerate(dl_manager.iter_archive(archive_nested_jsonl_path), start=1): for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(file), start=1): _test_jsonl(subpath, subfile) assert num_tar == 1 assert num_jsonl == 2 def test_iter_files(data_dir_with_hidden_files): dl_manager = DownloadManager() for num_file, file in enumerate(dl_manager.iter_files(data_dir_with_hidden_files), start=1): assert os.path.basename(file) == ("test.txt" if num_file == 1 else "train.txt") assert num_file == 2
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_experimental.py
import unittest import warnings from datasets.utils import experimental @experimental def dummy_function(): return "success" class TestExperimentalFlag(unittest.TestCase): def test_experimental_warning(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") self.assertEqual(dummy_function(), "success") self.assertEqual(len(w), 1)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_extract.py
import os import zipfile import pytest from datasets.utils.extract import ( Bzip2Extractor, Extractor, GzipExtractor, Lz4Extractor, SevenZipExtractor, TarExtractor, XzExtractor, ZipExtractor, ZstdExtractor, ) from .utils import require_lz4, require_py7zr, require_zstandard @pytest.mark.parametrize( "compression_format, is_archive", [ ("7z", True), ("bz2", False), ("gzip", False), ("lz4", False), ("tar", True), ("xz", False), ("zip", True), ("zstd", False), ], ) def test_base_extractors( compression_format, is_archive, bz2_file, gz_file, lz4_file, seven_zip_file, tar_file, xz_file, zip_file, zstd_file, tmp_path, text_file, ): input_paths_and_base_extractors = { "7z": (seven_zip_file, SevenZipExtractor), "bz2": (bz2_file, Bzip2Extractor), "gzip": (gz_file, GzipExtractor), "lz4": (lz4_file, Lz4Extractor), "tar": (tar_file, TarExtractor), "xz": (xz_file, XzExtractor), "zip": (zip_file, ZipExtractor), "zstd": (zstd_file, ZstdExtractor), } input_path, base_extractor = input_paths_and_base_extractors[compression_format] if input_path is None: reason = f"for '{compression_format}' compression_format, " if compression_format == "7z": reason += require_py7zr.kwargs["reason"] elif compression_format == "lz4": reason += require_lz4.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(reason) assert base_extractor.is_extractable(input_path) output_path = tmp_path / ("extracted" if is_archive else "extracted.txt") base_extractor.extract(input_path, output_path) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name extracted_file_content = file_path.read_text(encoding="utf-8") else: extracted_file_content = output_path.read_text(encoding="utf-8") expected_file_content = text_file.read_text(encoding="utf-8") assert extracted_file_content == expected_file_content @pytest.mark.parametrize( "compression_format, is_archive", [ ("7z", True), ("bz2", False), ("gzip", False), ("lz4", False), ("tar", True), ("xz", False), ("zip", True), ("zstd", False), ], ) def test_extractor( compression_format, is_archive, bz2_file, gz_file, lz4_file, seven_zip_file, tar_file, xz_file, zip_file, zstd_file, tmp_path, text_file, ): input_paths = { "7z": seven_zip_file, "bz2": bz2_file, "gzip": gz_file, "lz4": lz4_file, "tar": tar_file, "xz": xz_file, "zip": zip_file, "zstd": zstd_file, } input_path = input_paths[compression_format] if input_path is None: reason = f"for '{compression_format}' compression_format, " if compression_format == "7z": reason += require_py7zr.kwargs["reason"] elif compression_format == "lz4": reason += require_lz4.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(reason) extractor_format = Extractor.infer_extractor_format(input_path) assert extractor_format is not None output_path = tmp_path / ("extracted" if is_archive else "extracted.txt") Extractor.extract(input_path, output_path, extractor_format) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name extracted_file_content = file_path.read_text(encoding="utf-8") else: extracted_file_content = output_path.read_text(encoding="utf-8") expected_file_content = text_file.read_text(encoding="utf-8") assert extracted_file_content == expected_file_content @pytest.fixture def tar_file_with_dot_dot(tmp_path, text_file): import tarfile directory = tmp_path / "data_dot_dot" directory.mkdir() path = directory / "tar_file_with_dot_dot.tar" with tarfile.TarFile(path, "w") as f: f.add(text_file, arcname=os.path.join("..", text_file.name)) return path @pytest.fixture def tar_file_with_sym_link(tmp_path): import tarfile directory = tmp_path / "data_sym_link" directory.mkdir() path = directory / "tar_file_with_sym_link.tar" os.symlink("..", directory / "subdir", target_is_directory=True) with tarfile.TarFile(path, "w") as f: f.add(str(directory / "subdir"), arcname="subdir") # str required by os.readlink on Windows and Python < 3.8 return path @pytest.mark.parametrize( "insecure_tar_file, error_log", [("tar_file_with_dot_dot", "illegal path"), ("tar_file_with_sym_link", "Symlink")], ) def test_tar_extract_insecure_files( insecure_tar_file, error_log, tar_file_with_dot_dot, tar_file_with_sym_link, tmp_path, caplog ): insecure_tar_files = { "tar_file_with_dot_dot": tar_file_with_dot_dot, "tar_file_with_sym_link": tar_file_with_sym_link, } input_path = insecure_tar_files[insecure_tar_file] output_path = tmp_path / "extracted" TarExtractor.extract(input_path, output_path) assert caplog.text for record in caplog.records: assert record.levelname == "ERROR" assert error_log in record.msg def test_is_zipfile_false_positive(tmpdir): # We should have less false positives than zipfile.is_zipfile # We do that by checking only the magic number not_a_zip_file = tmpdir / "not_a_zip_file" # From: https://github.com/python/cpython/pull/5053 data = ( b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00" b"\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6'\x00\x00\x00\x15I" b"DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07" b"\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82" ) with not_a_zip_file.open("wb") as f: f.write(data) assert zipfile.is_zipfile(str(not_a_zip_file)) # is a false positive for `zipfile` assert not ZipExtractor.is_extractable(not_a_zip_file) # but we're right
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_file_utils.py
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) FILE_CONTENT = """\ Text data. Second line of data.""" FILE_PATH = "file" @pytest.fixture(scope="session") def zstd_path(tmp_path_factory): path = tmp_path_factory.mktemp("data") / (FILE_PATH + ".zstd") data = bytes(FILE_CONTENT, "utf-8") with zstd.open(path, "wb") as f: f.write(data) return path @pytest.fixture def tmpfs_file(tmpfs): with open(os.path.join(tmpfs.local_root_dir, FILE_PATH), "w") as f: f.write(FILE_CONTENT) return FILE_PATH @pytest.mark.parametrize("compression_format", ["gzip", "xz", "zstd"]) def test_cached_path_extract(compression_format, gz_file, xz_file, zstd_path, tmp_path, text_file): input_paths = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_path} input_path = input_paths[compression_format] cache_dir = tmp_path / "cache" download_config = DownloadConfig(cache_dir=cache_dir, extract_compressed_file=True) extracted_path = cached_path(input_path, download_config=download_config) with open(extracted_path) as f: extracted_file_content = f.read() with open(text_file) as f: expected_file_content = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("default_extracted", [True, False]) @pytest.mark.parametrize("default_cache_dir", [True, False]) def test_extracted_datasets_path(default_extracted, default_cache_dir, xz_file, tmp_path, monkeypatch): custom_cache_dir = "custom_cache" custom_extracted_dir = "custom_extracted_dir" custom_extracted_path = tmp_path / "custom_extracted_path" if default_extracted: expected = ("downloads" if default_cache_dir else custom_cache_dir, "extracted") else: monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_DIR", custom_extracted_dir) monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH", str(custom_extracted_path)) expected = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) filename = xz_file download_config = ( DownloadConfig(extract_compressed_file=True) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir, extract_compressed_file=True) ) extracted_file_path = cached_path(filename, download_config=download_config) assert Path(extracted_file_path).parent.parts[-2:] == expected def test_cached_path_local(text_file): # absolute path text_file = str(Path(text_file).resolve()) assert cached_path(text_file) == text_file # relative path text_file = str(Path(__file__).resolve().relative_to(Path(os.getcwd()))) assert cached_path(text_file) == text_file def test_cached_path_missing_local(tmp_path): # absolute path missing_file = str(tmp_path.resolve() / "__missing_file__.txt") with pytest.raises(FileNotFoundError): cached_path(missing_file) # relative path missing_file = "./__missing_file__.txt" with pytest.raises(FileNotFoundError): cached_path(missing_file) def test_get_from_cache_fsspec(tmpfs_file): output_path = get_from_cache(f"tmp://{tmpfs_file}") with open(output_path) as f: output_file_content = f.read() assert output_file_content == FILE_CONTENT @patch("datasets.config.HF_DATASETS_OFFLINE", True) def test_cached_path_offline(): with pytest.raises(OfflineModeIsEnabled): cached_path("https://huggingface.co") @patch("datasets.config.HF_DATASETS_OFFLINE", True) def test_http_offline(tmp_path_factory): filename = tmp_path_factory.mktemp("data") / "file.html" with pytest.raises(OfflineModeIsEnabled): http_get("https://huggingface.co", temp_file=filename) with pytest.raises(OfflineModeIsEnabled): http_head("https://huggingface.co") @patch("datasets.config.HF_DATASETS_OFFLINE", True) def test_ftp_offline(tmp_path_factory): filename = tmp_path_factory.mktemp("data") / "file.html" with pytest.raises(OfflineModeIsEnabled): ftp_get("ftp://huggingface.co", temp_file=filename) with pytest.raises(OfflineModeIsEnabled): ftp_head("ftp://huggingface.co") @patch("datasets.config.HF_DATASETS_OFFLINE", True) def test_fsspec_offline(tmp_path_factory): filename = tmp_path_factory.mktemp("data") / "file.html" with pytest.raises(OfflineModeIsEnabled): fsspec_get("s3://huggingface.co", temp_file=filename) with pytest.raises(OfflineModeIsEnabled): fsspec_head("s3://huggingface.co")
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_filelock.py
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def test_filelock(tmpdir): lock1 = FileLock(str(tmpdir / "foo.lock")) lock2 = FileLock(str(tmpdir / "foo.lock")) timeout = 0.01 with lock1.acquire(): with pytest.raises(Timeout): _start = time.time() lock2.acquire(timeout) assert time.time() - _start > timeout def test_long_filename(tmpdir): filename = "a" * 1000 + ".lock" lock1 = FileLock(str(tmpdir / filename)) assert lock1._lock_file.endswith(".lock") assert not lock1._lock_file.endswith(filename) assert len(os.path.basename(lock1._lock_file)) <= 255 lock2 = FileLock(tmpdir / filename) with lock1.acquire(): with pytest.raises(Timeout): lock2.acquire(0)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_filesystem.py
import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, extract_path_from_uri, is_remote_filesystem from .utils import require_lz4, require_zstandard def test_mockfs(mockfs): assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def test_non_mockfs(): assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def test_extract_path_from_uri(): mock_bucket = "mock-s3-bucket" dataset_path = f"s3://{mock_bucket}" dataset_path = extract_path_from_uri(dataset_path) assert dataset_path.startswith("s3://") is False dataset_path = "./local/path" new_dataset_path = extract_path_from_uri(dataset_path) assert dataset_path == new_dataset_path def test_is_remote_filesystem(mockfs): is_remote = is_remote_filesystem(mockfs) assert is_remote is True fs = fsspec.filesystem("file") is_remote = is_remote_filesystem(fs) assert is_remote is False @pytest.mark.parametrize("compression_fs_class", COMPRESSION_FILESYSTEMS) def test_compression_filesystems(compression_fs_class, gz_file, bz2_file, lz4_file, zstd_file, xz_file, text_file): input_paths = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_file, "bz2": bz2_file, "lz4": lz4_file} input_path = input_paths[compression_fs_class.protocol] if input_path is None: reason = f"for '{compression_fs_class.protocol}' compression protocol, " if compression_fs_class.protocol == "lz4": reason += require_lz4.kwargs["reason"] elif compression_fs_class.protocol == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(reason) fs = fsspec.filesystem(compression_fs_class.protocol, fo=input_path) assert isinstance(fs, compression_fs_class) expected_filename = os.path.basename(input_path) expected_filename = expected_filename[: expected_filename.rindex(".")] assert fs.glob("*") == [expected_filename] with fs.open(expected_filename, "r", encoding="utf-8") as f, open(text_file, encoding="utf-8") as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize("protocol", ["zip", "gzip"]) def test_fs_isfile(protocol, zip_jsonl_path, jsonl_gz_path): compressed_file_paths = {"zip": zip_jsonl_path, "gzip": jsonl_gz_path} compressed_file_path = compressed_file_paths[protocol] member_file_path = "dataset.jsonl" path = f"{protocol}://{member_file_path}::{compressed_file_path}" fs, *_ = fsspec.get_fs_token_paths(path) assert fs.isfile(member_file_path) assert not fs.isfile("non_existing_" + member_file_path) def test_fs_overwrites(): protocol = "bz2" # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(protocol, None, clobber=True) with pytest.warns(UserWarning) as warning_info: importlib.reload(datasets.filesystems) assert len(warning_info) == 1 assert ( str(warning_info[0].message) == f"A filesystem protocol was already set for {protocol} and will be overwritten." )
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_fingerprint.py
import json import os import pickle import subprocess from hashlib import md5 from pathlib import Path from tempfile import gettempdir from textwrap import dedent from types import FunctionType from unittest import TestCase from unittest.mock import patch import pytest from multiprocess import Pool import datasets from datasets.fingerprint import Hasher, fingerprint_transform from datasets.table import InMemoryTable from .utils import ( require_regex, require_spacy, require_spacy_model, require_tiktoken, require_torch, require_transformers, ) class Foo: def __init__(self, foo): self.foo = foo def __call__(self): return self.foo class DatasetChild(datasets.Dataset): @fingerprint_transform(inplace=False) def func1(self, new_fingerprint, *args, **kwargs): return DatasetChild(self.data, fingerprint=new_fingerprint) @fingerprint_transform(inplace=False) def func2(self, new_fingerprint, *args, **kwargs): return DatasetChild(self.data, fingerprint=new_fingerprint) class UnpicklableCallable: def __init__(self, callable): self.callable = callable def __call__(self, *args, **kwargs): if self.callable is not None: return self.callable(*args, **kwargs) def __getstate__(self): raise pickle.PicklingError() class TokenizersDumpTest(TestCase): @require_transformers @pytest.mark.integration def test_hash_tokenizer(self): from transformers import AutoTokenizer def encode(x): return tokenizer(x) # TODO: add hash consistency tests across sessions tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") hash1 = md5(datasets.utils.py_utils.dumps(tokenizer)).hexdigest() hash1_lambda = md5(datasets.utils.py_utils.dumps(lambda x: tokenizer(x))).hexdigest() hash1_encode = md5(datasets.utils.py_utils.dumps(encode)).hexdigest() tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") hash2 = md5(datasets.utils.py_utils.dumps(tokenizer)).hexdigest() hash2_lambda = md5(datasets.utils.py_utils.dumps(lambda x: tokenizer(x))).hexdigest() hash2_encode = md5(datasets.utils.py_utils.dumps(encode)).hexdigest() tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") hash3 = md5(datasets.utils.py_utils.dumps(tokenizer)).hexdigest() hash3_lambda = md5(datasets.utils.py_utils.dumps(lambda x: tokenizer(x))).hexdigest() hash3_encode = md5(datasets.utils.py_utils.dumps(encode)).hexdigest() self.assertEqual(hash1, hash3) self.assertNotEqual(hash1, hash2) self.assertEqual(hash1_lambda, hash3_lambda) self.assertNotEqual(hash1_lambda, hash2_lambda) self.assertEqual(hash1_encode, hash3_encode) self.assertNotEqual(hash1_encode, hash2_encode) @require_transformers @pytest.mark.integration def test_hash_tokenizer_with_cache(self): from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("gpt2") hash1 = md5(datasets.utils.py_utils.dumps(tokenizer)).hexdigest() tokenizer("Hello world !") # call once to change the tokenizer's cache hash2 = md5(datasets.utils.py_utils.dumps(tokenizer)).hexdigest() self.assertEqual(hash1, hash2) @require_regex def test_hash_regex(self): import regex pat = regex.Regex("foo") hash1 = md5(datasets.utils.py_utils.dumps(pat)).hexdigest() pat = regex.Regex("bar") hash2 = md5(datasets.utils.py_utils.dumps(pat)).hexdigest() pat = regex.Regex("foo") hash3 = md5(datasets.utils.py_utils.dumps(pat)).hexdigest() self.assertEqual(hash1, hash3) self.assertNotEqual(hash1, hash2) class RecurseDumpTest(TestCase): def test_recurse_dump_for_function(self): def func(): return foo foo = [0] hash1 = md5(datasets.utils.py_utils.dumps(func)).hexdigest() foo = [1] hash2 = md5(datasets.utils.py_utils.dumps(func)).hexdigest() foo = [0] hash3 = md5(datasets.utils.py_utils.dumps(func)).hexdigest() self.assertEqual(hash1, hash3) self.assertNotEqual(hash1, hash2) def test_dump_ignores_line_definition_of_function(self): def func(): pass hash1 = md5(datasets.utils.py_utils.dumps(func)).hexdigest() def func(): pass hash2 = md5(datasets.utils.py_utils.dumps(func)).hexdigest() self.assertEqual(hash1, hash2) def test_recurse_dump_for_class(self): hash1 = md5(datasets.utils.py_utils.dumps(Foo([0]))).hexdigest() hash2 = md5(datasets.utils.py_utils.dumps(Foo([1]))).hexdigest() hash3 = md5(datasets.utils.py_utils.dumps(Foo([0]))).hexdigest() self.assertEqual(hash1, hash3) self.assertNotEqual(hash1, hash2) def test_recurse_dump_for_method(self): hash1 = md5(datasets.utils.py_utils.dumps(Foo([0]).__call__)).hexdigest() hash2 = md5(datasets.utils.py_utils.dumps(Foo([1]).__call__)).hexdigest() hash3 = md5(datasets.utils.py_utils.dumps(Foo([0]).__call__)).hexdigest() self.assertEqual(hash1, hash3) self.assertNotEqual(hash1, hash2) def test_dump_ipython_function(self): def create_ipython_func(co_filename, returned_obj): def func(): return returned_obj code = func.__code__ # Use _create_code from dill in order to make it work for different python versions code = code.replace(co_filename=co_filename) return FunctionType(code, func.__globals__, func.__name__, func.__defaults__, func.__closure__) co_filename, returned_obj = "<ipython-input-2-e0383a102aae>", [0] hash1 = md5(datasets.utils.py_utils.dumps(create_ipython_func(co_filename, returned_obj))).hexdigest() co_filename, returned_obj = "<ipython-input-2-e0383a102aae>", [1] hash2 = md5(datasets.utils.py_utils.dumps(create_ipython_func(co_filename, returned_obj))).hexdigest() co_filename, returned_obj = "<ipython-input-5-713f6613acf3>", [0] hash3 = md5(datasets.utils.py_utils.dumps(create_ipython_func(co_filename, returned_obj))).hexdigest() self.assertEqual(hash1, hash3) self.assertNotEqual(hash1, hash2) co_filename, returned_obj = os.path.join(gettempdir(), "ipykernel_12345", "321456789.py"), [0] hash4 = md5(datasets.utils.py_utils.dumps(create_ipython_func(co_filename, returned_obj))).hexdigest() co_filename, returned_obj = os.path.join(gettempdir(), "ipykernel_12345", "321456789.py"), [1] hash5 = md5(datasets.utils.py_utils.dumps(create_ipython_func(co_filename, returned_obj))).hexdigest() co_filename, returned_obj = os.path.join(gettempdir(), "ipykernel_12345", "654123987.py"), [0] hash6 = md5(datasets.utils.py_utils.dumps(create_ipython_func(co_filename, returned_obj))).hexdigest() self.assertEqual(hash4, hash6) self.assertNotEqual(hash4, hash5) def test_recurse_dump_for_function_with_shuffled_globals(self): foo, bar = [0], [1] def func(): return foo, bar func.__module__ = "__main__" def globalvars_mock1_side_effect(func, *args, **kwargs): return {"foo": foo, "bar": bar} def globalvars_mock2_side_effect(func, *args, **kwargs): return {"bar": bar, "foo": foo} with patch("dill.detect.globalvars", side_effect=globalvars_mock1_side_effect) as globalvars_mock1: hash1 = md5(datasets.utils.py_utils.dumps(func)).hexdigest() self.assertGreater(globalvars_mock1.call_count, 0) with patch("dill.detect.globalvars", side_effect=globalvars_mock2_side_effect) as globalvars_mock2: hash2 = md5(datasets.utils.py_utils.dumps(func)).hexdigest() self.assertGreater(globalvars_mock2.call_count, 0) self.assertEqual(hash1, hash2) class HashingTest(TestCase): def test_hash_simple(self): hash1 = Hasher.hash("hello") hash2 = Hasher.hash("hello") hash3 = Hasher.hash("there") self.assertEqual(hash1, hash2) self.assertNotEqual(hash1, hash3) def test_hash_class_instance(self): hash1 = Hasher.hash(Foo("hello")) hash2 = Hasher.hash(Foo("hello")) hash3 = Hasher.hash(Foo("there")) self.assertEqual(hash1, hash2) self.assertNotEqual(hash1, hash3) def test_hash_update(self): hasher = Hasher() for x in ["hello", Foo("hello")]: hasher.update(x) hash1 = hasher.hexdigest() hasher = Hasher() for x in ["hello", Foo("hello")]: hasher.update(x) hash2 = hasher.hexdigest() hasher = Hasher() for x in ["there", Foo("there")]: hasher.update(x) hash3 = hasher.hexdigest() self.assertEqual(hash1, hash2) self.assertNotEqual(hash1, hash3) def test_hash_unpicklable(self): with self.assertRaises(pickle.PicklingError): Hasher.hash(UnpicklableCallable(Foo("hello"))) def test_hash_same_strings(self): string = "abc" obj1 = [string, string] # two strings have the same ids obj2 = [string, string] obj3 = json.loads(f'["{string}", "{string}"]') # two strings have different ids self.assertIs(obj1[0], string) self.assertIs(obj1[0], obj1[1]) self.assertIs(obj2[0], string) self.assertIs(obj2[0], obj2[1]) self.assertIsNot(obj3[0], string) self.assertIsNot(obj3[0], obj3[1]) hash1 = Hasher.hash(obj1) hash2 = Hasher.hash(obj2) hash3 = Hasher.hash(obj3) self.assertEqual(hash1, hash2) self.assertEqual(hash1, hash3) @require_tiktoken def test_hash_tiktoken_encoding(self): import tiktoken enc = tiktoken.get_encoding("gpt2") hash1 = md5(datasets.utils.py_utils.dumps(enc)).hexdigest() enc = tiktoken.get_encoding("r50k_base") hash2 = md5(datasets.utils.py_utils.dumps(enc)).hexdigest() enc = tiktoken.get_encoding("gpt2") hash3 = md5(datasets.utils.py_utils.dumps(enc)).hexdigest() self.assertEqual(hash1, hash3) self.assertNotEqual(hash1, hash2) @require_torch def test_hash_torch_tensor(self): import torch t = torch.tensor([1.0]) hash1 = md5(datasets.utils.py_utils.dumps(t)).hexdigest() t = torch.tensor([2.0]) hash2 = md5(datasets.utils.py_utils.dumps(t)).hexdigest() t = torch.tensor([1.0]) hash3 = md5(datasets.utils.py_utils.dumps(t)).hexdigest() self.assertEqual(hash1, hash3) self.assertNotEqual(hash1, hash2) @require_spacy @require_spacy_model("en_core_web_sm") @require_spacy_model("fr_core_news_sm") @pytest.mark.integration def test_hash_spacy_model(self): import spacy nlp = spacy.load("en_core_web_sm") hash1 = md5(datasets.utils.py_utils.dumps(nlp)).hexdigest() nlp = spacy.load("fr_core_news_sm") hash2 = md5(datasets.utils.py_utils.dumps(nlp)).hexdigest() nlp = spacy.load("en_core_web_sm") hash3 = md5(datasets.utils.py_utils.dumps(nlp)).hexdigest() self.assertEqual(hash1, hash3) self.assertNotEqual(hash1, hash2) @pytest.mark.integration def test_move_script_doesnt_change_hash(tmp_path: Path): dir1 = tmp_path / "dir1" dir2 = tmp_path / "dir2" dir1.mkdir() dir2.mkdir() script_filename = "script.py" code = dedent( """ from datasets.fingerprint import Hasher def foo(): pass print(Hasher.hash(foo)) """ ) script_path1 = dir1 / script_filename script_path2 = dir2 / script_filename with script_path1.open("w") as f: f.write(code) with script_path2.open("w") as f: f.write(code) fingerprint1 = subprocess.check_output(["python", str(script_path1)]) fingerprint2 = subprocess.check_output(["python", str(script_path2)]) assert fingerprint1 == fingerprint2 def test_fingerprint_in_multiprocessing(): data = {"a": [0, 1, 2]} dataset = DatasetChild(InMemoryTable.from_pydict(data)) expected_fingerprint = dataset.func1()._fingerprint assert expected_fingerprint == dataset.func1()._fingerprint assert expected_fingerprint != dataset.func2()._fingerprint with Pool(2) as p: assert expected_fingerprint == p.apply_async(dataset.func1).get()._fingerprint assert expected_fingerprint != p.apply_async(dataset.func2).get()._fingerprint def test_fingerprint_when_transform_version_changes(): data = {"a": [0, 1, 2]} class DummyDatasetChild(datasets.Dataset): @fingerprint_transform(inplace=False) def func(self, new_fingerprint): return DummyDatasetChild(self.data, fingerprint=new_fingerprint) fingeprint_no_version = DummyDatasetChild(InMemoryTable.from_pydict(data)).func() class DummyDatasetChild(datasets.Dataset): @fingerprint_transform(inplace=False, version="1.0.0") def func(self, new_fingerprint): return DummyDatasetChild(self.data, fingerprint=new_fingerprint) fingeprint_1 = DummyDatasetChild(InMemoryTable.from_pydict(data)).func() class DummyDatasetChild(datasets.Dataset): @fingerprint_transform(inplace=False, version="2.0.0") def func(self, new_fingerprint): return DummyDatasetChild(self.data, fingerprint=new_fingerprint) fingeprint_2 = DummyDatasetChild(InMemoryTable.from_pydict(data)).func() assert len({fingeprint_no_version, fingeprint_1, fingeprint_2}) == 3 def test_dependency_on_dill(): # AttributeError: module 'dill._dill' has no attribute 'stack' hasher = Hasher() hasher.update(lambda x: x)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_formatting.py
import datetime from pathlib import Path from unittest import TestCase import numpy as np import pandas as pd import pyarrow as pa import pytest from datasets import Audio, Features, Image, IterableDataset from datasets.formatting import NumpyFormatter, PandasFormatter, PythonFormatter, query_table from datasets.formatting.formatting import ( LazyBatch, LazyRow, NumpyArrowExtractor, PandasArrowExtractor, PythonArrowExtractor, ) from datasets.table import InMemoryTable from .utils import require_jax, require_pil, require_sndfile, require_tf, require_torch class AnyArray: def __init__(self, data) -> None: self.data = data def __array__(self) -> np.ndarray: return np.asarray(self.data) def _gen_any_arrays(): for _ in range(10): yield {"array": AnyArray(list(range(10)))} @pytest.fixture def any_arrays_dataset(): return IterableDataset.from_generator(_gen_any_arrays) _COL_A = [0, 1, 2] _COL_B = ["foo", "bar", "foobar"] _COL_C = [[[1.0, 0.0, 0.0]] * 2, [[0.0, 1.0, 0.0]] * 2, [[0.0, 0.0, 1.0]] * 2] _COL_D = [datetime.datetime(2023, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)] * 3 _INDICES = [1, 0] IMAGE_PATH_1 = Path(__file__).parent / "features" / "data" / "test_image_rgb.jpg" IMAGE_PATH_2 = Path(__file__).parent / "features" / "data" / "test_image_rgba.png" AUDIO_PATH_1 = Path(__file__).parent / "features" / "data" / "test_audio_44100.wav" class ArrowExtractorTest(TestCase): def _create_dummy_table(self): return pa.Table.from_pydict({"a": _COL_A, "b": _COL_B, "c": _COL_C, "d": _COL_D}) def test_python_extractor(self): pa_table = self._create_dummy_table() extractor = PythonArrowExtractor() row = extractor.extract_row(pa_table) self.assertEqual(row, {"a": _COL_A[0], "b": _COL_B[0], "c": _COL_C[0], "d": _COL_D[0]}) col = extractor.extract_column(pa_table) self.assertEqual(col, _COL_A) batch = extractor.extract_batch(pa_table) self.assertEqual(batch, {"a": _COL_A, "b": _COL_B, "c": _COL_C, "d": _COL_D}) def test_numpy_extractor(self): pa_table = self._create_dummy_table().drop(["c", "d"]) extractor = NumpyArrowExtractor() row = extractor.extract_row(pa_table) np.testing.assert_equal(row, {"a": _COL_A[0], "b": _COL_B[0]}) col = extractor.extract_column(pa_table) np.testing.assert_equal(col, np.array(_COL_A)) batch = extractor.extract_batch(pa_table) np.testing.assert_equal(batch, {"a": np.array(_COL_A), "b": np.array(_COL_B)}) def test_numpy_extractor_nested(self): pa_table = self._create_dummy_table().drop(["a", "b"]) extractor = NumpyArrowExtractor() row = extractor.extract_row(pa_table) self.assertEqual(row["c"][0].dtype, np.float64) self.assertEqual(row["c"].dtype, object) col = extractor.extract_column(pa_table) self.assertEqual(col[0][0].dtype, np.float64) self.assertEqual(col[0].dtype, object) self.assertEqual(col.dtype, object) batch = extractor.extract_batch(pa_table) self.assertEqual(batch["c"][0][0].dtype, np.float64) self.assertEqual(batch["c"][0].dtype, object) self.assertEqual(batch["c"].dtype, object) def test_numpy_extractor_temporal(self): pa_table = self._create_dummy_table().drop(["a", "b", "c"]) extractor = NumpyArrowExtractor() row = extractor.extract_row(pa_table) self.assertTrue(np.issubdtype(row["d"].dtype, np.datetime64)) col = extractor.extract_column(pa_table) self.assertTrue(np.issubdtype(col[0].dtype, np.datetime64)) self.assertTrue(np.issubdtype(col.dtype, np.datetime64)) batch = extractor.extract_batch(pa_table) self.assertTrue(np.issubdtype(batch["d"][0].dtype, np.datetime64)) self.assertTrue(np.issubdtype(batch["d"].dtype, np.datetime64)) def test_pandas_extractor(self): pa_table = self._create_dummy_table() extractor = PandasArrowExtractor() row = extractor.extract_row(pa_table) self.assertIsInstance(row, pd.DataFrame) pd.testing.assert_series_equal(row["a"], pd.Series(_COL_A, name="a")[:1]) pd.testing.assert_series_equal(row["b"], pd.Series(_COL_B, name="b")[:1]) pd.testing.assert_series_equal(row["d"], pd.Series(_COL_D, name="d")[:1]) col = extractor.extract_column(pa_table) pd.testing.assert_series_equal(col, pd.Series(_COL_A, name="a")) batch = extractor.extract_batch(pa_table) self.assertIsInstance(batch, pd.DataFrame) pd.testing.assert_series_equal(batch["a"], pd.Series(_COL_A, name="a")) pd.testing.assert_series_equal(batch["b"], pd.Series(_COL_B, name="b")) pd.testing.assert_series_equal(batch["d"], pd.Series(_COL_D, name="d")) class LazyDictTest(TestCase): def _create_dummy_table(self): return pa.Table.from_pydict({"a": _COL_A, "b": _COL_B, "c": _COL_C}) def _create_dummy_formatter(self): return PythonFormatter(lazy=True) def test_lazy_dict_copy(self): pa_table = self._create_dummy_table() formatter = self._create_dummy_formatter() lazy_batch = formatter.format_batch(pa_table) lazy_batch_copy = lazy_batch.copy() self.assertEqual(type(lazy_batch), type(lazy_batch_copy)) self.assertEqual(lazy_batch.items(), lazy_batch_copy.items()) lazy_batch["d"] = [1, 2, 3] self.assertNotEqual(lazy_batch.items(), lazy_batch_copy.items()) class FormatterTest(TestCase): def _create_dummy_table(self): return pa.Table.from_pydict({"a": _COL_A, "b": _COL_B, "c": _COL_C}) def test_python_formatter(self): pa_table = self._create_dummy_table() formatter = PythonFormatter() row = formatter.format_row(pa_table) self.assertEqual(row, {"a": _COL_A[0], "b": _COL_B[0], "c": _COL_C[0]}) col = formatter.format_column(pa_table) self.assertEqual(col, _COL_A) batch = formatter.format_batch(pa_table) self.assertEqual(batch, {"a": _COL_A, "b": _COL_B, "c": _COL_C}) def test_python_formatter_lazy(self): pa_table = self._create_dummy_table() formatter = PythonFormatter(lazy=True) row = formatter.format_row(pa_table) self.assertIsInstance(row, LazyRow) self.assertEqual(row["a"], _COL_A[0]) self.assertEqual(row["b"], _COL_B[0]) self.assertEqual(row["c"], _COL_C[0]) batch = formatter.format_batch(pa_table) self.assertIsInstance(batch, LazyBatch) self.assertEqual(batch["a"], _COL_A) self.assertEqual(batch["b"], _COL_B) self.assertEqual(batch["c"], _COL_C) def test_numpy_formatter(self): pa_table = self._create_dummy_table() formatter = NumpyFormatter() row = formatter.format_row(pa_table) np.testing.assert_equal(row, {"a": _COL_A[0], "b": _COL_B[0], "c": np.array(_COL_C[0])}) col = formatter.format_column(pa_table) np.testing.assert_equal(col, np.array(_COL_A)) batch = formatter.format_batch(pa_table) np.testing.assert_equal(batch, {"a": np.array(_COL_A), "b": np.array(_COL_B), "c": np.array(_COL_C)}) assert batch["c"].shape == np.array(_COL_C).shape def test_numpy_formatter_np_array_kwargs(self): pa_table = self._create_dummy_table().drop(["b"]) formatter = NumpyFormatter(dtype=np.float16) row = formatter.format_row(pa_table) self.assertEqual(row["c"].dtype, np.dtype(np.float16)) col = formatter.format_column(pa_table) self.assertEqual(col.dtype, np.float16) batch = formatter.format_batch(pa_table) self.assertEqual(batch["a"].dtype, np.dtype(np.float16)) self.assertEqual(batch["c"].dtype, np.dtype(np.float16)) @require_pil def test_numpy_formatter_image(self): # same dimensions pa_table = pa.table({"image": [{"bytes": None, "path": str(IMAGE_PATH_1)}] * 2}) formatter = NumpyFormatter(features=Features({"image": Image()})) row = formatter.format_row(pa_table) self.assertEqual(row["image"].dtype, np.uint8) self.assertEqual(row["image"].shape, (480, 640, 3)) col = formatter.format_column(pa_table) self.assertEqual(col.dtype, np.uint8) self.assertEqual(col.shape, (2, 480, 640, 3)) batch = formatter.format_batch(pa_table) self.assertEqual(batch["image"].dtype, np.uint8) self.assertEqual(batch["image"].shape, (2, 480, 640, 3)) # different dimensions pa_table = pa.table( {"image": [{"bytes": None, "path": str(IMAGE_PATH_1)}, {"bytes": None, "path": str(IMAGE_PATH_2)}]} ) formatter = NumpyFormatter(features=Features({"image": Image()})) row = formatter.format_row(pa_table) self.assertEqual(row["image"].dtype, np.uint8) self.assertEqual(row["image"].shape, (480, 640, 3)) col = formatter.format_column(pa_table) self.assertIsInstance(col, np.ndarray) self.assertEqual(col.dtype, object) self.assertEqual(col[0].dtype, np.uint8) self.assertEqual(col[0].shape, (480, 640, 3)) batch = formatter.format_batch(pa_table) self.assertIsInstance(batch["image"], np.ndarray) self.assertEqual(batch["image"].dtype, object) self.assertEqual(batch["image"][0].dtype, np.uint8) self.assertEqual(batch["image"][0].shape, (480, 640, 3)) @require_sndfile def test_numpy_formatter_audio(self): pa_table = pa.table({"audio": [{"bytes": None, "path": str(AUDIO_PATH_1)}]}) formatter = NumpyFormatter(features=Features({"audio": Audio()})) row = formatter.format_row(pa_table) self.assertEqual(row["audio"]["array"].dtype, np.dtype(np.float32)) col = formatter.format_column(pa_table) self.assertEqual(col[0]["array"].dtype, np.float32) batch = formatter.format_batch(pa_table) self.assertEqual(batch["audio"][0]["array"].dtype, np.dtype(np.float32)) def test_pandas_formatter(self): pa_table = self._create_dummy_table() formatter = PandasFormatter() row = formatter.format_row(pa_table) self.assertIsInstance(row, pd.DataFrame) pd.testing.assert_series_equal(row["a"], pd.Series(_COL_A, name="a")[:1]) pd.testing.assert_series_equal(row["b"], pd.Series(_COL_B, name="b")[:1]) col = formatter.format_column(pa_table) pd.testing.assert_series_equal(col, pd.Series(_COL_A, name="a")) batch = formatter.format_batch(pa_table) self.assertIsInstance(batch, pd.DataFrame) pd.testing.assert_series_equal(batch["a"], pd.Series(_COL_A, name="a")) pd.testing.assert_series_equal(batch["b"], pd.Series(_COL_B, name="b")) @require_torch def test_torch_formatter(self): import torch from datasets.formatting import TorchFormatter pa_table = self._create_dummy_table() formatter = TorchFormatter() row = formatter.format_row(pa_table) torch.testing.assert_close(row["a"], torch.tensor(_COL_A, dtype=torch.int64)[0]) assert row["b"] == _COL_B[0] torch.testing.assert_close(row["c"], torch.tensor(_COL_C, dtype=torch.float32)[0]) col = formatter.format_column(pa_table) torch.testing.assert_close(col, torch.tensor(_COL_A, dtype=torch.int64)) batch = formatter.format_batch(pa_table) torch.testing.assert_close(batch["a"], torch.tensor(_COL_A, dtype=torch.int64)) assert batch["b"] == _COL_B torch.testing.assert_close(batch["c"], torch.tensor(_COL_C, dtype=torch.float32)) assert batch["c"].shape == np.array(_COL_C).shape @require_torch def test_torch_formatter_torch_tensor_kwargs(self): import torch from datasets.formatting import TorchFormatter pa_table = self._create_dummy_table().drop(["b"]) formatter = TorchFormatter(dtype=torch.float16) row = formatter.format_row(pa_table) self.assertEqual(row["c"].dtype, torch.float16) col = formatter.format_column(pa_table) self.assertEqual(col.dtype, torch.float16) batch = formatter.format_batch(pa_table) self.assertEqual(batch["a"].dtype, torch.float16) self.assertEqual(batch["c"].dtype, torch.float16) @require_torch @require_pil def test_torch_formatter_image(self): import torch from datasets.formatting import TorchFormatter # same dimensions pa_table = pa.table({"image": [{"bytes": None, "path": str(IMAGE_PATH_1)}] * 2}) formatter = TorchFormatter(features=Features({"image": Image()})) row = formatter.format_row(pa_table) self.assertEqual(row["image"].dtype, torch.uint8) self.assertEqual(row["image"].shape, (480, 640, 3)) col = formatter.format_column(pa_table) self.assertEqual(col.dtype, torch.uint8) self.assertEqual(col.shape, (2, 480, 640, 3)) batch = formatter.format_batch(pa_table) self.assertEqual(batch["image"].dtype, torch.uint8) self.assertEqual(batch["image"].shape, (2, 480, 640, 3)) # different dimensions pa_table = pa.table( {"image": [{"bytes": None, "path": str(IMAGE_PATH_1)}, {"bytes": None, "path": str(IMAGE_PATH_2)}]} ) formatter = TorchFormatter(features=Features({"image": Image()})) row = formatter.format_row(pa_table) self.assertEqual(row["image"].dtype, torch.uint8) self.assertEqual(row["image"].shape, (480, 640, 3)) col = formatter.format_column(pa_table) self.assertIsInstance(col, list) self.assertEqual(col[0].dtype, torch.uint8) self.assertEqual(col[0].shape, (480, 640, 3)) batch = formatter.format_batch(pa_table) self.assertIsInstance(batch["image"], list) self.assertEqual(batch["image"][0].dtype, torch.uint8) self.assertEqual(batch["image"][0].shape, (480, 640, 3)) @require_torch @require_sndfile def test_torch_formatter_audio(self): import torch from datasets.formatting import TorchFormatter pa_table = pa.table({"audio": [{"bytes": None, "path": str(AUDIO_PATH_1)}]}) formatter = TorchFormatter(features=Features({"audio": Audio()})) row = formatter.format_row(pa_table) self.assertEqual(row["audio"]["array"].dtype, torch.float32) col = formatter.format_column(pa_table) self.assertEqual(col[0]["array"].dtype, torch.float32) batch = formatter.format_batch(pa_table) self.assertEqual(batch["audio"][0]["array"].dtype, torch.float32) @require_tf def test_tf_formatter(self): import tensorflow as tf from datasets.formatting import TFFormatter pa_table = self._create_dummy_table() formatter = TFFormatter() row = formatter.format_row(pa_table) tf.debugging.assert_equal(row["a"], tf.convert_to_tensor(_COL_A, dtype=tf.int64)[0]) tf.debugging.assert_equal(row["b"], tf.convert_to_tensor(_COL_B, dtype=tf.string)[0]) tf.debugging.assert_equal(row["c"], tf.convert_to_tensor(_COL_C, dtype=tf.float32)[0]) col = formatter.format_column(pa_table) tf.debugging.assert_equal(col, tf.ragged.constant(_COL_A, dtype=tf.int64)) batch = formatter.format_batch(pa_table) tf.debugging.assert_equal(batch["a"], tf.convert_to_tensor(_COL_A, dtype=tf.int64)) tf.debugging.assert_equal(batch["b"], tf.convert_to_tensor(_COL_B, dtype=tf.string)) self.assertIsInstance(batch["c"], tf.Tensor) self.assertEqual(batch["c"].dtype, tf.float32) tf.debugging.assert_equal( batch["c"].shape.as_list(), tf.convert_to_tensor(_COL_C, dtype=tf.float32).shape.as_list() ) tf.debugging.assert_equal(tf.convert_to_tensor(batch["c"]), tf.convert_to_tensor(_COL_C, dtype=tf.float32)) @require_tf def test_tf_formatter_tf_tensor_kwargs(self): import tensorflow as tf from datasets.formatting import TFFormatter pa_table = self._create_dummy_table().drop(["b"]) formatter = TFFormatter(dtype=tf.float16) row = formatter.format_row(pa_table) self.assertEqual(row["c"].dtype, tf.float16) col = formatter.format_column(pa_table) self.assertEqual(col.dtype, tf.float16) batch = formatter.format_batch(pa_table) self.assertEqual(batch["a"].dtype, tf.float16) self.assertEqual(batch["c"].dtype, tf.float16) @require_tf @require_pil def test_tf_formatter_image(self): import tensorflow as tf from datasets.formatting import TFFormatter # same dimensions pa_table = pa.table({"image": [{"bytes": None, "path": str(IMAGE_PATH_1)}] * 2}) formatter = TFFormatter(features=Features({"image": Image()})) row = formatter.format_row(pa_table) self.assertEqual(row["image"].dtype, tf.uint8) self.assertEqual(row["image"].shape, (480, 640, 3)) col = formatter.format_column(pa_table) self.assertEqual(col.dtype, tf.uint8) self.assertEqual(col.shape, (2, 480, 640, 3)) batch = formatter.format_batch(pa_table) self.assertEqual(batch["image"][0].dtype, tf.uint8) self.assertEqual(batch["image"].shape, (2, 480, 640, 3)) # different dimensions pa_table = pa.table( {"image": [{"bytes": None, "path": str(IMAGE_PATH_1)}, {"bytes": None, "path": str(IMAGE_PATH_2)}]} ) formatter = TFFormatter(features=Features({"image": Image()})) row = formatter.format_row(pa_table) self.assertEqual(row["image"].dtype, tf.uint8) self.assertEqual(row["image"].shape, (480, 640, 3)) col = formatter.format_column(pa_table) self.assertIsInstance(col, list) self.assertEqual(col[0].dtype, tf.uint8) self.assertEqual(col[0].shape, (480, 640, 3)) batch = formatter.format_batch(pa_table) self.assertIsInstance(batch["image"], list) self.assertEqual(batch["image"][0].dtype, tf.uint8) self.assertEqual(batch["image"][0].shape, (480, 640, 3)) @require_tf @require_sndfile def test_tf_formatter_audio(self): import tensorflow as tf from datasets.formatting import TFFormatter pa_table = pa.table({"audio": [{"bytes": None, "path": str(AUDIO_PATH_1)}]}) formatter = TFFormatter(features=Features({"audio": Audio()})) row = formatter.format_row(pa_table) self.assertEqual(row["audio"]["array"].dtype, tf.float32) col = formatter.format_column(pa_table) self.assertEqual(col[0]["array"].dtype, tf.float32) batch = formatter.format_batch(pa_table) self.assertEqual(batch["audio"][0]["array"].dtype, tf.float32) @require_jax def test_jax_formatter(self): import jax import jax.numpy as jnp from datasets.formatting import JaxFormatter pa_table = self._create_dummy_table() formatter = JaxFormatter() row = formatter.format_row(pa_table) jnp.allclose(row["a"], jnp.array(_COL_A, dtype=jnp.int64 if jax.config.jax_enable_x64 else jnp.int32)[0]) assert row["b"] == _COL_B[0] jnp.allclose(row["c"], jnp.array(_COL_C, dtype=jnp.float32)[0]) col = formatter.format_column(pa_table) jnp.allclose(col, jnp.array(_COL_A, dtype=jnp.int64 if jax.config.jax_enable_x64 else jnp.int32)) batch = formatter.format_batch(pa_table) jnp.allclose(batch["a"], jnp.array(_COL_A, dtype=jnp.int64 if jax.config.jax_enable_x64 else jnp.int32)) assert batch["b"] == _COL_B jnp.allclose(batch["c"], jnp.array(_COL_C, dtype=jnp.float32)) assert batch["c"].shape == np.array(_COL_C).shape @require_jax def test_jax_formatter_jnp_array_kwargs(self): import jax.numpy as jnp from datasets.formatting import JaxFormatter pa_table = self._create_dummy_table().drop(["b"]) formatter = JaxFormatter(dtype=jnp.float16) row = formatter.format_row(pa_table) self.assertEqual(row["c"].dtype, jnp.float16) col = formatter.format_column(pa_table) self.assertEqual(col.dtype, jnp.float16) batch = formatter.format_batch(pa_table) self.assertEqual(batch["a"].dtype, jnp.float16) self.assertEqual(batch["c"].dtype, jnp.float16) @require_jax @require_pil def test_jax_formatter_image(self): import jax.numpy as jnp from datasets.formatting import JaxFormatter # same dimensions pa_table = pa.table({"image": [{"bytes": None, "path": str(IMAGE_PATH_1)}] * 2}) formatter = JaxFormatter(features=Features({"image": Image()})) row = formatter.format_row(pa_table) self.assertEqual(row["image"].dtype, jnp.uint8) self.assertEqual(row["image"].shape, (480, 640, 3)) col = formatter.format_column(pa_table) self.assertEqual(col.dtype, jnp.uint8) self.assertEqual(col.shape, (2, 480, 640, 3)) batch = formatter.format_batch(pa_table) self.assertEqual(batch["image"].dtype, jnp.uint8) self.assertEqual(batch["image"].shape, (2, 480, 640, 3)) # different dimensions pa_table = pa.table( {"image": [{"bytes": None, "path": str(IMAGE_PATH_1)}, {"bytes": None, "path": str(IMAGE_PATH_2)}]} ) formatter = JaxFormatter(features=Features({"image": Image()})) row = formatter.format_row(pa_table) self.assertEqual(row["image"].dtype, jnp.uint8) self.assertEqual(row["image"].shape, (480, 640, 3)) col = formatter.format_column(pa_table) self.assertIsInstance(col, list) self.assertEqual(col[0].dtype, jnp.uint8) self.assertEqual(col[0].shape, (480, 640, 3)) batch = formatter.format_batch(pa_table) self.assertIsInstance(batch["image"], list) self.assertEqual(batch["image"][0].dtype, jnp.uint8) self.assertEqual(batch["image"][0].shape, (480, 640, 3)) @require_jax @require_sndfile def test_jax_formatter_audio(self): import jax.numpy as jnp from datasets.formatting import JaxFormatter pa_table = pa.table({"audio": [{"bytes": None, "path": str(AUDIO_PATH_1)}]}) formatter = JaxFormatter(features=Features({"audio": Audio()})) row = formatter.format_row(pa_table) self.assertEqual(row["audio"]["array"].dtype, jnp.float32) col = formatter.format_column(pa_table) self.assertEqual(col[0]["array"].dtype, jnp.float32) batch = formatter.format_batch(pa_table) self.assertEqual(batch["audio"][0]["array"].dtype, jnp.float32) @require_jax def test_jax_formatter_device(self): import jax from datasets.formatting import JaxFormatter pa_table = self._create_dummy_table() device = jax.devices()[0] formatter = JaxFormatter(device=str(device)) row = formatter.format_row(pa_table) assert row["a"].device() == device assert row["c"].device() == device col = formatter.format_column(pa_table) assert col.device() == device batch = formatter.format_batch(pa_table) assert batch["a"].device() == device assert batch["c"].device() == device class QueryTest(TestCase): def _create_dummy_table(self): return pa.Table.from_pydict({"a": _COL_A, "b": _COL_B, "c": _COL_C}) def _create_dummy_arrow_indices(self): return pa.Table.from_arrays([pa.array(_INDICES, type=pa.uint64())], names=["indices"]) def assertTableEqual(self, first: pa.Table, second: pa.Table): self.assertEqual(first.schema, second.schema) for first_array, second_array in zip(first, second): self.assertEqual(first_array, second_array) self.assertEqual(first, second) def test_query_table_int(self): pa_table = self._create_dummy_table() table = InMemoryTable(pa_table) n = pa_table.num_rows # classical usage subtable = query_table(table, 0) self.assertTableEqual(subtable, pa.Table.from_pydict({"a": _COL_A[:1], "b": _COL_B[:1], "c": _COL_C[:1]})) subtable = query_table(table, 1) self.assertTableEqual(subtable, pa.Table.from_pydict({"a": _COL_A[1:2], "b": _COL_B[1:2], "c": _COL_C[1:2]})) subtable = query_table(table, -1) self.assertTableEqual(subtable, pa.Table.from_pydict({"a": _COL_A[-1:], "b": _COL_B[-1:], "c": _COL_C[-1:]})) # raise an IndexError with self.assertRaises(IndexError): query_table(table, n) with self.assertRaises(IndexError): query_table(table, -(n + 1)) # with indices indices = InMemoryTable(self._create_dummy_arrow_indices()) subtable = query_table(table, 0, indices=indices) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": [_COL_A[_INDICES[0]]], "b": [_COL_B[_INDICES[0]]], "c": [_COL_C[_INDICES[0]]]}), ) with self.assertRaises(IndexError): assert len(indices) < n query_table(table, len(indices), indices=indices) def test_query_table_slice(self): pa_table = self._create_dummy_table() table = InMemoryTable(pa_table) n = pa_table.num_rows # classical usage subtable = query_table(table, slice(0, 1)) self.assertTableEqual(subtable, pa.Table.from_pydict({"a": _COL_A[:1], "b": _COL_B[:1], "c": _COL_C[:1]})) subtable = query_table(table, slice(1, 2)) self.assertTableEqual(subtable, pa.Table.from_pydict({"a": _COL_A[1:2], "b": _COL_B[1:2], "c": _COL_C[1:2]})) subtable = query_table(table, slice(-2, -1)) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": _COL_A[-2:-1], "b": _COL_B[-2:-1], "c": _COL_C[-2:-1]}) ) # usage with None subtable = query_table(table, slice(-1, None)) self.assertTableEqual(subtable, pa.Table.from_pydict({"a": _COL_A[-1:], "b": _COL_B[-1:], "c": _COL_C[-1:]})) subtable = query_table(table, slice(None, n + 1)) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": _COL_A[: n + 1], "b": _COL_B[: n + 1], "c": _COL_C[: n + 1]}) ) self.assertTableEqual(subtable, pa.Table.from_pydict({"a": _COL_A, "b": _COL_B, "c": _COL_C})) subtable = query_table(table, slice(-(n + 1), None)) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": _COL_A[-(n + 1) :], "b": _COL_B[-(n + 1) :], "c": _COL_C[-(n + 1) :]}) ) self.assertTableEqual(subtable, pa.Table.from_pydict({"a": _COL_A, "b": _COL_B, "c": _COL_C})) # usage with step subtable = query_table(table, slice(None, None, 2)) self.assertTableEqual(subtable, pa.Table.from_pydict({"a": _COL_A[::2], "b": _COL_B[::2], "c": _COL_C[::2]})) # empty ouput but no errors subtable = query_table(table, slice(-1, 0)) # usage with both negative and positive idx assert len(_COL_A[-1:0]) == 0 self.assertTableEqual(subtable, pa_table.slice(0, 0)) subtable = query_table(table, slice(2, 1)) assert len(_COL_A[2:1]) == 0 self.assertTableEqual(subtable, pa_table.slice(0, 0)) subtable = query_table(table, slice(n, n)) assert len(_COL_A[n:n]) == 0 self.assertTableEqual(subtable, pa_table.slice(0, 0)) subtable = query_table(table, slice(n, n + 1)) assert len(_COL_A[n : n + 1]) == 0 self.assertTableEqual(subtable, pa_table.slice(0, 0)) # it's not possible to get an error with a slice # with indices indices = InMemoryTable(self._create_dummy_arrow_indices()) subtable = query_table(table, slice(0, 1), indices=indices) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": [_COL_A[_INDICES[0]]], "b": [_COL_B[_INDICES[0]]], "c": [_COL_C[_INDICES[0]]]}), ) subtable = query_table(table, slice(n - 1, n), indices=indices) assert len(indices.column(0).to_pylist()[n - 1 : n]) == 0 self.assertTableEqual(subtable, pa_table.slice(0, 0)) def test_query_table_range(self): pa_table = self._create_dummy_table() table = InMemoryTable(pa_table) n = pa_table.num_rows np_A, np_B, np_C = np.array(_COL_A, dtype=np.int64), np.array(_COL_B), np.array(_COL_C) # classical usage subtable = query_table(table, range(0, 1)) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": np_A[range(0, 1)], "b": np_B[range(0, 1)], "c": np_C[range(0, 1)].tolist()}), ) subtable = query_table(table, range(1, 2)) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": np_A[range(1, 2)], "b": np_B[range(1, 2)], "c": np_C[range(1, 2)].tolist()}), ) subtable = query_table(table, range(-2, -1)) self.assertTableEqual( subtable, pa.Table.from_pydict( {"a": np_A[range(-2, -1)], "b": np_B[range(-2, -1)], "c": np_C[range(-2, -1)].tolist()} ), ) # usage with both negative and positive idx subtable = query_table(table, range(-1, 0)) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": np_A[range(-1, 0)], "b": np_B[range(-1, 0)], "c": np_C[range(-1, 0)].tolist()}), ) subtable = query_table(table, range(-1, n)) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": np_A[range(-1, n)], "b": np_B[range(-1, n)], "c": np_C[range(-1, n)].tolist()}), ) # usage with step subtable = query_table(table, range(0, n, 2)) self.assertTableEqual( subtable, pa.Table.from_pydict( {"a": np_A[range(0, n, 2)], "b": np_B[range(0, n, 2)], "c": np_C[range(0, n, 2)].tolist()} ), ) subtable = query_table(table, range(0, n + 1, 2 * n)) self.assertTableEqual( subtable, pa.Table.from_pydict( { "a": np_A[range(0, n + 1, 2 * n)], "b": np_B[range(0, n + 1, 2 * n)], "c": np_C[range(0, n + 1, 2 * n)].tolist(), } ), ) # empty ouput but no errors subtable = query_table(table, range(2, 1)) assert len(np_A[range(2, 1)]) == 0 self.assertTableEqual(subtable, pa.Table.from_batches([], schema=pa_table.schema)) subtable = query_table(table, range(n, n)) assert len(np_A[range(n, n)]) == 0 self.assertTableEqual(subtable, pa.Table.from_batches([], schema=pa_table.schema)) # raise an IndexError with self.assertRaises(IndexError): with self.assertRaises(IndexError): np_A[range(0, n + 1)] query_table(table, range(0, n + 1)) with self.assertRaises(IndexError): with self.assertRaises(IndexError): np_A[range(-(n + 1), -1)] query_table(table, range(-(n + 1), -1)) with self.assertRaises(IndexError): with self.assertRaises(IndexError): np_A[range(n, n + 1)] query_table(table, range(n, n + 1)) # with indices indices = InMemoryTable(self._create_dummy_arrow_indices()) subtable = query_table(table, range(0, 1), indices=indices) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": [_COL_A[_INDICES[0]]], "b": [_COL_B[_INDICES[0]]], "c": [_COL_C[_INDICES[0]]]}), ) with self.assertRaises(IndexError): assert len(indices) < n query_table(table, range(len(indices), len(indices) + 1), indices=indices) def test_query_table_str(self): pa_table = self._create_dummy_table() table = InMemoryTable(pa_table) subtable = query_table(table, "a") self.assertTableEqual(subtable, pa.Table.from_pydict({"a": _COL_A})) with self.assertRaises(KeyError): query_table(table, "z") indices = InMemoryTable(self._create_dummy_arrow_indices()) subtable = query_table(table, "a", indices=indices) self.assertTableEqual(subtable, pa.Table.from_pydict({"a": [_COL_A[i] for i in _INDICES]})) def test_query_table_iterable(self): pa_table = self._create_dummy_table() table = InMemoryTable(pa_table) n = pa_table.num_rows np_A, np_B, np_C = np.array(_COL_A, dtype=np.int64), np.array(_COL_B), np.array(_COL_C) # classical usage subtable = query_table(table, [0]) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": np_A[[0]], "b": np_B[[0]], "c": np_C[[0]].tolist()}) ) subtable = query_table(table, [1]) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": np_A[[1]], "b": np_B[[1]], "c": np_C[[1]].tolist()}) ) subtable = query_table(table, [-1]) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": np_A[[-1]], "b": np_B[[-1]], "c": np_C[[-1]].tolist()}) ) subtable = query_table(table, [0, -1, 1]) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": np_A[[0, -1, 1]], "b": np_B[[0, -1, 1]], "c": np_C[[0, -1, 1]].tolist()}), ) # numpy iterable subtable = query_table(table, np.array([0, -1, 1])) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": np_A[[0, -1, 1]], "b": np_B[[0, -1, 1]], "c": np_C[[0, -1, 1]].tolist()}), ) # empty ouput but no errors subtable = query_table(table, []) assert len(np_A[[]]) == 0 self.assertTableEqual(subtable, pa.Table.from_batches([], schema=pa_table.schema)) # raise an IndexError with self.assertRaises(IndexError): with self.assertRaises(IndexError): np_A[[n]] query_table(table, [n]) with self.assertRaises(IndexError): with self.assertRaises(IndexError): np_A[[-(n + 1)]] query_table(table, [-(n + 1)]) # with indices indices = InMemoryTable(self._create_dummy_arrow_indices()) subtable = query_table(table, [0], indices=indices) self.assertTableEqual( subtable, pa.Table.from_pydict({"a": [_COL_A[_INDICES[0]]], "b": [_COL_B[_INDICES[0]]], "c": [_COL_C[_INDICES[0]]]}), ) with self.assertRaises(IndexError): assert len(indices) < n query_table(table, [len(indices)], indices=indices) def test_query_table_invalid_key_type(self): pa_table = self._create_dummy_table() table = InMemoryTable(pa_table) with self.assertRaises(TypeError): query_table(table, 0.0) with self.assertRaises(TypeError): query_table(table, [0, "a"]) with self.assertRaises(TypeError): query_table(table, int) with self.assertRaises(TypeError): def iter_to_inf(start=0): while True: yield start start += 1 query_table(table, iter_to_inf()) @pytest.fixture(scope="session") def arrow_table(): return pa.Table.from_pydict({"col_int": [0, 1, 2], "col_float": [0.0, 1.0, 2.0]}) @require_tf @pytest.mark.parametrize( "cast_schema", [ None, [("col_int", pa.int64()), ("col_float", pa.float64())], [("col_int", pa.int32()), ("col_float", pa.float64())], [("col_int", pa.int64()), ("col_float", pa.float32())], ], ) def test_tf_formatter_sets_default_dtypes(cast_schema, arrow_table): import tensorflow as tf from datasets.formatting import TFFormatter if cast_schema: arrow_table = arrow_table.cast(pa.schema(cast_schema)) arrow_table_dict = arrow_table.to_pydict() list_int = arrow_table_dict["col_int"] list_float = arrow_table_dict["col_float"] formatter = TFFormatter() row = formatter.format_row(arrow_table) tf.debugging.assert_equal(row["col_int"], tf.ragged.constant(list_int, dtype=tf.int64)[0]) tf.debugging.assert_equal(row["col_float"], tf.ragged.constant(list_float, dtype=tf.float32)[0]) col = formatter.format_column(arrow_table) tf.debugging.assert_equal(col, tf.ragged.constant(list_int, dtype=tf.int64)) batch = formatter.format_batch(arrow_table) tf.debugging.assert_equal(batch["col_int"], tf.ragged.constant(list_int, dtype=tf.int64)) tf.debugging.assert_equal(batch["col_float"], tf.ragged.constant(list_float, dtype=tf.float32)) @require_torch @pytest.mark.parametrize( "cast_schema", [ None, [("col_int", pa.int64()), ("col_float", pa.float64())], [("col_int", pa.int32()), ("col_float", pa.float64())], [("col_int", pa.int64()), ("col_float", pa.float32())], ], ) def test_torch_formatter_sets_default_dtypes(cast_schema, arrow_table): import torch from datasets.formatting import TorchFormatter if cast_schema: arrow_table = arrow_table.cast(pa.schema(cast_schema)) arrow_table_dict = arrow_table.to_pydict() list_int = arrow_table_dict["col_int"] list_float = arrow_table_dict["col_float"] formatter = TorchFormatter() row = formatter.format_row(arrow_table) torch.testing.assert_close(row["col_int"], torch.tensor(list_int, dtype=torch.int64)[0]) torch.testing.assert_close(row["col_float"], torch.tensor(list_float, dtype=torch.float32)[0]) col = formatter.format_column(arrow_table) torch.testing.assert_close(col, torch.tensor(list_int, dtype=torch.int64)) batch = formatter.format_batch(arrow_table) torch.testing.assert_close(batch["col_int"], torch.tensor(list_int, dtype=torch.int64)) torch.testing.assert_close(batch["col_float"], torch.tensor(list_float, dtype=torch.float32)) def test_iterable_dataset_of_arrays_format_to_arrow(any_arrays_dataset: IterableDataset): formatted = any_arrays_dataset.with_format("arrow") assert all(isinstance(example, pa.Table) for example in formatted) def test_iterable_dataset_of_arrays_format_to_numpy(any_arrays_dataset: IterableDataset): formatted = any_arrays_dataset.with_format("np") assert all(isinstance(example["array"], np.ndarray) for example in formatted) @require_torch def test_iterable_dataset_of_arrays_format_to_torch(any_arrays_dataset: IterableDataset): import torch formatted = any_arrays_dataset.with_format("torch") assert all(isinstance(example["array"], torch.Tensor) for example in formatted) @require_tf def test_iterable_dataset_of_arrays_format_to_tf(any_arrays_dataset: IterableDataset): import tensorflow as tf formatted = any_arrays_dataset.with_format("tf") assert all(isinstance(example["array"], tf.Tensor) for example in formatted) @require_jax def test_iterable_dataset_of_arrays_format_to_jax(any_arrays_dataset: IterableDataset): import jax.numpy as jnp formatted = any_arrays_dataset.with_format("jax") assert all(isinstance(example["array"], jnp.ndarray) for example in formatted)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_hf_gcp.py
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path DATASETS_ON_HF_GCP = [ {"dataset": "wikipedia", "config_name": "20220301.de"}, {"dataset": "wikipedia", "config_name": "20220301.en"}, {"dataset": "wikipedia", "config_name": "20220301.fr"}, {"dataset": "wikipedia", "config_name": "20220301.frr"}, {"dataset": "wikipedia", "config_name": "20220301.it"}, {"dataset": "wikipedia", "config_name": "20220301.simple"}, {"dataset": "snli", "config_name": "plain_text"}, {"dataset": "eli5", "config_name": "LFQA_reddit"}, {"dataset": "wiki40b", "config_name": "en"}, {"dataset": "wiki_dpr", "config_name": "psgs_w100.nq.compressed"}, {"dataset": "wiki_dpr", "config_name": "psgs_w100.nq.no_index"}, {"dataset": "wiki_dpr", "config_name": "psgs_w100.multiset.no_index"}, {"dataset": "natural_questions", "config_name": "default"}, ] def list_datasets_on_hf_gcp_parameters(with_config=True): if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=True)) class TestDatasetOnHfGcp(TestCase): dataset = None config_name = None def test_dataset_info_available(self, dataset, config_name): with TemporaryDirectory() as tmp_dir: dataset_module = dataset_module_factory(dataset, cache_dir=tmp_dir) builder_cls = import_main_class(dataset_module.module_path, dataset=True) builder_instance: DatasetBuilder = builder_cls( cache_dir=tmp_dir, config_name=config_name, hash=dataset_module.hash, ) dataset_info_url = "/".join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=False).replace(os.sep, "/"), config.DATASET_INFO_FILENAME, ] ) datset_info_path = cached_path(dataset_info_url, cache_dir=tmp_dir) self.assertTrue(os.path.exists(datset_info_path)) @pytest.mark.integration def test_as_dataset_from_hf_gcs(tmp_path_factory): tmp_dir = tmp_path_factory.mktemp("test_hf_gcp") / "test_wikipedia_simple" dataset_module = dataset_module_factory("wikipedia", cache_dir=tmp_dir) builder_cls = import_main_class(dataset_module.module_path) builder_instance: DatasetBuilder = builder_cls( cache_dir=tmp_dir, config_name="20220301.frr", hash=dataset_module.hash, ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam builder_instance._download_and_prepare = None builder_instance.download_and_prepare() ds = builder_instance.as_dataset() assert ds @pytest.mark.integration def test_as_streaming_dataset_from_hf_gcs(tmp_path): dataset_module = dataset_module_factory("wikipedia", cache_dir=tmp_path) builder_cls = import_main_class(dataset_module.module_path, dataset=True) builder_instance: DatasetBuilder = builder_cls( cache_dir=tmp_path, config_name="20220301.frr", hash=dataset_module.hash, ) ds = builder_instance.as_streaming_dataset() assert ds assert isinstance(ds, IterableDatasetDict) assert "train" in ds assert isinstance(ds["train"], IterableDataset) assert next(iter(ds["train"]))
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_hub.py
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("repo_id", ["canonical_dataset_name", "org-name/dataset-name"]) @pytest.mark.parametrize("path", ["filename.csv", "filename with blanks.csv"]) @pytest.mark.parametrize("revision", [None, "v2"]) def test_hf_hub_url(repo_id, path, revision): url = hf_hub_url(repo_id=repo_id, path=path, revision=revision) assert url == f"https://huggingface.co/datasets/{repo_id}/resolve/{revision or 'main'}/{quote(path)}"
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_info.py
import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( "files", [ ["full:README.md", "dataset_infos.json"], ["empty:README.md", "dataset_infos.json"], ["dataset_infos.json"], ["full:README.md"], ], ) def test_from_dir(files, tmp_path_factory): dataset_infos_dir = tmp_path_factory.mktemp("dset_infos_dir") if "full:README.md" in files: with open(dataset_infos_dir / "README.md", "w") as f: f.write("---\ndataset_info:\n dataset_size: 42\n---") if "empty:README.md" in files: with open(dataset_infos_dir / "README.md", "w") as f: f.write("") # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / "dataset_infos.json", "w") as f: f.write('{"default": {"dataset_size": 42}}') dataset_infos = DatasetInfosDict.from_directory(dataset_infos_dir) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( "dataset_info", [ DatasetInfo(), DatasetInfo( description="foo", features=Features({"a": Value("int32")}), builder_name="builder", config_name="config", version="1.0.0", splits=[{"name": "train"}], download_size=42, ), ], ) def test_dataset_info_dump_and_reload(tmp_path, dataset_info: DatasetInfo): tmp_path = str(tmp_path) dataset_info.write_to_directory(tmp_path) reloaded = DatasetInfo.from_directory(tmp_path) assert dataset_info == reloaded assert os.path.exists(os.path.join(tmp_path, "dataset_info.json")) def test_dataset_info_to_yaml_dict(): dataset_info = DatasetInfo( description="foo", citation="bar", homepage="https://foo.bar", license="CC0", features=Features({"a": Value("int32")}), post_processed={}, supervised_keys=(), task_templates=[], builder_name="builder", config_name="config", version="1.0.0", splits=[{"name": "train", "num_examples": 42}], download_checksums={}, download_size=1337, post_processing_size=442, dataset_size=1234, size_in_bytes=1337 + 442 + 1234, ) dataset_info_yaml_dict = dataset_info._to_yaml_dict() assert sorted(dataset_info_yaml_dict) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key], (list, dict, int, str)) dataset_info_yaml = yaml.safe_dump(dataset_info_yaml_dict) reloaded = yaml.safe_load(dataset_info_yaml) assert dataset_info_yaml_dict == reloaded def test_dataset_info_to_yaml_dict_empty(): dataset_info = DatasetInfo() dataset_info_yaml_dict = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( "dataset_infos_dict", [ DatasetInfosDict(), DatasetInfosDict({"default": DatasetInfo()}), DatasetInfosDict({"my_config_name": DatasetInfo()}), DatasetInfosDict( { "default": DatasetInfo( description="foo", features=Features({"a": Value("int32")}), builder_name="builder", config_name="config", version="1.0.0", splits=[{"name": "train"}], download_size=42, ) } ), DatasetInfosDict( { "v1": DatasetInfo(dataset_size=42), "v2": DatasetInfo(dataset_size=1337), } ), ], ) def test_dataset_infos_dict_dump_and_reload(tmp_path, dataset_infos_dict: DatasetInfosDict): tmp_path = str(tmp_path) dataset_infos_dict.write_to_directory(tmp_path) reloaded = DatasetInfosDict.from_directory(tmp_path) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): dataset_info.config_name = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml dataset_infos_dict[config_name] = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict()) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(tmp_path, "README.md"))
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_info_utils.py
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize("dataset_size", [None, 400 * 2**20, 600 * 2**20]) @pytest.mark.parametrize("input_in_memory_max_size", ["default", 0, 100 * 2**20, 900 * 2**20]) def test_is_small_dataset(dataset_size, input_in_memory_max_size, monkeypatch): if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config, "IN_MEMORY_MAX_SIZE", input_in_memory_max_size) in_memory_max_size = datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: expected = dataset_size < in_memory_max_size else: expected = False result = is_small_dataset(dataset_size) assert result == expected
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_inspect.py
import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) pytestmark = pytest.mark.integration @pytest.mark.parametrize("path", ["paws", "csv"]) def test_inspect_dataset(path, tmp_path): inspect_dataset(path, tmp_path) script_name = path + ".py" assert script_name in os.listdir(tmp_path) assert "__pycache__" not in os.listdir(tmp_path) @pytest.mark.filterwarnings("ignore:inspect_metric is deprecated:FutureWarning") @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning") @pytest.mark.parametrize("path", ["accuracy"]) def test_inspect_metric(path, tmp_path): inspect_metric(path, tmp_path) script_name = path + ".py" assert script_name in os.listdir(tmp_path) assert "__pycache__" not in os.listdir(tmp_path) @pytest.mark.parametrize( "path, config_name, expected_splits", [ ("squad", "plain_text", ["train", "validation"]), ("dalle-mini/wit", "default", ["train"]), ("paws", "labeled_final", ["train", "test", "validation"]), ], ) def test_get_dataset_config_info(path, config_name, expected_splits): info = get_dataset_config_info(path, config_name=config_name) assert info.config_name == config_name assert list(info.splits.keys()) == expected_splits def test_get_dataset_config_info_private(hf_token, hf_private_dataset_repo_txt_data): info = get_dataset_config_info(hf_private_dataset_repo_txt_data, config_name="default", token=hf_token) assert list(info.splits.keys()) == ["train"] @pytest.mark.parametrize( "path, config_name, expected_exception", [ ("paws", None, ValueError), ], ) def test_get_dataset_config_info_error(path, config_name, expected_exception): with pytest.raises(expected_exception): get_dataset_config_info(path, config_name=config_name) @pytest.mark.parametrize( "path, expected", [ ("squad", ["plain_text"]), ("acronym_identification", ["default"]), ("lhoestq/squad", ["plain_text"]), ("lhoestq/test", ["default"]), ("lhoestq/demo1", ["default"]), ("dalle-mini/wit", ["default"]), ("datasets-maintainers/audiofolder_no_configs_in_metadata", ["default"]), ("datasets-maintainers/audiofolder_single_config_in_metadata", ["custom"]), ("datasets-maintainers/audiofolder_two_configs_in_metadata", ["v1", "v2"]), ], ) def test_get_dataset_config_names(path, expected): config_names = get_dataset_config_names(path) assert config_names == expected @pytest.mark.parametrize( "path, expected_configs, expected_splits_in_first_config", [ ("squad", ["plain_text"], ["train", "validation"]), ("dalle-mini/wit", ["default"], ["train"]), ("paws", ["labeled_final", "labeled_swap", "unlabeled_final"], ["train", "test", "validation"]), ], ) def test_get_dataset_info(path, expected_configs, expected_splits_in_first_config): infos = get_dataset_infos(path) assert list(infos.keys()) == expected_configs expected_config = expected_configs[0] assert expected_config in infos info = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys()) == expected_splits_in_first_config @pytest.mark.parametrize( "path, expected_config, expected_splits", [ ("squad", "plain_text", ["train", "validation"]), ("dalle-mini/wit", "default", ["train"]), ("paws", "labeled_final", ["train", "test", "validation"]), ], ) def test_get_dataset_split_names(path, expected_config, expected_splits): infos = get_dataset_infos(path) assert expected_config in infos info = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys()) == expected_splits @pytest.mark.parametrize( "path, config_name, expected_exception", [ ("paws", None, ValueError), ], ) def test_get_dataset_split_names_error(path, config_name, expected_exception): with pytest.raises(expected_exception): get_dataset_split_names(path, config_name=config_name)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_iterable_dataset.py
from copy import deepcopy from itertools import chain, islice import numpy as np import pandas as pd import pyarrow as pa import pyarrow.compute as pc import pytest from datasets import Dataset, load_dataset from datasets.combine import concatenate_datasets, interleave_datasets from datasets.features import ( ClassLabel, Features, Image, Value, ) from datasets.formatting import get_format_type_from_alias from datasets.info import DatasetInfo from datasets.iterable_dataset import ( ArrowExamplesIterable, BufferShuffledExamplesIterable, CyclingMultiSourcesExamplesIterable, ExamplesIterable, FilteredExamplesIterable, FormattingConfig, HorizontallyConcatenatedMultiSourcesExamplesIterable, IterableDataset, MappedExamplesIterable, RandomlyCyclingMultiSourcesExamplesIterable, SelectColumnsIterable, ShuffledDataSourcesArrowExamplesIterable, ShuffledDataSourcesExamplesIterable, ShufflingConfig, SkipExamplesIterable, StepExamplesIterable, TakeExamplesIterable, TypedExamplesIterable, VerticallyConcatenatedMultiSourcesExamplesIterable, _BaseExamplesIterable, _batch_arrow_tables, _batch_to_examples, _convert_to_arrow, _examples_to_batch, ) from .utils import ( assert_arrow_memory_doesnt_increase, is_rng_equal, require_dill_gt_0_3_2, require_not_windows, require_pyspark, require_tf, require_torch, ) DEFAULT_N_EXAMPLES = 20 DEFAULT_BATCH_SIZE = 4 DEFAULT_FILEPATH = "file.txt" SAMPLE_DATASET_IDENTIFIER = "lhoestq/test" # has dataset script def generate_examples_fn(**kwargs): kwargs = kwargs.copy() n = kwargs.pop("n", DEFAULT_N_EXAMPLES) filepaths = kwargs.pop("filepaths", None) for filepath in filepaths or [DEFAULT_FILEPATH]: if filepaths is not None: kwargs["filepath"] = filepath for i in range(n): yield f"{filepath}_{i}", {"id": i, **kwargs} def generate_tables_fn(**kwargs): kwargs = kwargs.copy() n = kwargs.pop("n", DEFAULT_N_EXAMPLES) batch_size = kwargs.pop("batch_size", DEFAULT_BATCH_SIZE) filepaths = kwargs.pop("filepaths", None) for filepath in filepaths or [DEFAULT_FILEPATH]: buffer = [] batch_idx = 0 if filepaths is not None: kwargs["filepath"] = filepath for i in range(n): buffer.append({"id": i, **kwargs}) if len(buffer) == batch_size: yield f"{filepath}_{batch_idx}", pa.Table.from_pylist(buffer) buffer = [] batch_idx += 1 yield batch_idx, pa.Table.from_pylist(buffer) @pytest.fixture def dataset(): ex_iterable = ExamplesIterable(generate_examples_fn, {}) return IterableDataset(ex_iterable, info=DatasetInfo(description="dummy"), split="train") @pytest.fixture def dataset_with_several_columns(): ex_iterable = ExamplesIterable( generate_examples_fn, {"filepath": ["data0.txt", "data1.txt", "data2.txt"], "metadata": {"sources": ["https://foo.bar"]}}, ) return IterableDataset(ex_iterable, info=DatasetInfo(description="dummy"), split="train") @pytest.fixture def arrow_file(tmp_path_factory, dataset: IterableDataset): filename = str(tmp_path_factory.mktemp("data") / "file.arrow") Dataset.from_generator(dataset.__iter__).map(cache_file_name=filename) return filename ################################ # # Utilities tests # ################################ @pytest.mark.parametrize("batch_size", [1, 2, 3, 9, 10, 11, 20]) @pytest.mark.parametrize("drop_last_batch", [False, True]) def test_convert_to_arrow(batch_size, drop_last_batch): examples = [{"foo": i} for i in range(10)] full_table = pa.Table.from_pylist(examples) num_rows = len(full_table) if not drop_last_batch else len(full_table) // batch_size * batch_size num_batches = (num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size subtables = list( _convert_to_arrow( [(i, example) for i, example in enumerate(examples)], batch_size=batch_size, drop_last_batch=drop_last_batch, ) ) assert len(subtables) == num_batches if drop_last_batch: assert all(len(subtable) == batch_size for _, subtable in subtables) else: assert all(len(subtable) == batch_size for _, subtable in subtables[:-1]) assert len(subtables[-1][1]) <= batch_size if num_rows > 0: reloaded = pa.concat_tables([subtable for _, subtable in subtables]) assert full_table.slice(0, num_rows).to_pydict() == reloaded.to_pydict() @pytest.mark.parametrize( "tables", [ [pa.table({"foo": range(10)})], [pa.table({"foo": range(0, 5)}), pa.table({"foo": range(5, 10)})], [pa.table({"foo": [i]}) for i in range(10)], ], ) @pytest.mark.parametrize("batch_size", [1, 2, 3, 9, 10, 11, 20]) @pytest.mark.parametrize("drop_last_batch", [False, True]) def test_batch_arrow_tables(tables, batch_size, drop_last_batch): full_table = pa.concat_tables(tables) num_rows = len(full_table) if not drop_last_batch else len(full_table) // batch_size * batch_size num_batches = (num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size subtables = list( _batch_arrow_tables( [(i, table) for i, table in enumerate(tables)], batch_size=batch_size, drop_last_batch=drop_last_batch ) ) assert len(subtables) == num_batches if drop_last_batch: assert all(len(subtable) == batch_size for _, subtable in subtables) else: assert all(len(subtable) == batch_size for _, subtable in subtables[:-1]) assert len(subtables[-1][1]) <= batch_size if num_rows > 0: reloaded = pa.concat_tables([subtable for _, subtable in subtables]) assert full_table.slice(0, num_rows).to_pydict() == reloaded.to_pydict() ################################ # # _BaseExampleIterable tests # ################################ def test_examples_iterable(): ex_iterable = ExamplesIterable(generate_examples_fn, {}) expected = list(generate_examples_fn()) assert next(iter(ex_iterable)) == expected[0] assert list(ex_iterable) == expected assert ex_iterable.iter_arrow is None def test_examples_iterable_with_kwargs(): ex_iterable = ExamplesIterable(generate_examples_fn, {"filepaths": ["0.txt", "1.txt"], "split": "train"}) expected = list(generate_examples_fn(filepaths=["0.txt", "1.txt"], split="train")) assert list(ex_iterable) == expected assert all("split" in ex for _, ex in ex_iterable) assert sorted({ex["filepath"] for _, ex in ex_iterable}) == ["0.txt", "1.txt"] def test_examples_iterable_shuffle_data_sources(): ex_iterable = ExamplesIterable(generate_examples_fn, {"filepaths": ["0.txt", "1.txt"]}) ex_iterable = ex_iterable.shuffle_data_sources(np.random.default_rng(40)) expected = list(generate_examples_fn(filepaths=["1.txt", "0.txt"])) # shuffle the filepaths assert list(ex_iterable) == expected def test_examples_iterable_shuffle_shards_and_metadata(): def gen(filepaths, all_metadata): for i, (filepath, metadata) in enumerate(zip(filepaths, all_metadata)): yield i, {"filepath": filepath, "metadata": metadata} ex_iterable = ExamplesIterable( gen, { "filepaths": [f"{i}.txt" for i in range(100)], "all_metadata": [{"id": str(i)} for i in range(100)], }, ) ex_iterable = ex_iterable.shuffle_data_sources(np.random.default_rng(42)) out = list(ex_iterable) filepaths_ids = [x["filepath"].split(".")[0] for _, x in out] metadata_ids = [x["metadata"]["id"] for _, x in out] assert filepaths_ids == metadata_ids, "entangled lists of shards/metadata should be shuffled the same way" def test_arrow_examples_iterable(): ex_iterable = ArrowExamplesIterable(generate_tables_fn, {}) expected = sum([pa_table.to_pylist() for _, pa_table in generate_tables_fn()], []) assert next(iter(ex_iterable))[1] == expected[0] assert [example for _, example in ex_iterable] == expected expected = list(generate_tables_fn()) assert list(ex_iterable.iter_arrow()) == expected def test_arrow_examples_iterable_with_kwargs(): ex_iterable = ArrowExamplesIterable(generate_tables_fn, {"filepaths": ["0.txt", "1.txt"], "split": "train"}) expected = sum( [pa_table.to_pylist() for _, pa_table in generate_tables_fn(filepaths=["0.txt", "1.txt"], split="train")], [] ) assert [example for _, example in ex_iterable] == expected assert all("split" in ex for _, ex in ex_iterable) assert sorted({ex["filepath"] for _, ex in ex_iterable}) == ["0.txt", "1.txt"] expected = list(generate_tables_fn(filepaths=["0.txt", "1.txt"], split="train")) assert list(ex_iterable.iter_arrow()) == expected def test_arrow_examples_iterable_shuffle_data_sources(): ex_iterable = ArrowExamplesIterable(generate_tables_fn, {"filepaths": ["0.txt", "1.txt"]}) ex_iterable = ex_iterable.shuffle_data_sources(np.random.default_rng(40)) expected = sum( [pa_table.to_pylist() for _, pa_table in generate_tables_fn(filepaths=["1.txt", "0.txt"])], [] ) # shuffle the filepaths assert [example for _, example in ex_iterable] == expected expected = list(generate_tables_fn(filepaths=["1.txt", "0.txt"])) assert list(ex_iterable.iter_arrow()) == expected @pytest.mark.parametrize("seed", [42, 1337, 101010, 123456]) def test_buffer_shuffled_examples_iterable(seed): n, buffer_size = 100, 30 generator = np.random.default_rng(seed) base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n}) ex_iterable = BufferShuffledExamplesIterable(base_ex_iterable, buffer_size=buffer_size, generator=generator) rng = deepcopy(generator) expected_indices_used_for_shuffling = list( islice(BufferShuffledExamplesIterable._iter_random_indices(rng, buffer_size=buffer_size), n - buffer_size) ) # indices to pick in the shuffle buffer should all be in the right range assert all(0 <= index_to_pick < buffer_size for index_to_pick in expected_indices_used_for_shuffling) # it should be random indices assert expected_indices_used_for_shuffling != list(range(buffer_size)) # The final order of examples is the result of a shuffle buffer. all_examples = list(generate_examples_fn(n=n)) # We create a buffer and we pick random examples from it. buffer, rest = all_examples[:buffer_size], all_examples[buffer_size:] expected = [] for i, index_to_pick in enumerate(expected_indices_used_for_shuffling): expected.append(buffer[index_to_pick]) # The picked examples are directly replaced by the next examples from the iterable. buffer[index_to_pick] = rest.pop(0) # Once we have reached the end of the iterable, we shuffle the buffer and return the remaining examples. rng.shuffle(buffer) expected += buffer assert next(iter(ex_iterable)) == expected[0] assert list(ex_iterable) == expected assert sorted(ex_iterable) == sorted(all_examples) def test_cycling_multi_sources_examples_iterable(): ex_iterable1 = ExamplesIterable(generate_examples_fn, {"text": "foo"}) ex_iterable2 = ExamplesIterable(generate_examples_fn, {"text": "bar"}) ex_iterable = CyclingMultiSourcesExamplesIterable([ex_iterable1, ex_iterable2]) expected = list(chain(*zip(generate_examples_fn(text="foo"), generate_examples_fn(text="bar")))) # The cycling stops as soon as one iterable is out of examples (here ex_iterable1), so the last sample from ex_iterable2 is unecessary expected = expected[:-1] assert next(iter(ex_iterable)) == expected[0] assert list(ex_iterable) == expected assert all((x["id"], x["text"]) == (i // 2, "bar" if i % 2 else "foo") for i, (_, x) in enumerate(ex_iterable)) @pytest.mark.parametrize("probabilities", [None, (0.5, 0.5), (0.9, 0.1)]) def test_randomly_cycling_multi_sources_examples_iterable(probabilities): seed = 42 generator = np.random.default_rng(seed) ex_iterable1 = ExamplesIterable(generate_examples_fn, {"text": "foo"}) ex_iterable2 = ExamplesIterable(generate_examples_fn, {"text": "bar"}) ex_iterable = RandomlyCyclingMultiSourcesExamplesIterable( [ex_iterable1, ex_iterable2], generator=generator, probabilities=probabilities ) # The source used randomly changes at each example. It stops when one of the iterators is empty. rng = deepcopy(generator) iterators = (generate_examples_fn(text="foo"), generate_examples_fn(text="bar")) indices_iterator = RandomlyCyclingMultiSourcesExamplesIterable._iter_random_indices( rng, len(iterators), p=probabilities ) expected = [] lengths = [len(list(ex_iterable1)), len(list(ex_iterable2))] for i in indices_iterator: if lengths[0] == 0 or lengths[1] == 0: break for key, example in iterators[i]: expected.append((key, example)) lengths[i] -= 1 break else: break assert next(iter(ex_iterable)) == expected[0] assert list(ex_iterable) == expected @pytest.mark.parametrize( "n, func, batched, batch_size", [ (3, lambda x: {"id+1": x["id"] + 1}, False, None), # just add 1 to the id (3, lambda x: {"id+1": [x["id"][0] + 1]}, True, 1), # same with bs=1 (5, lambda x: {"id+1": [i + 1 for i in x["id"]]}, True, 10), # same with bs=10 (25, lambda x: {"id+1": [i + 1 for i in x["id"]]}, True, 10), # same with bs=10 (5, lambda x: {"id+1": [i + 1 for i in x["id"]]}, True, None), # same with bs=None (5, lambda x: {"id+1": [i + 1 for i in x["id"]]}, True, -1), # same with bs<=0 (3, lambda x: {k: v * 2 for k, v in x.items()}, True, 1), # make a duplicate of each example ], ) def test_mapped_examples_iterable(n, func, batched, batch_size): base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n}) ex_iterable = MappedExamplesIterable(base_ex_iterable, func, batched=batched, batch_size=batch_size) all_examples = [x for _, x in generate_examples_fn(n=n)] if batched is False: expected = [{**x, **func(x)} for x in all_examples] else: # For batched map we have to format the examples as a batch (i.e. in one single dictionary) to pass the batch to the function all_transformed_examples = [] # If batch_size is None or <=0, we use the whole dataset as a single batch if batch_size is None or batch_size <= 0: batch_size = len(all_examples) for batch_offset in range(0, len(all_examples), batch_size): examples = all_examples[batch_offset : batch_offset + batch_size] batch = _examples_to_batch(examples) transformed_batch = func(batch) all_transformed_examples.extend(_batch_to_examples(transformed_batch)) expected = _examples_to_batch(all_examples) expected.update(_examples_to_batch(all_transformed_examples)) expected = list(_batch_to_examples(expected)) assert next(iter(ex_iterable))[1] == expected[0] assert [x for _, x in ex_iterable] == expected @pytest.mark.parametrize( "n, func, batched, batch_size", [ (3, lambda x: {"id+1": x["id"] + 1}, False, None), # just add 1 to the id (3, lambda x: {"id+1": [x["id"][0] + 1]}, True, 1), # same with bs=1 (5, lambda x: {"id+1": [i + 1 for i in x["id"]]}, True, 10), # same with bs=10 (25, lambda x: {"id+1": [i + 1 for i in x["id"]]}, True, 10), # same with bs=10 (5, lambda x: {"id+1": [i + 1 for i in x["id"]]}, True, None), # same with bs=None (5, lambda x: {"id+1": [i + 1 for i in x["id"]]}, True, -1), # same with bs<=0 (3, lambda x: {k: v * 2 for k, v in x.items()}, True, 1), # make a duplicate of each example ], ) def test_mapped_examples_iterable_drop_last_batch(n, func, batched, batch_size): base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n}) ex_iterable = MappedExamplesIterable( base_ex_iterable, func, batched=batched, batch_size=batch_size, drop_last_batch=True ) all_examples = [x for _, x in generate_examples_fn(n=n)] is_empty = False if batched is False: # `drop_last_batch` has no effect here expected = [{**x, **func(x)} for x in all_examples] else: # For batched map we have to format the examples as a batch (i.e. in one single dictionary) to pass the batch to the function all_transformed_examples = [] # If batch_size is None or <=0, we use the whole dataset as a single batch if batch_size is None or batch_size <= 0: batch_size = len(all_examples) for batch_offset in range(0, len(all_examples), batch_size): examples = all_examples[batch_offset : batch_offset + batch_size] if len(examples) < batch_size: # ignore last batch break batch = _examples_to_batch(examples) transformed_batch = func(batch) all_transformed_examples.extend(_batch_to_examples(transformed_batch)) all_examples = all_examples if n % batch_size == 0 else all_examples[: n // batch_size * batch_size] if all_examples: expected = _examples_to_batch(all_examples) expected.update(_examples_to_batch(all_transformed_examples)) expected = list(_batch_to_examples(expected)) else: is_empty = True if not is_empty: assert next(iter(ex_iterable))[1] == expected[0] assert [x for _, x in ex_iterable] == expected else: with pytest.raises(StopIteration): next(iter(ex_iterable)) @pytest.mark.parametrize( "n, func, batched, batch_size", [ (3, lambda x, index: {"id+idx": x["id"] + index}, False, None), # add the index to the id ( 25, lambda x, indices: {"id+idx": [i + j for i, j in zip(x["id"], indices)]}, True, 10, ), # add the index to the id (5, lambda x, indices: {"id+idx": [i + j for i, j in zip(x["id"], indices)]}, True, None), # same with bs=None (5, lambda x, indices: {"id+idx": [i + j for i, j in zip(x["id"], indices)]}, True, -1), # same with bs<=0 ], ) def test_mapped_examples_iterable_with_indices(n, func, batched, batch_size): base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n}) ex_iterable = MappedExamplesIterable( base_ex_iterable, func, batched=batched, batch_size=batch_size, with_indices=True ) all_examples = [x for _, x in generate_examples_fn(n=n)] if batched is False: expected = [{**x, **func(x, idx)} for idx, x in enumerate(all_examples)] else: # For batched map we have to format the examples as a batch (i.e. in one single dictionary) to pass the batch to the function all_transformed_examples = [] # If batch_size is None or <=0, we use the whole dataset as a single batch if batch_size is None or batch_size <= 0: batch_size = len(all_examples) for batch_offset in range(0, len(all_examples), batch_size): examples = all_examples[batch_offset : batch_offset + batch_size] batch = _examples_to_batch(examples) indices = list(range(batch_offset, batch_offset + len(examples))) transformed_batch = func(batch, indices) all_transformed_examples.extend(_batch_to_examples(transformed_batch)) expected = _examples_to_batch(all_examples) expected.update(_examples_to_batch(all_transformed_examples)) expected = list(_batch_to_examples(expected)) assert next(iter(ex_iterable))[1] == expected[0] assert [x for _, x in ex_iterable] == expected @pytest.mark.parametrize( "n, func, batched, batch_size, remove_columns", [ (3, lambda x: {"id+1": x["id"] + 1}, False, None, ["extra_column"]), # just add 1 to the id (25, lambda x: {"id+1": [i + 1 for i in x["id"]]}, True, 10, ["extra_column"]), # same with bs=10 ( 50, lambda x: {"foo": ["bar"] * np.random.default_rng(x["id"][0]).integers(0, 10)}, True, 8, ["extra_column", "id"], ), # make a duplicate of each example (5, lambda x: {"id+1": [i + 1 for i in x["id"]]}, True, None, ["extra_column"]), # same with bs=None (5, lambda x: {"id+1": [i + 1 for i in x["id"]]}, True, -1, ["extra_column"]), # same with bs<=0 ], ) def test_mapped_examples_iterable_remove_columns(n, func, batched, batch_size, remove_columns): base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n, "extra_column": "foo"}) ex_iterable = MappedExamplesIterable( base_ex_iterable, func, batched=batched, batch_size=batch_size, remove_columns=remove_columns ) all_examples = [x for _, x in generate_examples_fn(n=n)] columns_to_remove = remove_columns if isinstance(remove_columns, list) else [remove_columns] if batched is False: expected = [{**{k: v for k, v in x.items() if k not in columns_to_remove}, **func(x)} for x in all_examples] else: # For batched map we have to format the examples as a batch (i.e. in one single dictionary) to pass the batch to the function all_transformed_examples = [] # If batch_size is None or <=0, we use the whole dataset as a single batch if batch_size is None or batch_size <= 0: batch_size = len(all_examples) for batch_offset in range(0, len(all_examples), batch_size): examples = all_examples[batch_offset : batch_offset + batch_size] batch = _examples_to_batch(examples) transformed_batch = func(batch) all_transformed_examples.extend(_batch_to_examples(transformed_batch)) expected = {k: v for k, v in _examples_to_batch(all_examples).items() if k not in columns_to_remove} expected.update(_examples_to_batch(all_transformed_examples)) expected = list(_batch_to_examples(expected)) assert next(iter(ex_iterable))[1] == expected[0] assert [x for _, x in ex_iterable] == expected @pytest.mark.parametrize( "n, func, batched, batch_size, fn_kwargs", [ (3, lambda x, y=0: {"id+y": x["id"] + y}, False, None, None), (3, lambda x, y=0: {"id+y": x["id"] + y}, False, None, {"y": 3}), (25, lambda x, y=0: {"id+y": [i + y for i in x["id"]]}, True, 10, {"y": 3}), (5, lambda x, y=0: {"id+y": [i + y for i in x["id"]]}, True, None, {"y": 3}), # same with bs=None (5, lambda x, y=0: {"id+y": [i + y for i in x["id"]]}, True, -1, {"y": 3}), # same with bs<=0 ], ) def test_mapped_examples_iterable_fn_kwargs(n, func, batched, batch_size, fn_kwargs): base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n}) ex_iterable = MappedExamplesIterable( base_ex_iterable, func, batched=batched, batch_size=batch_size, fn_kwargs=fn_kwargs ) all_examples = [x for _, x in generate_examples_fn(n=n)] if fn_kwargs is None: fn_kwargs = {} if batched is False: expected = [{**x, **func(x, **fn_kwargs)} for x in all_examples] else: # For batched map we have to format the examples as a batch (i.e. in one single dictionary) to pass the batch to the function all_transformed_examples = [] # If batch_size is None or <=0, we use the whole dataset as a single batch if batch_size is None or batch_size <= 0: batch_size = len(all_examples) for batch_offset in range(0, len(all_examples), batch_size): examples = all_examples[batch_offset : batch_offset + batch_size] batch = _examples_to_batch(examples) transformed_batch = func(batch, **fn_kwargs) all_transformed_examples.extend(_batch_to_examples(transformed_batch)) expected = _examples_to_batch(all_examples) expected.update(_examples_to_batch(all_transformed_examples)) expected = list(_batch_to_examples(expected)) assert next(iter(ex_iterable))[1] == expected[0] assert [x for _, x in ex_iterable] == expected @pytest.mark.parametrize( "n, func, batched, batch_size, input_columns", [ (3, lambda id_: {"id+1": id_ + 1}, False, None, ["id"]), # just add 1 to the id (25, lambda ids_: {"id+1": [i + 1 for i in ids_]}, True, 10, ["id"]), # same with bs=10 (5, lambda ids_: {"id+1": [i + 1 for i in ids_]}, True, None, ["id"]), # same with bs=None (5, lambda ids_: {"id+1": [i + 1 for i in ids_]}, True, -1, ["id"]), # same with bs<=0 ], ) def test_mapped_examples_iterable_input_columns(n, func, batched, batch_size, input_columns): base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n}) ex_iterable = MappedExamplesIterable( base_ex_iterable, func, batched=batched, batch_size=batch_size, input_columns=input_columns ) all_examples = [x for _, x in generate_examples_fn(n=n)] columns_to_input = input_columns if isinstance(input_columns, list) else [input_columns] if batched is False: expected = [{**x, **func(*[x[col] for col in columns_to_input])} for x in all_examples] else: # For batched map we have to format the examples as a batch (i.e. in one single dictionary) to pass the batch to the function all_transformed_examples = [] # If batch_size is None or <=0, we use the whole dataset as a single batch if batch_size is None or batch_size <= 0: batch_size = len(all_examples) for batch_offset in range(0, len(all_examples), batch_size): examples = all_examples[batch_offset : batch_offset + batch_size] batch = _examples_to_batch(examples) transformed_batch = func(*[batch[col] for col in columns_to_input]) all_transformed_examples.extend(_batch_to_examples(transformed_batch)) expected = _examples_to_batch(all_examples) expected.update(_examples_to_batch(all_transformed_examples)) expected = list(_batch_to_examples(expected)) assert next(iter(ex_iterable))[1] == expected[0] assert [x for _, x in ex_iterable] == expected @pytest.mark.parametrize( "n, func, batched, batch_size", [ (3, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), False, None), # just add 1 to the id (3, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), True, 1), # same with bs=1 (5, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), True, 10), # same with bs=10 (25, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), True, 10), # same with bs=10 (5, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), True, None), # same with bs=None (5, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), True, -1), # same with bs<=0 (3, lambda t: pa.concat_tables([t] * 2), True, 1), # make a duplicate of each example ], ) def test_mapped_examples_iterable_arrow_format(n, func, batched, batch_size): base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n}) ex_iterable = MappedExamplesIterable( base_ex_iterable, func, batched=batched, batch_size=batch_size, formatting=FormattingConfig(format_type="arrow"), ) all_examples = [x for _, x in generate_examples_fn(n=n)] if batched is False: expected = [func(pa.Table.from_pylist([x])).to_pylist()[0] for x in all_examples] else: expected = [] # If batch_size is None or <=0, we use the whole dataset as a single batch if batch_size is None or batch_size <= 0: batch_size = len(all_examples) for batch_offset in range(0, len(all_examples), batch_size): examples = all_examples[batch_offset : batch_offset + batch_size] batch = pa.Table.from_pylist(examples) expected.extend(func(batch).to_pylist()) assert next(iter(ex_iterable))[1] == expected[0] assert [x for _, x in ex_iterable] == expected @pytest.mark.parametrize( "n, func, batched, batch_size", [ (3, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), False, None), # just add 1 to the id (3, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), True, 1), # same with bs=1 (5, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), True, 10), # same with bs=10 (25, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), True, 10), # same with bs=10 (5, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), True, None), # same with bs=None (5, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), True, -1), # same with bs<=0 (3, lambda t: pa.concat_tables([t] * 2), True, 1), # make a duplicate of each example ], ) def test_mapped_examples_iterable_drop_last_batch_and_arrow_format(n, func, batched, batch_size): base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n}) ex_iterable = MappedExamplesIterable( base_ex_iterable, func, batched=batched, batch_size=batch_size, drop_last_batch=True, formatting=FormattingConfig(format_type="arrow"), ) all_examples = [x for _, x in generate_examples_fn(n=n)] is_empty = False if batched is False: # `drop_last_batch` has no effect here expected = [func(pa.Table.from_pylist([x])).to_pylist()[0] for x in all_examples] else: all_transformed_examples = [] # If batch_size is None or <=0, we use the whole dataset as a single batch if batch_size is None or batch_size <= 0: batch_size = len(all_examples) for batch_offset in range(0, len(all_examples), batch_size): examples = all_examples[batch_offset : batch_offset + batch_size] if len(examples) < batch_size: # ignore last batch break batch = pa.Table.from_pylist(examples) out = func(batch) all_transformed_examples.extend( out.to_pylist() ) # we don't merge with input since they're arrow tables and not dictionaries all_examples = all_examples if n % batch_size == 0 else all_examples[: n // batch_size * batch_size] if all_examples: expected = all_transformed_examples else: is_empty = True if not is_empty: assert next(iter(ex_iterable))[1] == expected[0] assert [x for _, x in ex_iterable] == expected else: with pytest.raises(StopIteration): next(iter(ex_iterable)) @pytest.mark.parametrize( "n, func, batched, batch_size", [ ( 3, lambda t, index: t.append_column("id+idx", pc.add(t["id"], index)), False, None, ), # add the index to the id ( 25, lambda t, indices: t.append_column("id+idx", pc.add(t["id"], indices)), True, 10, ), # add the index to the id (5, lambda t, indices: t.append_column("id+idx", pc.add(t["id"], indices)), True, None), # same with bs=None (5, lambda t, indices: t.append_column("id+idx", pc.add(t["id"], indices)), True, -1), # same with bs<=0 ], ) def test_mapped_examples_iterable_with_indices_and_arrow_format(n, func, batched, batch_size): base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n}) ex_iterable = MappedExamplesIterable( base_ex_iterable, func, batched=batched, batch_size=batch_size, with_indices=True, formatting=FormattingConfig(format_type="arrow"), ) all_examples = [x for _, x in generate_examples_fn(n=n)] if batched is False: expected = [func(pa.Table.from_pylist([x]), i).to_pylist()[0] for i, x in enumerate(all_examples)] else: expected = [] # If batch_size is None or <=0, we use the whole dataset as a single batch if batch_size is None or batch_size <= 0: batch_size = len(all_examples) for batch_offset in range(0, len(all_examples), batch_size): examples = all_examples[batch_offset : batch_offset + batch_size] batch = pa.Table.from_pylist(examples) expected.extend(func(batch, list(range(batch_offset, batch_offset + len(batch)))).to_pylist()) assert next(iter(ex_iterable))[1] == expected[0] assert [x for _, x in ex_iterable] == expected @pytest.mark.parametrize( "n, func, batched, batch_size, remove_columns", [ ( 3, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), False, None, ["extra_column"], ), # just add 1 to the id (25, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), True, 10, ["extra_column"]), # same with bs=10 ( 50, lambda t: pa.table({"foo": ["bar"] * np.random.default_rng(t["id"][0].as_py()).integers(0, 10)}), True, 8, ["extra_column", "id"], ), # make a duplicate of each example (5, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), True, None, ["extra_column"]), # same with bs=None (5, lambda t: t.append_column("id+1", pc.add(t["id"], 1)), True, -1, ["extra_column"]), # same with bs<=0 ], ) def test_mapped_examples_iterable_remove_columns_arrow_format(n, func, batched, batch_size, remove_columns): base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n, "extra_column": "foo"}) ex_iterable = MappedExamplesIterable( base_ex_iterable, func, batched=batched, batch_size=batch_size, remove_columns=remove_columns, formatting=FormattingConfig(format_type="arrow"), ) all_examples = [x for _, x in generate_examples_fn(n=n)] columns_to_remove = remove_columns if isinstance(remove_columns, list) else [remove_columns] if batched is False: expected = [ {**{k: v for k, v in func(pa.Table.from_pylist([x])).to_pylist()[0].items() if k not in columns_to_remove}} for x in all_examples ] else: expected = [] # If batch_size is None or <=0, we use the whole dataset as a single batch if batch_size is None or batch_size <= 0: batch_size = len(all_examples) for batch_offset in range(0, len(all_examples), batch_size): examples = all_examples[batch_offset : batch_offset + batch_size] batch = pa.Table.from_pylist(examples) expected.extend( [{k: v for k, v in x.items() if k not in columns_to_remove} for x in func(batch).to_pylist()] ) assert next(iter(ex_iterable))[1] == expected[0] assert [x for _, x in ex_iterable] == expected @pytest.mark.parametrize( "n, func, batched, batch_size, fn_kwargs", [ (3, lambda t, y=0: t.append_column("id+idx", pc.add(t["id"], y)), False, None, None), (3, lambda t, y=0: t.append_column("id+idx", pc.add(t["id"], y)), False, None, {"y": 3}), (25, lambda t, y=0: t.append_column("id+idx", pc.add(t["id"], y)), True, 10, {"y": 3}), (5, lambda t, y=0: t.append_column("id+idx", pc.add(t["id"], y)), True, None, {"y": 3}), # same with bs=None (5, lambda t, y=0: t.append_column("id+idx", pc.add(t["id"], y)), True, -1, {"y": 3}), # same with bs<=0 ], ) def test_mapped_examples_iterable_fn_kwargs_and_arrow_format(n, func, batched, batch_size, fn_kwargs): base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n}) ex_iterable = MappedExamplesIterable( base_ex_iterable, func, batched=batched, batch_size=batch_size, fn_kwargs=fn_kwargs, formatting=FormattingConfig(format_type="arrow"), ) all_examples = [x for _, x in generate_examples_fn(n=n)] if fn_kwargs is None: fn_kwargs = {} if batched is False: expected = [func(pa.Table.from_pylist([x]), **fn_kwargs).to_pylist()[0] for x in all_examples] else: expected = [] # If batch_size is None or <=0, we use the whole dataset as a single batch if batch_size is None or batch_size <= 0: batch_size = len(all_examples) for batch_offset in range(0, len(all_examples), batch_size): examples = all_examples[batch_offset : batch_offset + batch_size] batch = pa.Table.from_pylist(examples) expected.extend(func(batch, **fn_kwargs).to_pylist()) assert next(iter(ex_iterable))[1] == expected[0] assert [x for _, x in ex_iterable] == expected @pytest.mark.parametrize( "n, func, batched, batch_size, input_columns", [ (3, lambda id_: pa.table({"id+1": pc.add(id_, 1)}), False, None, ["id"]), # just add 1 to the id (25, lambda ids_: pa.table({"id+1": pc.add(ids_, 1)}), True, 10, ["id"]), # same with bs=10 (5, lambda ids_: pa.table({"id+1": pc.add(ids_, 1)}), True, None, ["id"]), # same with bs=None (5, lambda ids_: pa.table({"id+1": pc.add(ids_, 1)}), True, -1, ["id"]), # same with bs<=0 ], ) def test_mapped_examples_iterable_input_columns_and_arrow_format(n, func, batched, batch_size, input_columns): base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n}) ex_iterable = MappedExamplesIterable( base_ex_iterable, func, batched=batched, batch_size=batch_size, input_columns=input_columns, formatting=FormattingConfig(format_type="arrow"), ) all_examples = [x for _, x in generate_examples_fn(n=n)] columns_to_input = input_columns if isinstance(input_columns, list) else [input_columns] if batched is False: expected = [ func(*[pa.Table.from_pylist([x])[col] for col in columns_to_input]).to_pylist()[0] for x in all_examples ] else: expected = [] # If batch_size is None or <=0, we use the whole dataset as a single batch if batch_size is None or batch_size <= 0: batch_size = len(all_examples) for batch_offset in range(0, len(all_examples), batch_size): examples = all_examples[batch_offset : batch_offset + batch_size] batch = pa.Table.from_pylist(examples) expected.extend(func(*[batch[col] for col in columns_to_input]).to_pylist()) assert next(iter(ex_iterable))[1] == expected[0] assert [x for _, x in ex_iterable] == expected @pytest.mark.parametrize( "n, func, batched, batch_size", [ (3, lambda x: x["id"] % 2 == 0, False, None), # keep even number (3, lambda x: [x["id"][0] % 2 == 0], True, 1), # same with bs=1 (25, lambda x: [i % 2 == 0 for i in x["id"]], True, 10), # same with bs=10 (5, lambda x: [i % 2 == 0 for i in x["id"]], True, None), # same with bs=None (5, lambda x: [i % 2 == 0 for i in x["id"]], True, -1), # same with bs<=0 (3, lambda x: False, False, None), # return 0 examples (3, lambda x: [False] * len(x["id"]), True, 10), # same with bs=10 ], ) def test_filtered_examples_iterable(n, func, batched, batch_size): base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n}) ex_iterable = FilteredExamplesIterable(base_ex_iterable, func, batched=batched, batch_size=batch_size) all_examples = [x for _, x in generate_examples_fn(n=n)] if batched is False: expected = [x for x in all_examples if func(x)] else: # For batched filter we have to format the examples as a batch (i.e. in one single dictionary) to pass the batch to the function expected = [] # If batch_size is None or <=0, we use the whole dataset as a single batch if batch_size is None or batch_size <= 0: batch_size = len(all_examples) for batch_offset in range(0, len(all_examples), batch_size): examples = all_examples[batch_offset : batch_offset + batch_size] batch = _examples_to_batch(examples) mask = func(batch) expected.extend([x for x, to_keep in zip(examples, mask) if to_keep]) if expected: assert next(iter(ex_iterable))[1] == expected[0] assert [x for _, x in ex_iterable] == expected @pytest.mark.parametrize( "n, func, batched, batch_size", [ (3, lambda x, index: index % 2 == 0, False, None), # keep even number (25, lambda x, indices: [idx % 2 == 0 for idx in indices], True, 10), # same with bs=10 (5, lambda x, indices: [idx % 2 == 0 for idx in indices], True, None), # same with bs=None (5, lambda x, indices: [idx % 2 == 0 for idx in indices], True, -1), # same with bs<=0 ], ) def test_filtered_examples_iterable_with_indices(n, func, batched, batch_size): base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n}) ex_iterable = FilteredExamplesIterable( base_ex_iterable, func, batched=batched, batch_size=batch_size, with_indices=True ) all_examples = [x for _, x in generate_examples_fn(n=n)] if batched is False: expected = [x for idx, x in enumerate(all_examples) if func(x, idx)] else: # For batched filter we have to format the examples as a batch (i.e. in one single dictionary) to pass the batch to the function expected = [] # If batch_size is None or <=0, we use the whole dataset as a single batch if batch_size is None or batch_size <= 0: batch_size = len(all_examples) for batch_offset in range(0, len(all_examples), batch_size): examples = all_examples[batch_offset : batch_offset + batch_size] batch = _examples_to_batch(examples) indices = list(range(batch_offset, batch_offset + len(examples))) mask = func(batch, indices) expected.extend([x for x, to_keep in zip(examples, mask) if to_keep]) assert next(iter(ex_iterable))[1] == expected[0] assert [x for _, x in ex_iterable] == expected @pytest.mark.parametrize( "n, func, batched, batch_size, input_columns", [ (3, lambda id_: id_ % 2 == 0, False, None, ["id"]), # keep even number (25, lambda ids_: [i % 2 == 0 for i in ids_], True, 10, ["id"]), # same with bs=10 (3, lambda ids_: [i % 2 == 0 for i in ids_], True, None, ["id"]), # same with bs=None (3, lambda ids_: [i % 2 == 0 for i in ids_], True, None, ["id"]), # same with bs=None ], ) def test_filtered_examples_iterable_input_columns(n, func, batched, batch_size, input_columns): base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n}) ex_iterable = FilteredExamplesIterable( base_ex_iterable, func, batched=batched, batch_size=batch_size, input_columns=input_columns ) all_examples = [x for _, x in generate_examples_fn(n=n)] columns_to_input = input_columns if isinstance(input_columns, list) else [input_columns] if batched is False: expected = [x for x in all_examples if func(*[x[col] for col in columns_to_input])] else: # For batched filter we have to format the examples as a batch (i.e. in one single dictionary) to pass the batch to the function expected = [] # If batch_size is None or <=0, we use the whole dataset as a single batch if batch_size is None or batch_size <= 0: batch_size = len(all_examples) for batch_offset in range(0, len(all_examples), batch_size): examples = all_examples[batch_offset : batch_offset + batch_size] batch = _examples_to_batch(examples) mask = func(*[batch[col] for col in columns_to_input]) expected.extend([x for x, to_keep in zip(examples, mask) if to_keep]) assert next(iter(ex_iterable))[1] == expected[0] assert [x for _, x in ex_iterable] == expected def test_skip_examples_iterable(): total, count = 10, 2 base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": total}) skip_ex_iterable = SkipExamplesIterable(base_ex_iterable, n=count) expected = list(generate_examples_fn(n=total))[count:] assert list(skip_ex_iterable) == expected assert ( skip_ex_iterable.shuffle_data_sources(np.random.default_rng(42)) is skip_ex_iterable ), "skip examples makes the shards order fixed" def test_take_examples_iterable(): total, count = 10, 2 base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": total}) take_ex_iterable = TakeExamplesIterable(base_ex_iterable, n=count) expected = list(generate_examples_fn(n=total))[:count] assert list(take_ex_iterable) == expected assert ( take_ex_iterable.shuffle_data_sources(np.random.default_rng(42)) is take_ex_iterable ), "skip examples makes the shards order fixed" def test_vertically_concatenated_examples_iterable(): ex_iterable1 = ExamplesIterable(generate_examples_fn, {"label": 10}) ex_iterable2 = ExamplesIterable(generate_examples_fn, {"label": 5}) concatenated_ex_iterable = VerticallyConcatenatedMultiSourcesExamplesIterable([ex_iterable1, ex_iterable2]) expected = [x for _, x in ex_iterable1] + [x for _, x in ex_iterable2] assert [x for _, x in concatenated_ex_iterable] == expected def test_vertically_concatenated_examples_iterable_with_different_columns(): # having different columns is supported # Though iterable datasets fill the missing data with nulls ex_iterable1 = ExamplesIterable(generate_examples_fn, {"label": 10}) ex_iterable2 = ExamplesIterable(generate_examples_fn, {}) concatenated_ex_iterable = VerticallyConcatenatedMultiSourcesExamplesIterable([ex_iterable1, ex_iterable2]) expected = [x for _, x in ex_iterable1] + [x for _, x in ex_iterable2] assert [x for _, x in concatenated_ex_iterable] == expected def test_vertically_concatenated_examples_iterable_shuffle_data_sources(): ex_iterable1 = ExamplesIterable(generate_examples_fn, {"label": 10}) ex_iterable2 = ExamplesIterable(generate_examples_fn, {"label": 5}) concatenated_ex_iterable = VerticallyConcatenatedMultiSourcesExamplesIterable([ex_iterable1, ex_iterable2]) rng = np.random.default_rng(42) shuffled_ex_iterable = concatenated_ex_iterable.shuffle_data_sources(rng) # make sure the list of examples iterables is shuffled, and each examples iterable is shuffled expected = [x for _, x in ex_iterable2.shuffle_data_sources(rng)] + [ x for _, x in ex_iterable1.shuffle_data_sources(rng) ] assert [x for _, x in shuffled_ex_iterable] == expected def test_horizontally_concatenated_examples_iterable(): ex_iterable1 = ExamplesIterable(generate_examples_fn, {"label1": 10}) ex_iterable2 = ExamplesIterable(generate_examples_fn, {"label2": 5}) concatenated_ex_iterable = HorizontallyConcatenatedMultiSourcesExamplesIterable([ex_iterable1, ex_iterable2]) with pytest.raises(ValueError): # column "id" is duplicated -> raise an error list(concatenated_ex_iterable) ex_iterable2 = MappedExamplesIterable(ex_iterable2, lambda x: x, remove_columns=["id"]) concatenated_ex_iterable = HorizontallyConcatenatedMultiSourcesExamplesIterable([ex_iterable1, ex_iterable2]) expected = [{**x, **y} for (_, x), (_, y) in zip(ex_iterable1, ex_iterable2)] assert [x for _, x in concatenated_ex_iterable] == expected assert ( concatenated_ex_iterable.shuffle_data_sources(np.random.default_rng(42)) is concatenated_ex_iterable ), "horizontally concatenated examples makes the shards order fixed" @pytest.mark.parametrize( "ex_iterable", [ ExamplesIterable(generate_examples_fn, {}), ShuffledDataSourcesExamplesIterable(generate_examples_fn, {}, np.random.default_rng(42)), SelectColumnsIterable(ExamplesIterable(generate_examples_fn, {}), ["id"]), StepExamplesIterable(ExamplesIterable(generate_examples_fn, {}), 2, 0), CyclingMultiSourcesExamplesIterable([ExamplesIterable(generate_examples_fn, {})]), VerticallyConcatenatedMultiSourcesExamplesIterable([ExamplesIterable(generate_examples_fn, {})]), HorizontallyConcatenatedMultiSourcesExamplesIterable([ExamplesIterable(generate_examples_fn, {})]), RandomlyCyclingMultiSourcesExamplesIterable( [ExamplesIterable(generate_examples_fn, {})], np.random.default_rng(42) ), MappedExamplesIterable(ExamplesIterable(generate_examples_fn, {}), lambda x: x), MappedExamplesIterable(ArrowExamplesIterable(generate_tables_fn, {}), lambda x: x), FilteredExamplesIterable(ExamplesIterable(generate_examples_fn, {}), lambda x: True), FilteredExamplesIterable(ArrowExamplesIterable(generate_tables_fn, {}), lambda x: True), BufferShuffledExamplesIterable(ExamplesIterable(generate_examples_fn, {}), 10, np.random.default_rng(42)), SkipExamplesIterable(ExamplesIterable(generate_examples_fn, {}), 10), TakeExamplesIterable(ExamplesIterable(generate_examples_fn, {}), 10), TypedExamplesIterable( ExamplesIterable(generate_examples_fn, {}), Features({"id": Value("int32")}), token_per_repo_id={} ), ], ) def test_no_iter_arrow(ex_iterable: _BaseExamplesIterable): assert ex_iterable.iter_arrow is None @pytest.mark.parametrize( "ex_iterable", [ ArrowExamplesIterable(generate_tables_fn, {}), ShuffledDataSourcesArrowExamplesIterable(generate_tables_fn, {}, np.random.default_rng(42)), SelectColumnsIterable(ArrowExamplesIterable(generate_tables_fn, {}), ["id"]), # StepExamplesIterable(ArrowExamplesIterable(generate_tables_fn, {}), 2, 0), # not implemented # CyclingMultiSourcesExamplesIterable([ArrowExamplesIterable(generate_tables_fn, {})]), # not implemented VerticallyConcatenatedMultiSourcesExamplesIterable([ArrowExamplesIterable(generate_tables_fn, {})]), # HorizontallyConcatenatedMultiSourcesExamplesIterable([ArrowExamplesIterable(generate_tables_fn, {})]), # not implemented # RandomlyCyclingMultiSourcesExamplesIterable([ArrowExamplesIterable(generate_tables_fn, {})], np.random.default_rng(42)), # not implemented MappedExamplesIterable( ExamplesIterable(generate_examples_fn, {}), lambda t: t, formatting=FormattingConfig(format_type="arrow") ), MappedExamplesIterable( ArrowExamplesIterable(generate_tables_fn, {}), lambda t: t, formatting=FormattingConfig(format_type="arrow"), ), FilteredExamplesIterable( ExamplesIterable(generate_examples_fn, {}), lambda t: True, formatting=FormattingConfig(format_type="arrow"), ), FilteredExamplesIterable( ArrowExamplesIterable(generate_tables_fn, {}), lambda t: True, formatting=FormattingConfig(format_type="arrow"), ), # BufferShuffledExamplesIterable(ArrowExamplesIterable(generate_tables_fn, {}), 10, np.random.default_rng(42)), # not implemented # SkipExamplesIterable(ArrowExamplesIterable(generate_tables_fn, {}), 10), # not implemented # TakeExamplesIterable(ArrowExamplesIterable(generate_tables_fn, {}), 10), # not implemented TypedExamplesIterable( ArrowExamplesIterable(generate_tables_fn, {}), Features({"id": Value("int32")}), token_per_repo_id={} ), ], ) def test_iter_arrow(ex_iterable: _BaseExamplesIterable): assert ex_iterable.iter_arrow is not None key, pa_table = next(ex_iterable.iter_arrow()) assert isinstance(pa_table, pa.Table) ############################ # # IterableDataset tests # ############################ def test_iterable_dataset(): dataset = IterableDataset(ExamplesIterable(generate_examples_fn, {})) expected = [x for _, x in generate_examples_fn()] assert next(iter(dataset)) == expected[0] assert list(dataset) == expected def test_iterable_dataset_from_generator(): data = [ {"col_1": "0", "col_2": 0, "col_3": 0.0}, {"col_1": "1", "col_2": 1, "col_3": 1.0}, {"col_1": "2", "col_2": 2, "col_3": 2.0}, {"col_1": "3", "col_2": 3, "col_3": 3.0}, ] def gen(): yield from data dataset = IterableDataset.from_generator(gen) assert isinstance(dataset, IterableDataset) assert list(dataset) == data def test_iterable_dataset_from_generator_with_shards(): def gen(shard_names): for shard_name in shard_names: for i in range(10): yield {"shard_name": shard_name, "i": i} shard_names = [f"data{shard_idx}.txt" for shard_idx in range(4)] dataset = IterableDataset.from_generator(gen, gen_kwargs={"shard_names": shard_names}) assert isinstance(dataset, IterableDataset) assert dataset.n_shards == len(shard_names) def test_iterable_dataset_from_file(dataset: IterableDataset, arrow_file: str): with assert_arrow_memory_doesnt_increase(): dataset_from_file = IterableDataset.from_file(arrow_file) expected_features = dataset._resolve_features().features assert dataset_from_file.features.type == expected_features.type assert dataset_from_file.features == expected_features assert isinstance(dataset_from_file, IterableDataset) assert list(dataset_from_file) == list(dataset) @require_not_windows @require_dill_gt_0_3_2 @require_pyspark def test_from_spark_streaming(): import pyspark spark = pyspark.sql.SparkSession.builder.master("local[*]").appName("pyspark").getOrCreate() data = [ ("0", 0, 0.0), ("1", 1, 1.0), ("2", 2, 2.0), ("3", 3, 3.0), ] df = spark.createDataFrame(data, "col_1: string, col_2: int, col_3: float") dataset = IterableDataset.from_spark(df) assert isinstance(dataset, IterableDataset) results = [] for ex in dataset: results.append(ex) assert results == [ {"col_1": "0", "col_2": 0, "col_3": 0.0}, {"col_1": "1", "col_2": 1, "col_3": 1.0}, {"col_1": "2", "col_2": 2, "col_3": 2.0}, {"col_1": "3", "col_2": 3, "col_3": 3.0}, ] @require_not_windows @require_dill_gt_0_3_2 @require_pyspark def test_from_spark_streaming_features(): import PIL.Image import pyspark spark = pyspark.sql.SparkSession.builder.master("local[*]").appName("pyspark").getOrCreate() data = [(0, np.arange(4 * 4 * 3).reshape(4, 4, 3).tolist())] df = spark.createDataFrame(data, "idx: int, image: array<array<array<int>>>") features = Features({"idx": Value("int64"), "image": Image()}) dataset = IterableDataset.from_spark( df, features=features, ) assert isinstance(dataset, IterableDataset) results = [] for ex in dataset: results.append(ex) assert len(results) == 1 isinstance(results[0]["image"], PIL.Image.Image) @require_torch def test_iterable_dataset_torch_integration(): ex_iterable = ExamplesIterable(generate_examples_fn, {}) dataset = IterableDataset(ex_iterable) import torch.utils.data assert isinstance(dataset, torch.utils.data.IterableDataset) assert isinstance(dataset, IterableDataset) assert dataset._ex_iterable is ex_iterable @require_torch def test_iterable_dataset_torch_picklable(): import pickle ex_iterable = ExamplesIterable(generate_examples_fn, {}) dataset = IterableDataset(ex_iterable, formatting=FormattingConfig(format_type="torch")) reloaded_dataset = pickle.loads(pickle.dumps(dataset)) import torch.utils.data assert isinstance(reloaded_dataset, IterableDataset) assert isinstance(reloaded_dataset, torch.utils.data.IterableDataset) assert reloaded_dataset._formatting.format_type == "torch" assert len(list(dataset)) == len(list(reloaded_dataset)) @require_torch def test_iterable_dataset_with_format_torch(): ex_iterable = ExamplesIterable(generate_examples_fn, {}) dataset = IterableDataset(ex_iterable) from torch.utils.data import DataLoader dataloader = DataLoader(dataset) assert len(list(dataloader)) == len(list(ex_iterable)) @require_torch def test_iterable_dataset_torch_dataloader_parallel(): from torch.utils.data import DataLoader ex_iterable = ExamplesIterable(generate_examples_fn, {}) dataset = IterableDataset(ex_iterable) dataloader = DataLoader(dataset, num_workers=2, batch_size=None) result = list(dataloader) expected = [example for _, example in ex_iterable] assert len(result) == len(expected) assert {str(x) for x in result} == {str(x) for x in expected} @require_torch @pytest.mark.filterwarnings("ignore:This DataLoader will create:UserWarning") @pytest.mark.parametrize("n_shards, num_workers", [(2, 1), (2, 2), (3, 2), (2, 3)]) def test_sharded_iterable_dataset_torch_dataloader_parallel(n_shards, num_workers): from torch.utils.data import DataLoader ex_iterable = ExamplesIterable(generate_examples_fn, {"filepaths": [f"{i}.txt" for i in range(n_shards)]}) dataset = IterableDataset(ex_iterable) dataloader = DataLoader(dataset, batch_size=None, num_workers=num_workers) result = list(dataloader) expected = [example for _, example in ex_iterable] assert len(result) == len(expected) assert {str(x) for x in result} == {str(x) for x in expected} @require_torch @pytest.mark.integration @pytest.mark.parametrize("num_workers", [1, 2]) def test_iterable_dataset_from_hub_torch_dataloader_parallel(num_workers, tmp_path): from torch.utils.data import DataLoader dataset = load_dataset(SAMPLE_DATASET_IDENTIFIER, cache_dir=str(tmp_path), streaming=True, split="train") dataloader = DataLoader(dataset, batch_size=None, num_workers=num_workers) result = list(dataloader) assert len(result) == 2 @pytest.mark.parametrize("batch_size", [4, 5]) @pytest.mark.parametrize("drop_last_batch", [False, True]) def test_iterable_dataset_iter_batch(batch_size, drop_last_batch): n = 25 dataset = IterableDataset(ExamplesIterable(generate_examples_fn, {"n": n})) all_examples = [ex for _, ex in generate_examples_fn(n=n)] expected = [] for i in range(0, len(all_examples), batch_size): if len(all_examples[i : i + batch_size]) < batch_size and drop_last_batch: continue expected.append(_examples_to_batch(all_examples[i : i + batch_size])) assert next(iter(dataset.iter(batch_size, drop_last_batch=drop_last_batch))) == expected[0] assert list(dataset.iter(batch_size, drop_last_batch=drop_last_batch)) == expected def test_iterable_dataset_info(): info = DatasetInfo(description="desc", citation="@article{}", size_in_bytes=42) ex_iterable = ExamplesIterable(generate_examples_fn, {}) dataset = IterableDataset(ex_iterable, info=info) assert dataset.info == info assert dataset.description == info.description assert dataset.citation == info.citation assert dataset.size_in_bytes == info.size_in_bytes def test_iterable_dataset_set_epoch(dataset: IterableDataset): assert dataset._epoch == 0 dataset.set_epoch(42) assert dataset._epoch == 42 @pytest.mark.parametrize("seed", [None, 42, 1337]) @pytest.mark.parametrize("epoch", [None, 0, 1, 10]) def test_iterable_dataset_set_epoch_of_shuffled_dataset(dataset: IterableDataset, seed, epoch): buffer_size = 10 shuffled_dataset = dataset.shuffle(seed, buffer_size=buffer_size) base_generator = shuffled_dataset._shuffling.generator if epoch is not None: shuffled_dataset.set_epoch(epoch) effective_generator = shuffled_dataset._effective_generator() assert effective_generator is not None if epoch is None or epoch == 0: assert is_rng_equal(base_generator, shuffled_dataset._effective_generator()) else: assert not is_rng_equal(base_generator, shuffled_dataset._effective_generator()) effective_seed = deepcopy(base_generator).integers(0, 1 << 63) - epoch assert is_rng_equal(np.random.default_rng(effective_seed), shuffled_dataset._effective_generator()) def test_iterable_dataset_map( dataset: IterableDataset, ): func = lambda x: {"id+1": x["id"] + 1} # noqa: E731 mapped_dataset = dataset.map(func) assert isinstance(mapped_dataset._ex_iterable, MappedExamplesIterable) assert mapped_dataset._ex_iterable.function is func assert mapped_dataset._ex_iterable.batched is False assert next(iter(mapped_dataset)) == {**next(iter(dataset)), **func(next(iter(generate_examples_fn()))[1])} def test_iterable_dataset_map_batched( dataset: IterableDataset, ): func = lambda x: {"id+1": [i + 1 for i in x["id"]]} # noqa: E731 batch_size = 3 dataset = dataset.map(func, batched=True, batch_size=batch_size) assert isinstance(dataset._ex_iterable, MappedExamplesIterable) assert dataset._ex_iterable.function is func assert dataset._ex_iterable.batch_size == batch_size assert next(iter(dataset)) == {"id": 0, "id+1": 1} def test_iterable_dataset_map_complex_features( dataset: IterableDataset, ): # https://github.com/huggingface/datasets/issues/3505 ex_iterable = ExamplesIterable(generate_examples_fn, {"label": "positive"}) features = Features( { "id": Value("int64"), "label": Value("string"), } ) dataset = IterableDataset(ex_iterable, info=DatasetInfo(features=features)) dataset = dataset.cast_column("label", ClassLabel(names=["negative", "positive"])) dataset = dataset.map(lambda x: {"id+1": x["id"] + 1, **x}) assert isinstance(dataset._ex_iterable, MappedExamplesIterable) features["label"] = ClassLabel(names=["negative", "positive"]) assert [{k: v for k, v in ex.items() if k != "id+1"} for ex in dataset] == [ features.encode_example(ex) for _, ex in ex_iterable ] def test_iterable_dataset_map_with_features(dataset: IterableDataset) -> None: # https://github.com/huggingface/datasets/issues/3888 ex_iterable = ExamplesIterable(generate_examples_fn, {"label": "positive"}) features_before_map = Features( { "id": Value("int64"), "label": Value("string"), } ) dataset = IterableDataset(ex_iterable, info=DatasetInfo(features=features_before_map)) assert dataset.info.features is not None assert dataset.info.features == features_before_map features_after_map = Features( { "id": Value("int64"), "label": Value("string"), "target": Value("string"), } ) dataset = dataset.map(lambda x: {"target": x["label"]}, features=features_after_map) assert dataset.info.features is not None assert dataset.info.features == features_after_map def test_iterable_dataset_map_with_fn_kwargs(dataset: IterableDataset) -> None: fn_kwargs = {"y": 1} mapped_dataset = dataset.map(lambda x, y: {"id+y": x["id"] + y}, fn_kwargs=fn_kwargs) assert mapped_dataset._ex_iterable.batched is False assert next(iter(mapped_dataset)) == {"id": 0, "id+y": 1} batch_size = 3 mapped_dataset = dataset.map( lambda x, y: {"id+y": [i + y for i in x["id"]]}, batched=True, batch_size=batch_size, fn_kwargs=fn_kwargs ) assert isinstance(mapped_dataset._ex_iterable, MappedExamplesIterable) assert mapped_dataset._ex_iterable.batch_size == batch_size assert next(iter(mapped_dataset)) == {"id": 0, "id+y": 1} def test_iterable_dataset_filter(dataset: IterableDataset) -> None: fn_kwargs = {"y": 1} filtered_dataset = dataset.filter(lambda x, y: x["id"] == y, fn_kwargs=fn_kwargs) assert filtered_dataset._ex_iterable.batched is False assert next(iter(filtered_dataset)) == {"id": 1} @pytest.mark.parametrize("seed", [42, 1337, 101010, 123456]) @pytest.mark.parametrize("epoch", [None, 0, 1]) def test_iterable_dataset_shuffle(dataset: IterableDataset, seed, epoch): buffer_size = 3 dataset = deepcopy(dataset) dataset._ex_iterable.kwargs["filepaths"] = ["0.txt", "1.txt"] dataset = dataset.shuffle(seed, buffer_size=buffer_size) assert isinstance(dataset._shuffling, ShufflingConfig) assert isinstance(dataset._shuffling.generator, np.random.Generator) assert is_rng_equal(dataset._shuffling.generator, np.random.default_rng(seed)) # Effective seed is sum of seed and epoch if epoch is None or epoch == 0: effective_seed = seed else: dataset.set_epoch(epoch) effective_seed = np.random.default_rng(seed).integers(0, 1 << 63) - epoch # Shuffling adds a shuffle buffer expected_first_example_index = next( iter(BufferShuffledExamplesIterable._iter_random_indices(np.random.default_rng(effective_seed), buffer_size)) ) assert isinstance(dataset._ex_iterable, BufferShuffledExamplesIterable) # It also shuffles the underlying examples iterable expected_ex_iterable = ExamplesIterable( generate_examples_fn, {"filepaths": ["0.txt", "1.txt"]} ).shuffle_data_sources(np.random.default_rng(effective_seed)) assert isinstance(dataset._ex_iterable.ex_iterable, ExamplesIterable) assert next(iter(dataset)) == list(islice(expected_ex_iterable, expected_first_example_index + 1))[-1][1] @pytest.mark.parametrize( "features", [ None, Features( { "id": Value("int64"), "label": Value("int64"), } ), Features( { "id": Value("int64"), "label": ClassLabel(names=["negative", "positive"]), } ), ], ) def test_iterable_dataset_features(features): ex_iterable = ExamplesIterable(generate_examples_fn, {"label": 0}) dataset = IterableDataset(ex_iterable, info=DatasetInfo(features=features)) if features: expected = [features.encode_example(x) for _, x in ex_iterable] else: expected = [x for _, x in ex_iterable] assert list(dataset) == expected def test_iterable_dataset_features_cast_to_python(): ex_iterable = ExamplesIterable( generate_examples_fn, {"timestamp": pd.Timestamp(2020, 1, 1), "array": np.ones(5), "n": 1} ) features = Features( { "id": Value("int64"), "timestamp": Value("timestamp[us]"), "array": [Value("int64")], } ) dataset = IterableDataset(ex_iterable, info=DatasetInfo(features=features)) assert list(dataset) == [{"timestamp": pd.Timestamp(2020, 1, 1).to_pydatetime(), "array": [1] * 5, "id": 0}] @pytest.mark.parametrize("format_type", [None, "torch", "python", "tf", "tensorflow", "np", "numpy", "jax"]) def test_iterable_dataset_with_format(dataset: IterableDataset, format_type): formatted_dataset = dataset.with_format(format_type) assert formatted_dataset._formatting.format_type == get_format_type_from_alias(format_type) @require_torch def test_iterable_dataset_is_torch_iterable_dataset(dataset: IterableDataset): from torch.utils.data import DataLoader, _DatasetKind dataloader = DataLoader(dataset) assert dataloader._dataset_kind == _DatasetKind.Iterable out = list(dataloader) assert len(out) == DEFAULT_N_EXAMPLES @pytest.mark.parametrize("n", [0, 2, int(1e10)]) def test_iterable_dataset_skip(dataset: IterableDataset, n): skip_dataset = dataset.skip(n) assert isinstance(skip_dataset._ex_iterable, SkipExamplesIterable) assert skip_dataset._ex_iterable.n == n assert list(skip_dataset) == list(dataset)[n:] @pytest.mark.parametrize("n", [0, 2, int(1e10)]) def test_iterable_dataset_take(dataset: IterableDataset, n): take_dataset = dataset.take(n) assert isinstance(take_dataset._ex_iterable, TakeExamplesIterable) assert take_dataset._ex_iterable.n == n assert list(take_dataset) == list(dataset)[:n] @pytest.mark.parametrize("method", ["skip", "take"]) def test_iterable_dataset_shuffle_after_skip_or_take(method): seed = 42 n, n_shards = 3, 10 count = 7 ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n, "filepaths": [f"{i}.txt" for i in range(n_shards)]}) dataset = IterableDataset(ex_iterable) dataset = dataset.skip(n) if method == "skip" else dataset.take(count) shuffled_dataset = dataset.shuffle(seed, buffer_size=DEFAULT_N_EXAMPLES) # shuffling a skip/take dataset should keep the same examples and don't shuffle the shards key = lambda x: f"{x['filepath']}_{x['id']}" # noqa: E731 assert sorted(dataset, key=key) == sorted(shuffled_dataset, key=key) def test_iterable_dataset_add_column(dataset_with_several_columns): new_column = list(range(DEFAULT_N_EXAMPLES)) new_dataset = dataset_with_several_columns.add_column("new_column", new_column) assert list(new_dataset) == [ {**example, "new_column": idx} for idx, example in enumerate(dataset_with_several_columns) ] new_dataset = new_dataset._resolve_features() assert "new_column" in new_dataset.column_names def test_iterable_dataset_rename_column(dataset_with_several_columns): new_dataset = dataset_with_several_columns.rename_column("id", "new_id") assert list(new_dataset) == [ {("new_id" if k == "id" else k): v for k, v in example.items()} for example in dataset_with_several_columns ] assert new_dataset.features is None assert new_dataset.column_names is None # rename the column if ds.features was not None new_dataset = dataset_with_several_columns._resolve_features().rename_column("id", "new_id") assert new_dataset.features is not None assert new_dataset.column_names is not None assert "id" not in new_dataset.column_names assert "new_id" in new_dataset.column_names def test_iterable_dataset_rename_columns(dataset_with_several_columns): column_mapping = {"id": "new_id", "filepath": "filename"} new_dataset = dataset_with_several_columns.rename_columns(column_mapping) assert list(new_dataset) == [ {column_mapping.get(k, k): v for k, v in example.items()} for example in dataset_with_several_columns ] assert new_dataset.features is None assert new_dataset.column_names is None # rename the columns if ds.features was not None new_dataset = dataset_with_several_columns._resolve_features().rename_columns(column_mapping) assert new_dataset.features is not None assert new_dataset.column_names is not None assert all(c not in new_dataset.column_names for c in ["id", "filepath"]) assert all(c in new_dataset.column_names for c in ["new_id", "filename"]) def test_iterable_dataset_remove_columns(dataset_with_several_columns): new_dataset = dataset_with_several_columns.remove_columns("id") assert list(new_dataset) == [ {k: v for k, v in example.items() if k != "id"} for example in dataset_with_several_columns ] assert new_dataset.features is None new_dataset = dataset_with_several_columns.remove_columns(["id", "filepath"]) assert list(new_dataset) == [ {k: v for k, v in example.items() if k != "id" and k != "filepath"} for example in dataset_with_several_columns ] assert new_dataset.features is None assert new_dataset.column_names is None # remove the columns if ds.features was not None new_dataset = dataset_with_several_columns._resolve_features().remove_columns(["id", "filepath"]) assert new_dataset.features is not None assert new_dataset.column_names is not None assert all(c not in new_dataset.features for c in ["id", "filepath"]) assert all(c not in new_dataset.column_names for c in ["id", "filepath"]) def test_iterable_dataset_select_columns(dataset_with_several_columns): new_dataset = dataset_with_several_columns.select_columns("id") assert list(new_dataset) == [ {k: v for k, v in example.items() if k == "id"} for example in dataset_with_several_columns ] assert new_dataset.features is None new_dataset = dataset_with_several_columns.select_columns(["id", "filepath"]) assert list(new_dataset) == [ {k: v for k, v in example.items() if k in ("id", "filepath")} for example in dataset_with_several_columns ] assert new_dataset.features is None # select the columns if ds.features was not None new_dataset = dataset_with_several_columns._resolve_features().select_columns(["id", "filepath"]) assert new_dataset.features is not None assert new_dataset.column_names is not None assert all(c in new_dataset.features for c in ["id", "filepath"]) assert all(c in new_dataset.column_names for c in ["id", "filepath"]) def test_iterable_dataset_cast_column(): ex_iterable = ExamplesIterable(generate_examples_fn, {"label": 10}) features = Features({"id": Value("int64"), "label": Value("int64")}) dataset = IterableDataset(ex_iterable, info=DatasetInfo(features=features)) casted_dataset = dataset.cast_column("label", Value("bool")) casted_features = features.copy() casted_features["label"] = Value("bool") assert list(casted_dataset) == [casted_features.encode_example(ex) for _, ex in ex_iterable] def test_iterable_dataset_cast(): ex_iterable = ExamplesIterable(generate_examples_fn, {"label": 10}) features = Features({"id": Value("int64"), "label": Value("int64")}) dataset = IterableDataset(ex_iterable, info=DatasetInfo(features=features)) new_features = Features({"id": Value("int64"), "label": Value("bool")}) casted_dataset = dataset.cast(new_features) assert list(casted_dataset) == [new_features.encode_example(ex) for _, ex in ex_iterable] def test_iterable_dataset_resolve_features(): ex_iterable = ExamplesIterable(generate_examples_fn, {}) dataset = IterableDataset(ex_iterable) assert dataset.features is None assert dataset.column_names is None dataset = dataset._resolve_features() assert dataset.features == Features( { "id": Value("int64"), } ) assert dataset.column_names == ["id"] def test_iterable_dataset_resolve_features_keep_order(): def gen(): yield from zip(range(3), [{"a": 1}, {"c": 1}, {"b": 1}]) ex_iterable = ExamplesIterable(gen, {}) dataset = IterableDataset(ex_iterable)._resolve_features() # columns appear in order of appearance in the dataset assert list(dataset.features) == ["a", "c", "b"] assert dataset.column_names == ["a", "c", "b"] def test_iterable_dataset_with_features_fill_with_none(): def gen(): yield from zip(range(2), [{"a": 1}, {"b": 1}]) ex_iterable = ExamplesIterable(gen, {}) info = DatasetInfo(features=Features({"a": Value("int32"), "b": Value("int32")})) dataset = IterableDataset(ex_iterable, info=info) assert list(dataset) == [{"a": 1, "b": None}, {"b": 1, "a": None}] def test_concatenate_datasets(): ex_iterable1 = ExamplesIterable(generate_examples_fn, {"label": 10}) dataset1 = IterableDataset(ex_iterable1) ex_iterable2 = ExamplesIterable(generate_examples_fn, {"label": 5}) dataset2 = IterableDataset(ex_iterable2) concatenated_dataset = concatenate_datasets([dataset1, dataset2]) assert list(concatenated_dataset) == list(dataset1) + list(dataset2) def test_concatenate_datasets_resolves_features(): ex_iterable1 = ExamplesIterable(generate_examples_fn, {"label": 10}) dataset1 = IterableDataset(ex_iterable1) ex_iterable2 = ExamplesIterable(generate_examples_fn, {"label": 5}) dataset2 = IterableDataset(ex_iterable2) concatenated_dataset = concatenate_datasets([dataset1, dataset2]) assert concatenated_dataset.features is not None assert sorted(concatenated_dataset.features) == ["id", "label"] def test_concatenate_datasets_with_different_columns(): ex_iterable1 = ExamplesIterable(generate_examples_fn, {"label": 10}) dataset1 = IterableDataset(ex_iterable1) ex_iterable2 = ExamplesIterable(generate_examples_fn, {}) dataset2 = IterableDataset(ex_iterable2) # missing column "label" -> it should be replaced with nulls extended_dataset2_list = [{"label": None, **x} for x in dataset2] concatenated_dataset = concatenate_datasets([dataset1, dataset2]) assert list(concatenated_dataset) == list(dataset1) + extended_dataset2_list # change order concatenated_dataset = concatenate_datasets([dataset2, dataset1]) assert list(concatenated_dataset) == extended_dataset2_list + list(dataset1) def test_concatenate_datasets_axis_1(): ex_iterable1 = ExamplesIterable(generate_examples_fn, {"label1": 10}) dataset1 = IterableDataset(ex_iterable1) ex_iterable2 = ExamplesIterable(generate_examples_fn, {"label2": 5}) dataset2 = IterableDataset(ex_iterable2) with pytest.raises(ValueError): # column "id" is duplicated -> raise an error concatenate_datasets([dataset1, dataset2], axis=1) concatenated_dataset = concatenate_datasets([dataset1, dataset2.remove_columns("id")], axis=1) assert list(concatenated_dataset) == [{**x, **y} for x, y in zip(dataset1, dataset2)] def test_concatenate_datasets_axis_1_resolves_features(): ex_iterable1 = ExamplesIterable(generate_examples_fn, {"label1": 10}) dataset1 = IterableDataset(ex_iterable1) ex_iterable2 = ExamplesIterable(generate_examples_fn, {"label2": 5}) dataset2 = IterableDataset(ex_iterable2).remove_columns("id") concatenated_dataset = concatenate_datasets([dataset1, dataset2], axis=1) assert concatenated_dataset.features is not None assert sorted(concatenated_dataset.features) == ["id", "label1", "label2"] def test_concatenate_datasets_axis_1_with_different_lengths(): n1 = 10 ex_iterable1 = ExamplesIterable(generate_examples_fn, {"label1": 10, "n": n1}) dataset1 = IterableDataset(ex_iterable1) n2 = 5 ex_iterable2 = ExamplesIterable(generate_examples_fn, {"label2": 5, "n": n2}) dataset2 = IterableDataset(ex_iterable2).remove_columns("id") # missing rows -> they should be replaced with nulls extended_dataset2_list = list(dataset2) + [{"label2": None}] * (n1 - n2) concatenated_dataset = concatenate_datasets([dataset1, dataset2], axis=1) assert list(concatenated_dataset) == [{**x, **y} for x, y in zip(dataset1, extended_dataset2_list)] # change order concatenated_dataset = concatenate_datasets([dataset2, dataset1], axis=1) assert list(concatenated_dataset) == [{**x, **y} for x, y in zip(extended_dataset2_list, dataset1)] @pytest.mark.parametrize( "probas, seed, expected_length, stopping_strategy", [ (None, None, 3 * (DEFAULT_N_EXAMPLES - 1) + 1, "first_exhausted"), ([1, 0, 0], None, DEFAULT_N_EXAMPLES, "first_exhausted"), ([0, 1, 0], None, DEFAULT_N_EXAMPLES, "first_exhausted"), ([0.2, 0.5, 0.3], 42, None, "first_exhausted"), ([0.1, 0.1, 0.8], 1337, None, "first_exhausted"), ([0.5, 0.2, 0.3], 101010, None, "first_exhausted"), (None, None, 3 * DEFAULT_N_EXAMPLES, "all_exhausted"), ([0.2, 0.5, 0.3], 42, None, "all_exhausted"), ([0.1, 0.1, 0.8], 1337, None, "all_exhausted"), ([0.5, 0.2, 0.3], 101010, None, "all_exhausted"), ], ) def test_interleave_datasets(dataset: IterableDataset, probas, seed, expected_length, stopping_strategy): d1 = dataset d2 = dataset.map(lambda x: {"id+1": x["id"] + 1, **x}) d3 = dataset.with_format("python") datasets = [d1, d2, d3] merged_dataset = interleave_datasets( datasets, probabilities=probas, seed=seed, stopping_strategy=stopping_strategy ) def fill_default(example): return {"id": None, "id+1": None, **example} # Check the examples iterable assert isinstance( merged_dataset._ex_iterable, (CyclingMultiSourcesExamplesIterable, RandomlyCyclingMultiSourcesExamplesIterable) ) # Check that it is deterministic if seed is not None: merged_dataset2 = interleave_datasets( [d1, d2, d3], probabilities=probas, seed=seed, stopping_strategy=stopping_strategy ) assert list(merged_dataset) == list(merged_dataset2) # Check features assert merged_dataset.features == Features({"id": Value("int64"), "id+1": Value("int64")}) # Check first example if seed is not None: rng = np.random.default_rng(seed) i = next(iter(RandomlyCyclingMultiSourcesExamplesIterable._iter_random_indices(rng, len(datasets), p=probas))) assert next(iter(merged_dataset)) == fill_default(next(iter(datasets[i]))) else: assert any(next(iter(merged_dataset)) == fill_default(next(iter(dataset))) for dataset in datasets) # Compute length it case it's random if expected_length is None: expected_length = 0 counts = np.array([len(list(d)) for d in datasets]) bool_strategy_func = np.all if stopping_strategy == "all_exhausted" else np.any rng = np.random.default_rng(seed) for i in RandomlyCyclingMultiSourcesExamplesIterable._iter_random_indices(rng, len(datasets), p=probas): counts[i] -= 1 expected_length += 1 if bool_strategy_func(counts <= 0): break # Check length assert len(list(merged_dataset)) == expected_length def test_interleave_datasets_with_features( dataset: IterableDataset, ): features = Features( { "id": Value("int64"), "label": ClassLabel(names=["negative", "positive"]), } ) ex_iterable = ExamplesIterable(generate_examples_fn, {"label": 0}) dataset_with_features = IterableDataset(ex_iterable, info=DatasetInfo(features=features)) merged_dataset = interleave_datasets([dataset, dataset_with_features]) assert merged_dataset.features == features def test_interleave_datasets_with_oversampling(): # Test hardcoded results d1 = IterableDataset(ExamplesIterable((lambda: (yield from [(i, {"a": i}) for i in [0, 1, 2]])), {})) d2 = IterableDataset(ExamplesIterable((lambda: (yield from [(i, {"a": i}) for i in [10, 11, 12, 13]])), {})) d3 = IterableDataset(ExamplesIterable((lambda: (yield from [(i, {"a": i}) for i in [20, 21, 22, 23, 24]])), {})) expected_values = [0, 10, 20, 1, 11, 21, 2, 12, 22, 0, 13, 23, 1, 10, 24] # Check oversampling strategy without probabilities assert [x["a"] for x in interleave_datasets([d1, d2, d3], stopping_strategy="all_exhausted")] == expected_values # Check oversampling strategy with probabilities expected_values = [20, 0, 21, 10, 1, 22, 23, 24, 2, 0, 1, 20, 11, 21, 2, 0, 12, 1, 22, 13] values = [ x["a"] for x in interleave_datasets( [d1, d2, d3], probabilities=[0.5, 0.2, 0.3], seed=42, stopping_strategy="all_exhausted" ) ] assert values == expected_values @require_torch def test_with_format_torch(dataset_with_several_columns: IterableDataset): import torch dset = dataset_with_several_columns.with_format(type="torch") example = next(iter(dset)) batch = next(iter(dset.iter(batch_size=3))) assert len(example) == 3 assert isinstance(example["id"], torch.Tensor) assert list(example["id"].shape) == [] assert example["id"].item() == 0 assert isinstance(batch["id"], torch.Tensor) assert isinstance(example["filepath"], list) assert isinstance(example["filepath"][0], str) assert example["filepath"][0] == "data0.txt" assert isinstance(batch["filepath"], list) assert isinstance(example["metadata"], dict) assert isinstance(example["metadata"]["sources"], list) assert isinstance(example["metadata"]["sources"][0], str) assert isinstance(batch["metadata"], list) @require_tf def test_with_format_tf(dataset_with_several_columns: IterableDataset): import tensorflow as tf dset = dataset_with_several_columns.with_format(type="tensorflow") example = next(iter(dset)) batch = next(iter(dset.iter(batch_size=3))) assert isinstance(example["id"], tf.Tensor) assert list(example["id"].shape) == [] assert example["id"].numpy().item() == 0 assert isinstance(batch["id"], tf.Tensor) assert isinstance(example["filepath"], tf.Tensor) assert example["filepath"][0] == b"data0.txt" assert isinstance(batch["filepath"], tf.Tensor) assert isinstance(example["metadata"], dict) assert isinstance(example["metadata"]["sources"], tf.Tensor) assert isinstance(batch["metadata"], list) def test_map_array_are_not_converted_back_to_lists(dataset: IterableDataset): def func(example): return {"array": np.array([1, 2, 3])} dset_test = dataset.map(func) example = next(iter(dset_test)) # not aligned with Dataset.map because we don't convert back to lists after map() assert isinstance(example["array"], np.ndarray) def test_formatted_map(dataset: IterableDataset): dataset = dataset.with_format("np") assert isinstance(next(dataset.iter(batch_size=3))["id"], np.ndarray) dataset = dataset.with_format(None) assert isinstance(next(dataset.iter(batch_size=3))["id"], list) def add_one_numpy(example): assert isinstance(example["id"], np.ndarray) return {"id": example["id"] + 1} dataset = dataset.with_format("np") dataset = dataset.map(add_one_numpy, batched=True) assert isinstance(next(dataset.iter(batch_size=3))["id"], np.ndarray) dataset = dataset.with_format(None) assert isinstance(next(dataset.iter(batch_size=3))["id"], list) @pytest.mark.parametrize("n_shards1, nshards2, num_workers", [(2, 1, 1), (2, 2, 2), (1, 3, 1), (4, 3, 3)]) def test_interleave_dataset_with_sharding(n_shards1, nshards2, num_workers): from torch.utils.data import DataLoader ex_iterable1 = ExamplesIterable(generate_examples_fn, {"filepaths": [f"{i}-1.txt" for i in range(n_shards1)]}) dataset1 = IterableDataset(ex_iterable1).with_format("torch") ex_iterable2 = ExamplesIterable(generate_examples_fn, {"filepaths": [f"{i}-2.txt" for i in range(nshards2)]}) dataset2 = IterableDataset(ex_iterable2).with_format("torch") dataset_merged = interleave_datasets([dataset1, dataset2], stopping_strategy="first_exhausted") assert dataset_merged.n_shards == min(n_shards1, nshards2) dataloader = DataLoader(dataset_merged, batch_size=None, num_workers=num_workers) result = list(dataloader) expected_length = 2 * min( len([example for _, example in ex_iterable1]), len([example for _, example in ex_iterable2]) ) # some samples may be missing because the stopping strategy is applied per process assert expected_length - num_workers <= len(result) <= expected_length assert len(result) == len({str(x) for x in result})
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_load.py
import importlib import os import pickle import shutil import tempfile import time from hashlib import sha256 from multiprocessing import Pool from pathlib import Path from unittest import TestCase from unittest.mock import patch import dill import pyarrow as pa import pytest import requests import datasets from datasets import config, load_dataset, load_from_disk from datasets.arrow_dataset import Dataset from datasets.arrow_writer import ArrowWriter from datasets.builder import DatasetBuilder from datasets.config import METADATA_CONFIGS_FIELD from datasets.data_files import DataFilesDict from datasets.dataset_dict import DatasetDict, IterableDatasetDict from datasets.download.download_config import DownloadConfig from datasets.features import Features, Value from datasets.iterable_dataset import IterableDataset from datasets.load import ( CachedDatasetModuleFactory, CachedMetricModuleFactory, GithubMetricModuleFactory, HubDatasetModuleFactoryWithoutScript, HubDatasetModuleFactoryWithScript, LocalDatasetModuleFactoryWithoutScript, LocalDatasetModuleFactoryWithScript, LocalMetricModuleFactory, PackagedDatasetModuleFactory, infer_module_for_data_files_list, infer_module_for_data_files_list_in_archives, load_dataset_builder, ) from datasets.packaged_modules.audiofolder.audiofolder import AudioFolder, AudioFolderConfig from datasets.packaged_modules.imagefolder.imagefolder import ImageFolder, ImageFolderConfig from datasets.utils.logging import INFO, get_logger from .utils import ( OfflineSimulationMode, assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, offline, require_pil, require_sndfile, set_current_working_directory_to_temp_dir, ) DATASET_LOADING_SCRIPT_NAME = "__dummy_dataset1__" DATASET_LOADING_SCRIPT_CODE = """ import os import datasets from datasets import DatasetInfo, Features, Split, SplitGenerator, Value class __DummyDataset1__(datasets.GeneratorBasedBuilder): def _info(self) -> DatasetInfo: return DatasetInfo(features=Features({"text": Value("string")})) def _split_generators(self, dl_manager): return [ SplitGenerator(Split.TRAIN, gen_kwargs={"filepath": os.path.join(dl_manager.manual_dir, "train.txt")}), SplitGenerator(Split.TEST, gen_kwargs={"filepath": os.path.join(dl_manager.manual_dir, "test.txt")}), ] def _generate_examples(self, filepath, **kwargs): with open(filepath, "r", encoding="utf-8") as f: for i, line in enumerate(f): yield i, {"text": line.strip()} """ SAMPLE_DATASET_IDENTIFIER = "lhoestq/test" # has dataset script SAMPLE_DATASET_IDENTIFIER2 = "lhoestq/test2" # only has data files SAMPLE_DATASET_IDENTIFIER3 = "mariosasko/test_multi_dir_dataset" # has multiple data directories SAMPLE_DATASET_IDENTIFIER4 = "mariosasko/test_imagefolder_with_metadata" # imagefolder with a metadata file outside of the train/test directories SAMPLE_NOT_EXISTING_DATASET_IDENTIFIER = "lhoestq/_dummy" SAMPLE_DATASET_NAME_THAT_DOESNT_EXIST = "_dummy" SAMPLE_DATASET_NO_CONFIGS_IN_METADATA = "datasets-maintainers/audiofolder_no_configs_in_metadata" SAMPLE_DATASET_SINGLE_CONFIG_IN_METADATA = "datasets-maintainers/audiofolder_single_config_in_metadata" SAMPLE_DATASET_TWO_CONFIG_IN_METADATA = "datasets-maintainers/audiofolder_two_configs_in_metadata" SAMPLE_DATASET_TWO_CONFIG_IN_METADATA_WITH_DEFAULT = ( "datasets-maintainers/audiofolder_two_configs_in_metadata_with_default" ) METRIC_LOADING_SCRIPT_NAME = "__dummy_metric1__" METRIC_LOADING_SCRIPT_CODE = """ import datasets from datasets import MetricInfo, Features, Value class __DummyMetric1__(datasets.Metric): def _info(self): return MetricInfo(features=Features({"predictions": Value("int"), "references": Value("int")})) def _compute(self, predictions, references): return {"__dummy_metric1__": sum(int(p == r) for p, r in zip(predictions, references))} """ @pytest.fixture def data_dir(tmp_path): data_dir = tmp_path / "data_dir" data_dir.mkdir() with open(data_dir / "train.txt", "w") as f: f.write("foo\n" * 10) with open(data_dir / "test.txt", "w") as f: f.write("bar\n" * 10) return str(data_dir) @pytest.fixture def data_dir_with_arrow(tmp_path): data_dir = tmp_path / "data_dir" data_dir.mkdir() output_train = os.path.join(data_dir, "train.arrow") with ArrowWriter(path=output_train) as writer: writer.write_table(pa.Table.from_pydict({"col_1": ["foo"] * 10})) num_examples, num_bytes = writer.finalize() assert num_examples == 10 assert num_bytes > 0 output_test = os.path.join(data_dir, "test.arrow") with ArrowWriter(path=output_test) as writer: writer.write_table(pa.Table.from_pydict({"col_1": ["bar"] * 10})) num_examples, num_bytes = writer.finalize() assert num_examples == 10 assert num_bytes > 0 return str(data_dir) @pytest.fixture def data_dir_with_metadata(tmp_path): data_dir = tmp_path / "data_dir_with_metadata" data_dir.mkdir() with open(data_dir / "train.jpg", "wb") as f: f.write(b"train_image_bytes") with open(data_dir / "test.jpg", "wb") as f: f.write(b"test_image_bytes") with open(data_dir / "metadata.jsonl", "w") as f: f.write( """\ {"file_name": "train.jpg", "caption": "Cool tran image"} {"file_name": "test.jpg", "caption": "Cool test image"} """ ) return str(data_dir) @pytest.fixture def data_dir_with_single_config_in_metadata(tmp_path): data_dir = tmp_path / "data_dir_with_one_default_config_in_metadata" cats_data_dir = data_dir / "cats" cats_data_dir.mkdir(parents=True) dogs_data_dir = data_dir / "dogs" dogs_data_dir.mkdir(parents=True) with open(cats_data_dir / "cat.jpg", "wb") as f: f.write(b"this_is_a_cat_image_bytes") with open(dogs_data_dir / "dog.jpg", "wb") as f: f.write(b"this_is_a_dog_image_bytes") with open(data_dir / "README.md", "w") as f: f.write( f"""\ --- {METADATA_CONFIGS_FIELD}: - config_name: custom drop_labels: true --- """ ) return str(data_dir) @pytest.fixture def data_dir_with_two_config_in_metadata(tmp_path): data_dir = tmp_path / "data_dir_with_two_configs_in_metadata" cats_data_dir = data_dir / "cats" cats_data_dir.mkdir(parents=True) dogs_data_dir = data_dir / "dogs" dogs_data_dir.mkdir(parents=True) with open(cats_data_dir / "cat.jpg", "wb") as f: f.write(b"this_is_a_cat_image_bytes") with open(dogs_data_dir / "dog.jpg", "wb") as f: f.write(b"this_is_a_dog_image_bytes") with open(data_dir / "README.md", "w") as f: f.write( f"""\ --- {METADATA_CONFIGS_FIELD}: - config_name: "v1" drop_labels: true default: true - config_name: "v2" drop_labels: false --- """ ) return str(data_dir) @pytest.fixture def data_dir_with_data_dir_configs_in_metadata(tmp_path): data_dir = tmp_path / "data_dir_with_two_configs_in_metadata" cats_data_dir = data_dir / "cats" cats_data_dir.mkdir(parents=True) dogs_data_dir = data_dir / "dogs" dogs_data_dir.mkdir(parents=True) with open(cats_data_dir / "cat.jpg", "wb") as f: f.write(b"this_is_a_cat_image_bytes") with open(dogs_data_dir / "dog.jpg", "wb") as f: f.write(b"this_is_a_dog_image_bytes") @pytest.fixture def sub_data_dirs(tmp_path): data_dir2 = tmp_path / "data_dir2" relative_subdir1 = "subdir1" sub_data_dir1 = data_dir2 / relative_subdir1 sub_data_dir1.mkdir(parents=True) with open(sub_data_dir1 / "train.txt", "w") as f: f.write("foo\n" * 10) with open(sub_data_dir1 / "test.txt", "w") as f: f.write("bar\n" * 10) relative_subdir2 = "subdir2" sub_data_dir2 = tmp_path / data_dir2 / relative_subdir2 sub_data_dir2.mkdir(parents=True) with open(sub_data_dir2 / "train.txt", "w") as f: f.write("foo\n" * 10) with open(sub_data_dir2 / "test.txt", "w") as f: f.write("bar\n" * 10) return str(data_dir2), relative_subdir1 @pytest.fixture def complex_data_dir(tmp_path): data_dir = tmp_path / "complex_data_dir" data_dir.mkdir() (data_dir / "data").mkdir() with open(data_dir / "data" / "train.txt", "w") as f: f.write("foo\n" * 10) with open(data_dir / "data" / "test.txt", "w") as f: f.write("bar\n" * 10) with open(data_dir / "README.md", "w") as f: f.write("This is a readme") with open(data_dir / ".dummy", "w") as f: f.write("this is a dummy file that is not a data file") return str(data_dir) @pytest.fixture def dataset_loading_script_dir(tmp_path): script_name = DATASET_LOADING_SCRIPT_NAME script_dir = tmp_path / script_name script_dir.mkdir() script_path = script_dir / f"{script_name}.py" with open(script_path, "w") as f: f.write(DATASET_LOADING_SCRIPT_CODE) return str(script_dir) @pytest.fixture def dataset_loading_script_dir_readonly(tmp_path): script_name = DATASET_LOADING_SCRIPT_NAME script_dir = tmp_path / "readonly" / script_name script_dir.mkdir(parents=True) script_path = script_dir / f"{script_name}.py" with open(script_path, "w") as f: f.write(DATASET_LOADING_SCRIPT_CODE) dataset_loading_script_dir = str(script_dir) # Make this directory readonly os.chmod(dataset_loading_script_dir, 0o555) os.chmod(os.path.join(dataset_loading_script_dir, f"{script_name}.py"), 0o555) return dataset_loading_script_dir @pytest.fixture def metric_loading_script_dir(tmp_path): script_name = METRIC_LOADING_SCRIPT_NAME script_dir = tmp_path / script_name script_dir.mkdir() script_path = script_dir / f"{script_name}.py" with open(script_path, "w") as f: f.write(METRIC_LOADING_SCRIPT_CODE) return str(script_dir) @pytest.mark.parametrize( "data_files, expected_module, expected_builder_kwargs", [ (["train.csv"], "csv", {}), (["train.tsv"], "csv", {"sep": "\t"}), (["train.json"], "json", {}), (["train.jsonl"], "json", {}), (["train.parquet"], "parquet", {}), (["train.arrow"], "arrow", {}), (["train.txt"], "text", {}), (["uppercase.TXT"], "text", {}), (["unsupported.ext"], None, {}), ([""], None, {}), ], ) def test_infer_module_for_data_files(data_files, expected_module, expected_builder_kwargs): module, builder_kwargs = infer_module_for_data_files_list(data_files) assert module == expected_module assert builder_kwargs == expected_builder_kwargs @pytest.mark.parametrize( "data_file, expected_module", [ ("zip_csv_path", "csv"), ("zip_csv_with_dir_path", "csv"), ("zip_uppercase_csv_path", "csv"), ("zip_unsupported_ext_path", None), ], ) def test_infer_module_for_data_files_in_archives( data_file, expected_module, zip_csv_path, zip_csv_with_dir_path, zip_uppercase_csv_path, zip_unsupported_ext_path ): data_file_paths = { "zip_csv_path": zip_csv_path, "zip_csv_with_dir_path": zip_csv_with_dir_path, "zip_uppercase_csv_path": zip_uppercase_csv_path, "zip_unsupported_ext_path": zip_unsupported_ext_path, } data_files = [str(data_file_paths[data_file])] inferred_module, _ = infer_module_for_data_files_list_in_archives(data_files) assert inferred_module == expected_module class ModuleFactoryTest(TestCase): @pytest.fixture(autouse=True) def inject_fixtures( self, jsonl_path, data_dir, data_dir_with_metadata, data_dir_with_single_config_in_metadata, data_dir_with_two_config_in_metadata, sub_data_dirs, dataset_loading_script_dir, metric_loading_script_dir, ): self._jsonl_path = jsonl_path self._data_dir = data_dir self._data_dir_with_metadata = data_dir_with_metadata self._data_dir_with_single_config_in_metadata = data_dir_with_single_config_in_metadata self._data_dir_with_two_config_in_metadata = data_dir_with_two_config_in_metadata self._data_dir2 = sub_data_dirs[0] self._sub_data_dir = sub_data_dirs[1] self._dataset_loading_script_dir = dataset_loading_script_dir self._metric_loading_script_dir = metric_loading_script_dir def setUp(self): self.hf_modules_cache = tempfile.mkdtemp() self.cache_dir = tempfile.mkdtemp() self.download_config = DownloadConfig(cache_dir=self.cache_dir) self.dynamic_modules_path = datasets.load.init_dynamic_modules( name="test_datasets_modules_" + os.path.basename(self.hf_modules_cache), hf_modules_cache=self.hf_modules_cache, ) def test_HubDatasetModuleFactoryWithScript_with_github_dataset(self): # "wmt_t2t" has additional imports (internal) factory = HubDatasetModuleFactoryWithScript( "wmt_t2t", download_config=self.download_config, dynamic_modules_path=self.dynamic_modules_path ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None assert module_factory_result.builder_kwargs["base_path"].startswith(config.HF_ENDPOINT) def test_GithubMetricModuleFactory_with_internal_import(self): # "squad_v2" requires additional imports (internal) factory = GithubMetricModuleFactory( "squad_v2", download_config=self.download_config, dynamic_modules_path=self.dynamic_modules_path ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None @pytest.mark.filterwarnings("ignore:GithubMetricModuleFactory is deprecated:FutureWarning") def test_GithubMetricModuleFactory_with_external_import(self): # "bleu" requires additional imports (external from github) factory = GithubMetricModuleFactory( "bleu", download_config=self.download_config, dynamic_modules_path=self.dynamic_modules_path ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None def test_LocalMetricModuleFactory(self): path = os.path.join(self._metric_loading_script_dir, f"{METRIC_LOADING_SCRIPT_NAME}.py") factory = LocalMetricModuleFactory( path, download_config=self.download_config, dynamic_modules_path=self.dynamic_modules_path ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None def test_LocalDatasetModuleFactoryWithScript(self): path = os.path.join(self._dataset_loading_script_dir, f"{DATASET_LOADING_SCRIPT_NAME}.py") factory = LocalDatasetModuleFactoryWithScript( path, download_config=self.download_config, dynamic_modules_path=self.dynamic_modules_path ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None assert os.path.isdir(module_factory_result.builder_kwargs["base_path"]) def test_LocalDatasetModuleFactoryWithoutScript(self): factory = LocalDatasetModuleFactoryWithoutScript(self._data_dir) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None assert os.path.isdir(module_factory_result.builder_kwargs["base_path"]) def test_LocalDatasetModuleFactoryWithoutScript_with_data_dir(self): factory = LocalDatasetModuleFactoryWithoutScript(self._data_dir2, data_dir=self._sub_data_dir) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None assert ( module_factory_result.builder_kwargs["data_files"] is not None and len(module_factory_result.builder_kwargs["data_files"]["train"]) == 1 and len(module_factory_result.builder_kwargs["data_files"]["test"]) == 1 ) assert all( self._sub_data_dir in Path(data_file).parts for data_file in module_factory_result.builder_kwargs["data_files"]["train"] + module_factory_result.builder_kwargs["data_files"]["test"] ) def test_LocalDatasetModuleFactoryWithoutScript_with_metadata(self): factory = LocalDatasetModuleFactoryWithoutScript(self._data_dir_with_metadata) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None assert ( module_factory_result.builder_kwargs["data_files"] is not None and len(module_factory_result.builder_kwargs["data_files"]["train"]) > 0 and len(module_factory_result.builder_kwargs["data_files"]["test"]) > 0 ) assert any( Path(data_file).name == "metadata.jsonl" for data_file in module_factory_result.builder_kwargs["data_files"]["train"] ) assert any( Path(data_file).name == "metadata.jsonl" for data_file in module_factory_result.builder_kwargs["data_files"]["test"] ) def test_LocalDatasetModuleFactoryWithoutScript_with_single_config_in_metadata(self): factory = LocalDatasetModuleFactoryWithoutScript( self._data_dir_with_single_config_in_metadata, ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None module_metadata_configs = module_factory_result.builder_configs_parameters.metadata_configs assert module_metadata_configs is not None assert len(module_metadata_configs) == 1 assert next(iter(module_metadata_configs)) == "custom" assert "drop_labels" in next(iter(module_metadata_configs.values())) assert next(iter(module_metadata_configs.values()))["drop_labels"] is True module_builder_configs = module_factory_result.builder_configs_parameters.builder_configs assert module_builder_configs is not None assert len(module_builder_configs) == 1 assert isinstance(module_builder_configs[0], ImageFolderConfig) assert module_builder_configs[0].name == "custom" assert module_builder_configs[0].data_files is not None assert isinstance(module_builder_configs[0].data_files, DataFilesDict) assert len(module_builder_configs[0].data_files) == 1 # one train split assert len(module_builder_configs[0].data_files["train"]) == 2 # two files assert module_builder_configs[0].drop_labels is True # parameter is passed from metadata # config named "default" is automatically considered to be a default config assert module_factory_result.builder_configs_parameters.default_config_name is None # we don't pass config params to builder in builder_kwargs, they are stored in builder_configs directly assert "drop_labels" not in module_factory_result.builder_kwargs def test_LocalDatasetModuleFactoryWithoutScript_with_two_configs_in_metadata(self): factory = LocalDatasetModuleFactoryWithoutScript( self._data_dir_with_two_config_in_metadata, ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None module_metadata_configs = module_factory_result.builder_configs_parameters.metadata_configs assert module_metadata_configs is not None assert len(module_metadata_configs) == 2 assert list(module_metadata_configs) == ["v1", "v2"] assert "drop_labels" in module_metadata_configs["v1"] assert module_metadata_configs["v1"]["drop_labels"] is True assert "drop_labels" in module_metadata_configs["v2"] assert module_metadata_configs["v2"]["drop_labels"] is False module_builder_configs = module_factory_result.builder_configs_parameters.builder_configs assert module_builder_configs is not None assert len(module_builder_configs) == 2 module_builder_config_v1, module_builder_config_v2 = module_builder_configs assert module_builder_config_v1.name == "v1" assert module_builder_config_v2.name == "v2" assert isinstance(module_builder_config_v1, ImageFolderConfig) assert isinstance(module_builder_config_v2, ImageFolderConfig) assert isinstance(module_builder_config_v1.data_files, DataFilesDict) assert isinstance(module_builder_config_v2.data_files, DataFilesDict) assert sorted(module_builder_config_v1.data_files) == ["train"] assert len(module_builder_config_v1.data_files["train"]) == 2 assert sorted(module_builder_config_v2.data_files) == ["train"] assert len(module_builder_config_v2.data_files["train"]) == 2 assert module_builder_config_v1.drop_labels is True # parameter is passed from metadata assert module_builder_config_v2.drop_labels is False # parameter is passed from metadata assert ( module_factory_result.builder_configs_parameters.default_config_name == "v1" ) # it's marked as a default one in yaml # we don't pass config params to builder in builder_kwargs, they are stored in builder_configs directly assert "drop_labels" not in module_factory_result.builder_kwargs def test_PackagedDatasetModuleFactory(self): factory = PackagedDatasetModuleFactory( "json", data_files=self._jsonl_path, download_config=self.download_config ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None def test_PackagedDatasetModuleFactory_with_data_dir(self): factory = PackagedDatasetModuleFactory("json", data_dir=self._data_dir, download_config=self.download_config) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None assert ( module_factory_result.builder_kwargs["data_files"] is not None and len(module_factory_result.builder_kwargs["data_files"]["train"]) > 0 and len(module_factory_result.builder_kwargs["data_files"]["test"]) > 0 ) assert Path(module_factory_result.builder_kwargs["data_files"]["train"][0]).parent.samefile(self._data_dir) assert Path(module_factory_result.builder_kwargs["data_files"]["test"][0]).parent.samefile(self._data_dir) def test_PackagedDatasetModuleFactory_with_data_dir_and_metadata(self): factory = PackagedDatasetModuleFactory( "imagefolder", data_dir=self._data_dir_with_metadata, download_config=self.download_config ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None assert ( module_factory_result.builder_kwargs["data_files"] is not None and len(module_factory_result.builder_kwargs["data_files"]["train"]) > 0 and len(module_factory_result.builder_kwargs["data_files"]["test"]) > 0 ) assert Path(module_factory_result.builder_kwargs["data_files"]["train"][0]).parent.samefile( self._data_dir_with_metadata ) assert Path(module_factory_result.builder_kwargs["data_files"]["test"][0]).parent.samefile( self._data_dir_with_metadata ) assert any( Path(data_file).name == "metadata.jsonl" for data_file in module_factory_result.builder_kwargs["data_files"]["train"] ) assert any( Path(data_file).name == "metadata.jsonl" for data_file in module_factory_result.builder_kwargs["data_files"]["test"] ) @pytest.mark.integration def test_HubDatasetModuleFactoryWithoutScript(self): factory = HubDatasetModuleFactoryWithoutScript( SAMPLE_DATASET_IDENTIFIER2, download_config=self.download_config ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None assert module_factory_result.builder_kwargs["base_path"].startswith(config.HF_ENDPOINT) @pytest.mark.integration def test_HubDatasetModuleFactoryWithoutScript_with_data_dir(self): data_dir = "data2" factory = HubDatasetModuleFactoryWithoutScript( SAMPLE_DATASET_IDENTIFIER3, data_dir=data_dir, download_config=self.download_config ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None assert module_factory_result.builder_kwargs["base_path"].startswith(config.HF_ENDPOINT) assert ( module_factory_result.builder_kwargs["data_files"] is not None and len(module_factory_result.builder_kwargs["data_files"]["train"]) == 1 and len(module_factory_result.builder_kwargs["data_files"]["test"]) == 1 ) assert all( data_dir in Path(data_file).parts for data_file in module_factory_result.builder_kwargs["data_files"]["train"] + module_factory_result.builder_kwargs["data_files"]["test"] ) @pytest.mark.integration def test_HubDatasetModuleFactoryWithoutScript_with_metadata(self): factory = HubDatasetModuleFactoryWithoutScript( SAMPLE_DATASET_IDENTIFIER4, download_config=self.download_config ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None assert module_factory_result.builder_kwargs["base_path"].startswith(config.HF_ENDPOINT) assert ( module_factory_result.builder_kwargs["data_files"] is not None and len(module_factory_result.builder_kwargs["data_files"]["train"]) > 0 and len(module_factory_result.builder_kwargs["data_files"]["test"]) > 0 ) assert any( Path(data_file).name == "metadata.jsonl" for data_file in module_factory_result.builder_kwargs["data_files"]["train"] ) assert any( Path(data_file).name == "metadata.jsonl" for data_file in module_factory_result.builder_kwargs["data_files"]["test"] ) @pytest.mark.integration def test_HubDatasetModuleFactoryWithoutScript_with_one_default_config_in_metadata(self): factory = HubDatasetModuleFactoryWithoutScript( SAMPLE_DATASET_SINGLE_CONFIG_IN_METADATA, download_config=self.download_config, ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None assert module_factory_result.builder_kwargs["base_path"].startswith(config.HF_ENDPOINT) module_metadata_configs = module_factory_result.builder_configs_parameters.metadata_configs assert module_metadata_configs is not None assert len(module_metadata_configs) == 1 assert next(iter(module_metadata_configs)) == "custom" assert "drop_labels" in next(iter(module_metadata_configs.values())) assert next(iter(module_metadata_configs.values()))["drop_labels"] is True module_builder_configs = module_factory_result.builder_configs_parameters.builder_configs assert module_builder_configs is not None assert len(module_builder_configs) == 1 assert isinstance(module_builder_configs[0], AudioFolderConfig) assert module_builder_configs[0].name == "custom" assert module_builder_configs[0].data_files is not None assert isinstance(module_builder_configs[0].data_files, DataFilesDict) assert sorted(module_builder_configs[0].data_files) == ["test", "train"] assert len(module_builder_configs[0].data_files["train"]) == 3 assert len(module_builder_configs[0].data_files["test"]) == 3 assert module_builder_configs[0].drop_labels is True # parameter is passed from metadata # config named "default" is automatically considered to be a default config assert module_factory_result.builder_configs_parameters.default_config_name is None # we don't pass config params to builder in builder_kwargs, they are stored in builder_configs directly assert "drop_labels" not in module_factory_result.builder_kwargs @pytest.mark.integration def test_HubDatasetModuleFactoryWithoutScript_with_two_configs_in_metadata(self): datasets_names = [SAMPLE_DATASET_TWO_CONFIG_IN_METADATA, SAMPLE_DATASET_TWO_CONFIG_IN_METADATA_WITH_DEFAULT] for dataset_name in datasets_names: factory = HubDatasetModuleFactoryWithoutScript(dataset_name, download_config=self.download_config) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None module_metadata_configs = module_factory_result.builder_configs_parameters.metadata_configs assert module_metadata_configs is not None assert len(module_metadata_configs) == 2 assert list(module_metadata_configs) == ["v1", "v2"] assert "drop_labels" in module_metadata_configs["v1"] assert module_metadata_configs["v1"]["drop_labels"] is True assert "drop_labels" in module_metadata_configs["v2"] assert module_metadata_configs["v2"]["drop_labels"] is False module_builder_configs = module_factory_result.builder_configs_parameters.builder_configs assert module_builder_configs is not None assert len(module_builder_configs) == 2 module_builder_config_v1, module_builder_config_v2 = module_builder_configs assert module_builder_config_v1.name == "v1" assert module_builder_config_v2.name == "v2" assert isinstance(module_builder_config_v1, AudioFolderConfig) assert isinstance(module_builder_config_v2, AudioFolderConfig) assert isinstance(module_builder_config_v1.data_files, DataFilesDict) assert isinstance(module_builder_config_v2.data_files, DataFilesDict) assert sorted(module_builder_config_v1.data_files) == ["test", "train"] assert len(module_builder_config_v1.data_files["train"]) == 3 assert len(module_builder_config_v1.data_files["test"]) == 3 assert sorted(module_builder_config_v2.data_files) == ["test", "train"] assert len(module_builder_config_v2.data_files["train"]) == 2 assert len(module_builder_config_v2.data_files["test"]) == 1 assert module_builder_config_v1.drop_labels is True # parameter is passed from metadata assert module_builder_config_v2.drop_labels is False # parameter is passed from metadata # we don't pass config params to builder in builder_kwargs, they are stored in builder_configs directly assert "drop_labels" not in module_factory_result.builder_kwargs if dataset_name == SAMPLE_DATASET_TWO_CONFIG_IN_METADATA_WITH_DEFAULT: assert module_factory_result.builder_configs_parameters.default_config_name == "v1" else: assert module_factory_result.builder_configs_parameters.default_config_name is None @pytest.mark.integration def test_HubDatasetModuleFactoryWithScript(self): factory = HubDatasetModuleFactoryWithScript( SAMPLE_DATASET_IDENTIFIER, download_config=self.download_config, dynamic_modules_path=self.dynamic_modules_path, ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None assert module_factory_result.builder_kwargs["base_path"].startswith(config.HF_ENDPOINT) def test_CachedDatasetModuleFactory(self): path = os.path.join(self._dataset_loading_script_dir, f"{DATASET_LOADING_SCRIPT_NAME}.py") factory = LocalDatasetModuleFactoryWithScript( path, download_config=self.download_config, dynamic_modules_path=self.dynamic_modules_path ) module_factory_result = factory.get_module() for offline_mode in OfflineSimulationMode: with offline(offline_mode): factory = CachedDatasetModuleFactory( DATASET_LOADING_SCRIPT_NAME, dynamic_modules_path=self.dynamic_modules_path, ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None @pytest.mark.filterwarnings("ignore:LocalMetricModuleFactory is deprecated:FutureWarning") @pytest.mark.filterwarnings("ignore:CachedMetricModuleFactory is deprecated:FutureWarning") def test_CachedMetricModuleFactory(self): path = os.path.join(self._metric_loading_script_dir, f"{METRIC_LOADING_SCRIPT_NAME}.py") factory = LocalMetricModuleFactory( path, download_config=self.download_config, dynamic_modules_path=self.dynamic_modules_path ) module_factory_result = factory.get_module() for offline_mode in OfflineSimulationMode: with offline(offline_mode): factory = CachedMetricModuleFactory( METRIC_LOADING_SCRIPT_NAME, dynamic_modules_path=self.dynamic_modules_path, ) module_factory_result = factory.get_module() assert importlib.import_module(module_factory_result.module_path) is not None @pytest.mark.parametrize( "factory_class", [ CachedDatasetModuleFactory, CachedMetricModuleFactory, GithubMetricModuleFactory, HubDatasetModuleFactoryWithoutScript, HubDatasetModuleFactoryWithScript, LocalDatasetModuleFactoryWithoutScript, LocalDatasetModuleFactoryWithScript, LocalMetricModuleFactory, PackagedDatasetModuleFactory, ], ) def test_module_factories(factory_class): name = "dummy_name" factory = factory_class(name) assert factory.name == name @pytest.mark.integration class LoadTest(TestCase): @pytest.fixture(autouse=True) def inject_fixtures(self, caplog): self._caplog = caplog def setUp(self): self.hf_modules_cache = tempfile.mkdtemp() self.dynamic_modules_path = datasets.load.init_dynamic_modules( name="test_datasets_modules2", hf_modules_cache=self.hf_modules_cache ) def tearDown(self): shutil.rmtree(self.hf_modules_cache) def _dummy_module_dir(self, modules_dir, dummy_module_name, dummy_code): assert dummy_module_name.startswith("__") module_dir = os.path.join(modules_dir, dummy_module_name) os.makedirs(module_dir, exist_ok=True) module_path = os.path.join(module_dir, dummy_module_name + ".py") with open(module_path, "w") as f: f.write(dummy_code) return module_dir def test_dataset_module_factory(self): with tempfile.TemporaryDirectory() as tmp_dir: # prepare module from directory path dummy_code = "MY_DUMMY_VARIABLE = 'hello there'" module_dir = self._dummy_module_dir(tmp_dir, "__dummy_module_name1__", dummy_code) dataset_module = datasets.load.dataset_module_factory( module_dir, dynamic_modules_path=self.dynamic_modules_path ) dummy_module = importlib.import_module(dataset_module.module_path) self.assertEqual(dummy_module.MY_DUMMY_VARIABLE, "hello there") self.assertEqual(dataset_module.hash, sha256(dummy_code.encode("utf-8")).hexdigest()) # prepare module from file path + check resolved_file_path dummy_code = "MY_DUMMY_VARIABLE = 'general kenobi'" module_dir = self._dummy_module_dir(tmp_dir, "__dummy_module_name1__", dummy_code) module_path = os.path.join(module_dir, "__dummy_module_name1__.py") dataset_module = datasets.load.dataset_module_factory( module_path, dynamic_modules_path=self.dynamic_modules_path ) dummy_module = importlib.import_module(dataset_module.module_path) self.assertEqual(dummy_module.MY_DUMMY_VARIABLE, "general kenobi") self.assertEqual(dataset_module.hash, sha256(dummy_code.encode("utf-8")).hexdigest()) # missing module for offline_simulation_mode in list(OfflineSimulationMode): with offline(offline_simulation_mode): with self.assertRaises((FileNotFoundError, ConnectionError, requests.exceptions.ConnectionError)): datasets.load.dataset_module_factory( "__missing_dummy_module_name__", dynamic_modules_path=self.dynamic_modules_path ) def test_offline_dataset_module_factory(self): with tempfile.TemporaryDirectory() as tmp_dir: dummy_code = "MY_DUMMY_VARIABLE = 'hello there'" module_dir = self._dummy_module_dir(tmp_dir, "__dummy_module_name2__", dummy_code) dataset_module_1 = datasets.load.dataset_module_factory( module_dir, dynamic_modules_path=self.dynamic_modules_path ) time.sleep(0.1) # make sure there's a difference in the OS update time of the python file dummy_code = "MY_DUMMY_VARIABLE = 'general kenobi'" module_dir = self._dummy_module_dir(tmp_dir, "__dummy_module_name2__", dummy_code) dataset_module_2 = datasets.load.dataset_module_factory( module_dir, dynamic_modules_path=self.dynamic_modules_path ) for offline_simulation_mode in list(OfflineSimulationMode): with offline(offline_simulation_mode): self._caplog.clear() # allow provide the module name without an explicit path to remote or local actual file dataset_module_3 = datasets.load.dataset_module_factory( "__dummy_module_name2__", dynamic_modules_path=self.dynamic_modules_path ) # it loads the most recent version of the module self.assertEqual(dataset_module_2.module_path, dataset_module_3.module_path) self.assertNotEqual(dataset_module_1.module_path, dataset_module_3.module_path) self.assertIn("Using the latest cached version of the module", self._caplog.text) def test_load_dataset_from_hub(self): with self.assertRaises(FileNotFoundError) as context: datasets.load_dataset("_dummy") self.assertIn( "Dataset '_dummy' doesn't exist on the Hub", str(context.exception), ) with self.assertRaises(FileNotFoundError) as context: datasets.load_dataset("_dummy", revision="0.0.0") self.assertIn( "Dataset '_dummy' doesn't exist on the Hub", str(context.exception), ) self.assertIn( "at revision '0.0.0'", str(context.exception), ) for offline_simulation_mode in list(OfflineSimulationMode): with offline(offline_simulation_mode): with self.assertRaises(ConnectionError) as context: datasets.load_dataset("_dummy") if offline_simulation_mode != OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: self.assertIn( "Couldn't reach '_dummy' on the Hub", str(context.exception), ) def test_load_dataset_users(self): with self.assertRaises(FileNotFoundError) as context: datasets.load_dataset("lhoestq/_dummy") self.assertIn( "lhoestq/_dummy", str(context.exception), ) for offline_simulation_mode in list(OfflineSimulationMode): with offline(offline_simulation_mode): with self.assertRaises(ConnectionError) as context: datasets.load_dataset("lhoestq/_dummy") self.assertIn("lhoestq/_dummy", str(context.exception), msg=offline_simulation_mode) @pytest.mark.integration def test_load_dataset_builder_with_metadata(): builder = datasets.load_dataset_builder(SAMPLE_DATASET_IDENTIFIER4) assert isinstance(builder, ImageFolder) assert builder.config.name == "default" assert builder.config.data_files is not None assert builder.config.drop_metadata is None builder = datasets.load_dataset_builder(SAMPLE_DATASET_IDENTIFIER4, "non-existing-config") assert isinstance(builder, ImageFolder) assert builder.config.name == "non-existing-config" @pytest.mark.integration def test_load_dataset_builder_config_kwargs_passed_as_arguments(): builder_default = datasets.load_dataset_builder(SAMPLE_DATASET_IDENTIFIER4) builder_custom = datasets.load_dataset_builder(SAMPLE_DATASET_IDENTIFIER4, drop_metadata=True) assert builder_custom.config.drop_metadata != builder_default.config.drop_metadata assert builder_custom.config.drop_metadata is True @pytest.mark.integration def test_load_dataset_builder_with_two_configs_in_metadata(): builder = datasets.load_dataset_builder(SAMPLE_DATASET_TWO_CONFIG_IN_METADATA, "v1") assert isinstance(builder, AudioFolder) assert builder.config.name == "v1" assert builder.config.data_files is not None with pytest.raises(ValueError): datasets.load_dataset_builder(SAMPLE_DATASET_TWO_CONFIG_IN_METADATA) with pytest.raises(ValueError): datasets.load_dataset_builder(SAMPLE_DATASET_TWO_CONFIG_IN_METADATA, "non-existing-config") @pytest.mark.parametrize("serializer", [pickle, dill]) def test_load_dataset_builder_with_metadata_configs_pickable(serializer): builder = datasets.load_dataset_builder(SAMPLE_DATASET_SINGLE_CONFIG_IN_METADATA) builder_unpickled = serializer.loads(serializer.dumps(builder)) assert builder.BUILDER_CONFIGS == builder_unpickled.BUILDER_CONFIGS assert list(builder_unpickled.builder_configs) == ["custom"] assert isinstance(builder_unpickled.builder_configs["custom"], AudioFolderConfig) builder2 = datasets.load_dataset_builder(SAMPLE_DATASET_TWO_CONFIG_IN_METADATA, "v1") builder2_unpickled = serializer.loads(serializer.dumps(builder2)) assert builder2.BUILDER_CONFIGS == builder2_unpickled.BUILDER_CONFIGS != builder_unpickled.BUILDER_CONFIGS assert list(builder2_unpickled.builder_configs) == ["v1", "v2"] assert isinstance(builder2_unpickled.builder_configs["v1"], AudioFolderConfig) assert isinstance(builder2_unpickled.builder_configs["v2"], AudioFolderConfig) def test_load_dataset_builder_for_absolute_script_dir(dataset_loading_script_dir, data_dir): builder = datasets.load_dataset_builder(dataset_loading_script_dir, data_dir=data_dir) assert isinstance(builder, DatasetBuilder) assert builder.name == DATASET_LOADING_SCRIPT_NAME assert builder.dataset_name == DATASET_LOADING_SCRIPT_NAME assert builder.info.features == Features({"text": Value("string")}) def test_load_dataset_builder_for_relative_script_dir(dataset_loading_script_dir, data_dir): with set_current_working_directory_to_temp_dir(): relative_script_dir = DATASET_LOADING_SCRIPT_NAME shutil.copytree(dataset_loading_script_dir, relative_script_dir) builder = datasets.load_dataset_builder(relative_script_dir, data_dir=data_dir) assert isinstance(builder, DatasetBuilder) assert builder.name == DATASET_LOADING_SCRIPT_NAME assert builder.dataset_name == DATASET_LOADING_SCRIPT_NAME assert builder.info.features == Features({"text": Value("string")}) def test_load_dataset_builder_for_script_path(dataset_loading_script_dir, data_dir): builder = datasets.load_dataset_builder( os.path.join(dataset_loading_script_dir, DATASET_LOADING_SCRIPT_NAME + ".py"), data_dir=data_dir ) assert isinstance(builder, DatasetBuilder) assert builder.name == DATASET_LOADING_SCRIPT_NAME assert builder.dataset_name == DATASET_LOADING_SCRIPT_NAME assert builder.info.features == Features({"text": Value("string")}) def test_load_dataset_builder_for_absolute_data_dir(complex_data_dir): builder = datasets.load_dataset_builder(complex_data_dir) assert isinstance(builder, DatasetBuilder) assert builder.name == "text" assert builder.dataset_name == Path(complex_data_dir).name assert builder.config.name == "default" assert isinstance(builder.config.data_files, DataFilesDict) assert len(builder.config.data_files["train"]) > 0 assert len(builder.config.data_files["test"]) > 0 def test_load_dataset_builder_for_relative_data_dir(complex_data_dir): with set_current_working_directory_to_temp_dir(): relative_data_dir = "relative_data_dir" shutil.copytree(complex_data_dir, relative_data_dir) builder = datasets.load_dataset_builder(relative_data_dir) assert isinstance(builder, DatasetBuilder) assert builder.name == "text" assert builder.dataset_name == relative_data_dir assert builder.config.name == "default" assert isinstance(builder.config.data_files, DataFilesDict) assert len(builder.config.data_files["train"]) > 0 assert len(builder.config.data_files["test"]) > 0 @pytest.mark.integration def test_load_dataset_builder_for_community_dataset_with_script(): builder = datasets.load_dataset_builder(SAMPLE_DATASET_IDENTIFIER) assert isinstance(builder, DatasetBuilder) assert builder.name == SAMPLE_DATASET_IDENTIFIER.split("/")[-1] assert builder.dataset_name == SAMPLE_DATASET_IDENTIFIER.split("/")[-1] assert builder.config.name == "default" assert builder.info.features == Features({"text": Value("string")}) namespace = SAMPLE_DATASET_IDENTIFIER[: SAMPLE_DATASET_IDENTIFIER.index("/")] assert builder._relative_data_dir().startswith(namespace) assert SAMPLE_DATASET_IDENTIFIER.replace("/", "--") in builder.__module__ @pytest.mark.integration def test_load_dataset_builder_for_community_dataset_without_script(): builder = datasets.load_dataset_builder(SAMPLE_DATASET_IDENTIFIER2) assert isinstance(builder, DatasetBuilder) assert builder.name == "text" assert builder.dataset_name == SAMPLE_DATASET_IDENTIFIER2.split("/")[-1] assert builder.config.name == "default" assert isinstance(builder.config.data_files, DataFilesDict) assert len(builder.config.data_files["train"]) > 0 assert len(builder.config.data_files["test"]) > 0 def test_load_dataset_builder_fail(): with pytest.raises(FileNotFoundError): datasets.load_dataset_builder("blabla") @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_load_dataset_local(dataset_loading_script_dir, data_dir, keep_in_memory, caplog): with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = load_dataset(dataset_loading_script_dir, data_dir=data_dir, keep_in_memory=keep_in_memory) assert isinstance(dataset, DatasetDict) assert all(isinstance(d, Dataset) for d in dataset.values()) assert len(dataset) == 2 assert isinstance(next(iter(dataset["train"])), dict) for offline_simulation_mode in list(OfflineSimulationMode): with offline(offline_simulation_mode): caplog.clear() # Load dataset from cache dataset = datasets.load_dataset(DATASET_LOADING_SCRIPT_NAME, data_dir=data_dir) assert len(dataset) == 2 assert "Using the latest cached version of the module" in caplog.text with pytest.raises(FileNotFoundError) as exc_info: datasets.load_dataset(SAMPLE_DATASET_NAME_THAT_DOESNT_EXIST) assert f"Dataset '{SAMPLE_DATASET_NAME_THAT_DOESNT_EXIST}' doesn't exist on the Hub" in str(exc_info.value) assert os.path.abspath(SAMPLE_DATASET_NAME_THAT_DOESNT_EXIST) in str(exc_info.value) def test_load_dataset_streaming(dataset_loading_script_dir, data_dir): dataset = load_dataset(dataset_loading_script_dir, streaming=True, data_dir=data_dir) assert isinstance(dataset, IterableDatasetDict) assert all(isinstance(d, IterableDataset) for d in dataset.values()) assert len(dataset) == 2 assert isinstance(next(iter(dataset["train"])), dict) def test_load_dataset_streaming_gz_json(jsonl_gz_path): data_files = jsonl_gz_path ds = load_dataset("json", split="train", data_files=data_files, streaming=True) assert isinstance(ds, IterableDataset) ds_item = next(iter(ds)) assert ds_item == {"col_1": "0", "col_2": 0, "col_3": 0.0} @pytest.mark.integration @pytest.mark.parametrize( "path", ["sample.jsonl", "sample.jsonl.gz", "sample.tar", "sample.jsonl.xz", "sample.zip", "sample.jsonl.zst"] ) def test_load_dataset_streaming_compressed_files(path): repo_id = "albertvillanova/datasets-tests-compression" data_files = f"https://huggingface.co/datasets/{repo_id}/resolve/main/{path}" if data_files[-3:] in ("zip", "tar"): # we need to glob "*" inside archives data_files = data_files[-3:] + "://*::" + data_files return # TODO(QL, albert): support re-add support for ZIP and TAR archives streaming ds = load_dataset("json", split="train", data_files=data_files, streaming=True) assert isinstance(ds, IterableDataset) ds_item = next(iter(ds)) assert ds_item == { "tokens": ["Ministeri", "de", "Justícia", "d'Espanya"], "ner_tags": [1, 2, 2, 2], "langs": ["ca", "ca", "ca", "ca"], "spans": ["PER: Ministeri de Justícia d'Espanya"], } @pytest.mark.parametrize("path_extension", ["csv", "csv.bz2"]) @pytest.mark.parametrize("streaming", [False, True]) def test_load_dataset_streaming_csv(path_extension, streaming, csv_path, bz2_csv_path): paths = {"csv": csv_path, "csv.bz2": bz2_csv_path} data_files = str(paths[path_extension]) features = Features({"col_1": Value("string"), "col_2": Value("int32"), "col_3": Value("float32")}) ds = load_dataset("csv", split="train", data_files=data_files, features=features, streaming=streaming) assert isinstance(ds, IterableDataset if streaming else Dataset) ds_item = next(iter(ds)) assert ds_item == {"col_1": "0", "col_2": 0, "col_3": 0.0} @pytest.mark.parametrize("streaming", [False, True]) @pytest.mark.parametrize("data_file", ["zip_csv_path", "zip_csv_with_dir_path", "csv_path"]) def test_load_dataset_zip_csv(data_file, streaming, zip_csv_path, zip_csv_with_dir_path, csv_path): data_file_paths = { "zip_csv_path": zip_csv_path, "zip_csv_with_dir_path": zip_csv_with_dir_path, "csv_path": csv_path, } data_files = str(data_file_paths[data_file]) expected_size = 8 if data_file.startswith("zip") else 4 features = Features({"col_1": Value("string"), "col_2": Value("int32"), "col_3": Value("float32")}) ds = load_dataset("csv", split="train", data_files=data_files, features=features, streaming=streaming) if streaming: ds_item_counter = 0 for ds_item in ds: if ds_item_counter == 0: assert ds_item == {"col_1": "0", "col_2": 0, "col_3": 0.0} ds_item_counter += 1 assert ds_item_counter == expected_size else: assert ds.shape[0] == expected_size ds_item = next(iter(ds)) assert ds_item == {"col_1": "0", "col_2": 0, "col_3": 0.0} @pytest.mark.parametrize("streaming", [False, True]) @pytest.mark.parametrize("data_file", ["zip_jsonl_path", "zip_jsonl_with_dir_path", "jsonl_path"]) def test_load_dataset_zip_jsonl(data_file, streaming, zip_jsonl_path, zip_jsonl_with_dir_path, jsonl_path): data_file_paths = { "zip_jsonl_path": zip_jsonl_path, "zip_jsonl_with_dir_path": zip_jsonl_with_dir_path, "jsonl_path": jsonl_path, } data_files = str(data_file_paths[data_file]) expected_size = 8 if data_file.startswith("zip") else 4 features = Features({"col_1": Value("string"), "col_2": Value("int32"), "col_3": Value("float32")}) ds = load_dataset("json", split="train", data_files=data_files, features=features, streaming=streaming) if streaming: ds_item_counter = 0 for ds_item in ds: if ds_item_counter == 0: assert ds_item == {"col_1": "0", "col_2": 0, "col_3": 0.0} ds_item_counter += 1 assert ds_item_counter == expected_size else: assert ds.shape[0] == expected_size ds_item = next(iter(ds)) assert ds_item == {"col_1": "0", "col_2": 0, "col_3": 0.0} @pytest.mark.parametrize("streaming", [False, True]) @pytest.mark.parametrize("data_file", ["zip_text_path", "zip_text_with_dir_path", "text_path"]) def test_load_dataset_zip_text(data_file, streaming, zip_text_path, zip_text_with_dir_path, text_path): data_file_paths = { "zip_text_path": zip_text_path, "zip_text_with_dir_path": zip_text_with_dir_path, "text_path": text_path, } data_files = str(data_file_paths[data_file]) expected_size = 8 if data_file.startswith("zip") else 4 ds = load_dataset("text", split="train", data_files=data_files, streaming=streaming) if streaming: ds_item_counter = 0 for ds_item in ds: if ds_item_counter == 0: assert ds_item == {"text": "0"} ds_item_counter += 1 assert ds_item_counter == expected_size else: assert ds.shape[0] == expected_size ds_item = next(iter(ds)) assert ds_item == {"text": "0"} @pytest.mark.parametrize("streaming", [False, True]) def test_load_dataset_arrow(streaming, data_dir_with_arrow): ds = load_dataset("arrow", split="train", data_dir=data_dir_with_arrow, streaming=streaming) expected_size = 10 if streaming: ds_item_counter = 0 for ds_item in ds: if ds_item_counter == 0: assert ds_item == {"col_1": "foo"} ds_item_counter += 1 assert ds_item_counter == 10 else: assert ds.num_rows == 10 assert ds.shape[0] == expected_size ds_item = next(iter(ds)) assert ds_item == {"col_1": "foo"} def test_load_dataset_text_with_unicode_new_lines(text_path_with_unicode_new_lines): data_files = str(text_path_with_unicode_new_lines) ds = load_dataset("text", split="train", data_files=data_files) assert ds.num_rows == 3 def test_load_dataset_with_unsupported_extensions(text_dir_with_unsupported_extension): data_files = str(text_dir_with_unsupported_extension) ds = load_dataset("text", split="train", data_files=data_files) assert ds.num_rows == 4 @pytest.mark.integration def test_loading_from_the_datasets_hub(): with tempfile.TemporaryDirectory() as tmp_dir: dataset = load_dataset(SAMPLE_DATASET_IDENTIFIER, cache_dir=tmp_dir) assert len(dataset["train"]) == 2 assert len(dataset["validation"]) == 3 del dataset @pytest.mark.integration def test_loading_from_the_datasets_hub_with_token(): true_request = requests.Session().request def assert_auth(method, url, *args, headers, **kwargs): assert headers["authorization"] == "Bearer foo" return true_request(method, url, *args, headers=headers, **kwargs) with patch("requests.Session.request") as mock_request: mock_request.side_effect = assert_auth with tempfile.TemporaryDirectory() as tmp_dir: with offline(): with pytest.raises((ConnectionError, requests.exceptions.ConnectionError)): load_dataset(SAMPLE_NOT_EXISTING_DATASET_IDENTIFIER, cache_dir=tmp_dir, token="foo") mock_request.assert_called() @pytest.mark.integration def test_load_streaming_private_dataset(hf_token, hf_private_dataset_repo_txt_data): ds = load_dataset(hf_private_dataset_repo_txt_data, streaming=True, token=hf_token) assert next(iter(ds)) is not None @pytest.mark.integration def test_load_dataset_builder_private_dataset(hf_token, hf_private_dataset_repo_txt_data): builder = load_dataset_builder(hf_private_dataset_repo_txt_data, token=hf_token) assert isinstance(builder, DatasetBuilder) @pytest.mark.integration def test_load_streaming_private_dataset_with_zipped_data(hf_token, hf_private_dataset_repo_zipped_txt_data): ds = load_dataset(hf_private_dataset_repo_zipped_txt_data, streaming=True, token=hf_token) assert next(iter(ds)) is not None @pytest.mark.integration def test_load_dataset_config_kwargs_passed_as_arguments(): ds_default = load_dataset(SAMPLE_DATASET_IDENTIFIER4) ds_custom = load_dataset(SAMPLE_DATASET_IDENTIFIER4, drop_metadata=True) assert list(ds_default["train"].features) == ["image", "caption"] assert list(ds_custom["train"].features) == ["image"] @require_sndfile @pytest.mark.integration def test_load_hub_dataset_without_script_with_single_config_in_metadata(): # load the same dataset but with no configurations (=with default parameters) ds = load_dataset(SAMPLE_DATASET_NO_CONFIGS_IN_METADATA) assert list(ds["train"].features) == ["audio", "label"] # assert label feature is here as expected by default assert len(ds["train"]) == 5 and len(ds["test"]) == 4 ds2 = load_dataset(SAMPLE_DATASET_SINGLE_CONFIG_IN_METADATA) # single config -> no need to specify it assert list(ds2["train"].features) == ["audio"] # assert param `drop_labels=True` from metadata is passed assert len(ds2["train"]) == 3 and len(ds2["test"]) == 3 ds3 = load_dataset(SAMPLE_DATASET_SINGLE_CONFIG_IN_METADATA, "custom") assert list(ds3["train"].features) == ["audio"] # assert param `drop_labels=True` from metadata is passed assert len(ds3["train"]) == 3 and len(ds3["test"]) == 3 with pytest.raises(ValueError): # no config named "default" _ = load_dataset(SAMPLE_DATASET_SINGLE_CONFIG_IN_METADATA, "default") @require_sndfile @pytest.mark.integration def test_load_hub_dataset_without_script_with_two_config_in_metadata(): ds = load_dataset(SAMPLE_DATASET_TWO_CONFIG_IN_METADATA, "v1") assert list(ds["train"].features) == ["audio"] # assert param `drop_labels=True` from metadata is passed assert len(ds["train"]) == 3 and len(ds["test"]) == 3 ds2 = load_dataset(SAMPLE_DATASET_TWO_CONFIG_IN_METADATA, "v2") assert list(ds2["train"].features) == [ "audio", "label", ] # assert param `drop_labels=False` from metadata is passed assert len(ds2["train"]) == 2 and len(ds2["test"]) == 1 with pytest.raises(ValueError): # config is required but not specified _ = load_dataset(SAMPLE_DATASET_TWO_CONFIG_IN_METADATA) with pytest.raises(ValueError): # no config named "default" _ = load_dataset(SAMPLE_DATASET_TWO_CONFIG_IN_METADATA, "default") ds_with_default = load_dataset(SAMPLE_DATASET_TWO_CONFIG_IN_METADATA_WITH_DEFAULT) # it's a dataset with the same data but "v1" config is marked as a default one assert list(ds_with_default["train"].features) == list(ds["train"].features) assert len(ds_with_default["train"]) == len(ds["train"]) and len(ds_with_default["test"]) == len(ds["test"]) @require_sndfile @pytest.mark.integration def test_load_hub_dataset_without_script_with_metadata_config_in_parallel(): # assert it doesn't fail (pickling of dynamically created class works) ds = load_dataset(SAMPLE_DATASET_SINGLE_CONFIG_IN_METADATA, num_proc=2) assert "label" not in ds["train"].features # assert param `drop_labels=True` from metadata is passed assert len(ds["train"]) == 3 and len(ds["test"]) == 3 ds = load_dataset(SAMPLE_DATASET_TWO_CONFIG_IN_METADATA, "v1", num_proc=2) assert "label" not in ds["train"].features # assert param `drop_labels=True` from metadata is passed assert len(ds["train"]) == 3 and len(ds["test"]) == 3 ds = load_dataset(SAMPLE_DATASET_TWO_CONFIG_IN_METADATA, "v2", num_proc=2) assert "label" in ds["train"].features assert len(ds["train"]) == 2 and len(ds["test"]) == 1 @require_pil @pytest.mark.integration @pytest.mark.parametrize("streaming", [True]) def test_load_dataset_private_zipped_images(hf_private_dataset_repo_zipped_img_data, hf_token, streaming): ds = load_dataset(hf_private_dataset_repo_zipped_img_data, split="train", streaming=streaming, token=hf_token) assert isinstance(ds, IterableDataset if streaming else Dataset) ds_items = list(ds) assert len(ds_items) == 2 def test_load_dataset_then_move_then_reload(dataset_loading_script_dir, data_dir, tmp_path, caplog): cache_dir1 = tmp_path / "cache1" cache_dir2 = tmp_path / "cache2" dataset = load_dataset(dataset_loading_script_dir, data_dir=data_dir, split="train", cache_dir=cache_dir1) fingerprint1 = dataset._fingerprint del dataset os.rename(cache_dir1, cache_dir2) caplog.clear() with caplog.at_level(INFO, logger=get_logger().name): dataset = load_dataset(dataset_loading_script_dir, data_dir=data_dir, split="train", cache_dir=cache_dir2) assert "Found cached dataset" in caplog.text assert dataset._fingerprint == fingerprint1, "for the caching mechanism to work, fingerprint should stay the same" dataset = load_dataset(dataset_loading_script_dir, data_dir=data_dir, split="test", cache_dir=cache_dir2) assert dataset._fingerprint != fingerprint1 def test_load_dataset_readonly(dataset_loading_script_dir, dataset_loading_script_dir_readonly, data_dir, tmp_path): cache_dir1 = tmp_path / "cache1" cache_dir2 = tmp_path / "cache2" dataset = load_dataset(dataset_loading_script_dir, data_dir=data_dir, split="train", cache_dir=cache_dir1) fingerprint1 = dataset._fingerprint del dataset # Load readonly dataset and check that the fingerprint is the same. dataset = load_dataset(dataset_loading_script_dir_readonly, data_dir=data_dir, split="train", cache_dir=cache_dir2) assert dataset._fingerprint == fingerprint1, "Cannot load a dataset in a readonly folder." @pytest.mark.parametrize("max_in_memory_dataset_size", ["default", 0, 50, 500]) def test_load_dataset_local_with_default_in_memory( max_in_memory_dataset_size, dataset_loading_script_dir, data_dir, monkeypatch ): current_dataset_size = 148 if max_in_memory_dataset_size == "default": max_in_memory_dataset_size = 0 # default else: monkeypatch.setattr(datasets.config, "IN_MEMORY_MAX_SIZE", max_in_memory_dataset_size) if max_in_memory_dataset_size: expected_in_memory = current_dataset_size < max_in_memory_dataset_size else: expected_in_memory = False with assert_arrow_memory_increases() if expected_in_memory else assert_arrow_memory_doesnt_increase(): dataset = load_dataset(dataset_loading_script_dir, data_dir=data_dir) assert (dataset["train"].dataset_size < max_in_memory_dataset_size) is expected_in_memory @pytest.mark.parametrize("max_in_memory_dataset_size", ["default", 0, 100, 1000]) def test_load_from_disk_with_default_in_memory( max_in_memory_dataset_size, dataset_loading_script_dir, data_dir, tmp_path, monkeypatch ): current_dataset_size = 512 # arrow file size = 512, in-memory dataset size = 148 if max_in_memory_dataset_size == "default": max_in_memory_dataset_size = 0 # default else: monkeypatch.setattr(datasets.config, "IN_MEMORY_MAX_SIZE", max_in_memory_dataset_size) if max_in_memory_dataset_size: expected_in_memory = current_dataset_size < max_in_memory_dataset_size else: expected_in_memory = False dset = load_dataset(dataset_loading_script_dir, data_dir=data_dir, keep_in_memory=True) dataset_path = os.path.join(tmp_path, "saved_dataset") dset.save_to_disk(dataset_path) with assert_arrow_memory_increases() if expected_in_memory else assert_arrow_memory_doesnt_increase(): _ = load_from_disk(dataset_path) @pytest.mark.integration def test_remote_data_files(): repo_id = "albertvillanova/tests-raw-jsonl" filename = "wikiann-bn-validation.jsonl" data_files = f"https://huggingface.co/datasets/{repo_id}/resolve/main/{filename}" ds = load_dataset("json", split="train", data_files=data_files, streaming=True) assert isinstance(ds, IterableDataset) ds_item = next(iter(ds)) assert ds_item.keys() == {"langs", "ner_tags", "spans", "tokens"} @pytest.mark.parametrize("deleted", [False, True]) def test_load_dataset_deletes_extracted_files(deleted, jsonl_gz_path, tmp_path): data_files = jsonl_gz_path cache_dir = tmp_path / "cache" if deleted: download_config = DownloadConfig(delete_extracted=True, cache_dir=cache_dir / "downloads") ds = load_dataset( "json", split="train", data_files=data_files, cache_dir=cache_dir, download_config=download_config ) else: # default ds = load_dataset("json", split="train", data_files=data_files, cache_dir=cache_dir) assert ds[0] == {"col_1": "0", "col_2": 0, "col_3": 0.0} assert ( [path for path in (cache_dir / "downloads" / "extracted").iterdir() if path.suffix != ".lock"] == [] ) is deleted def distributed_load_dataset(args): data_name, tmp_dir, datafiles = args dataset = load_dataset(data_name, cache_dir=tmp_dir, data_files=datafiles) return dataset def test_load_dataset_distributed(tmp_path, csv_path): num_workers = 5 args = "csv", str(tmp_path), csv_path with Pool(processes=num_workers) as pool: # start num_workers processes datasets = pool.map(distributed_load_dataset, [args] * num_workers) assert len(datasets) == num_workers assert all(len(dataset) == len(datasets[0]) > 0 for dataset in datasets) assert len(datasets[0].cache_files) > 0 assert all(dataset.cache_files == datasets[0].cache_files for dataset in datasets) def test_load_dataset_with_storage_options(mockfs): with mockfs.open("data.txt", "w") as f: f.write("Hello there\n") f.write("General Kenobi !") data_files = {"train": ["mock://data.txt"]} ds = load_dataset("text", data_files=data_files, storage_options=mockfs.storage_options) assert list(ds["train"]) == [{"text": "Hello there"}, {"text": "General Kenobi !"}] @require_pil def test_load_dataset_with_storage_options_with_decoding(mockfs, image_file): import PIL.Image filename = os.path.basename(image_file) with mockfs.open(filename, "wb") as fout: with open(image_file, "rb") as fin: fout.write(fin.read()) data_files = {"train": ["mock://" + filename]} ds = load_dataset("imagefolder", data_files=data_files, storage_options=mockfs.storage_options) assert len(ds["train"]) == 1 assert isinstance(ds["train"][0]["image"], PIL.Image.Image)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_logging.py
from unittest.mock import patch import datasets from datasets import Dataset def test_enable_disable_progress_bar(): dset = Dataset.from_dict({"col_1": [3, 2, 0, 1]}) with patch("tqdm.auto.tqdm") as mock_tqdm: datasets.disable_progress_bar() dset.map(lambda x: {"col_2": x["col_1"] + 1}) mock_tqdm.assert_not_called() mock_tqdm.reset_mock() datasets.enable_progress_bar() dset.map(lambda x: {"col_2": x["col_1"] + 1}) mock_tqdm.assert_called()
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_metadata_util.py
import re import sys import tempfile import unittest from pathlib import Path import pytest import yaml from huggingface_hub import DatasetCard, DatasetCardData from datasets.config import METADATA_CONFIGS_FIELD from datasets.utils.metadata import MetadataConfigs def _dedent(string: str) -> str: indent_level = min(re.search("^ +", t).end() if t.startswith(" ") else 0 for t in string.splitlines()) return "\n".join([line[indent_level:] for line in string.splitlines() if indent_level < len(line)]) README_YAML = """\ --- language: - zh - en task_ids: - sentiment-classification --- # Begin of markdown Some cool dataset card """ README_EMPTY_YAML = """\ --- --- # Begin of markdown Some cool dataset card """ README_NO_YAML = """\ # Begin of markdown Some cool dataset card """ README_METADATA_CONFIG_INCORRECT_FORMAT = f"""\ --- {METADATA_CONFIGS_FIELD}: data_dir: v1 drop_labels: true --- """ README_METADATA_SINGLE_CONFIG = f"""\ --- {METADATA_CONFIGS_FIELD}: - config_name: custom data_dir: v1 drop_labels: true --- """ README_METADATA_TWO_CONFIGS_WITH_DEFAULT_FLAG = f"""\ --- {METADATA_CONFIGS_FIELD}: - config_name: v1 data_dir: v1 drop_labels: true - config_name: v2 data_dir: v2 drop_labels: false default: true --- """ README_METADATA_TWO_CONFIGS_WITH_DEFAULT_NAME = f"""\ --- {METADATA_CONFIGS_FIELD}: - config_name: custom data_dir: custom drop_labels: true - config_name: default data_dir: data drop_labels: false --- """ EXPECTED_METADATA_SINGLE_CONFIG = {"custom": {"data_dir": "v1", "drop_labels": True}} EXPECTED_METADATA_TWO_CONFIGS_DEFAULT_FLAG = { "v1": {"data_dir": "v1", "drop_labels": True}, "v2": {"data_dir": "v2", "drop_labels": False, "default": True}, } EXPECTED_METADATA_TWO_CONFIGS_DEFAULT_NAME = { "custom": {"data_dir": "custom", "drop_labels": True}, "default": {"data_dir": "data", "drop_labels": False}, } @pytest.fixture def data_dir_with_two_subdirs(tmp_path): data_dir = tmp_path / "data_dir_with_two_configs_in_metadata" cats_data_dir = data_dir / "cats" cats_data_dir.mkdir(parents=True) dogs_data_dir = data_dir / "dogs" dogs_data_dir.mkdir(parents=True) with open(cats_data_dir / "cat.jpg", "wb") as f: f.write(b"this_is_a_cat_image_bytes") with open(dogs_data_dir / "dog.jpg", "wb") as f: f.write(b"this_is_a_dog_image_bytes") return str(data_dir) class TestMetadataUtils(unittest.TestCase): def test_metadata_dict_from_readme(self): with tempfile.TemporaryDirectory() as tmp_dir: path = Path(tmp_dir) / "README.md" with open(path, "w+") as readme_file: readme_file.write(README_YAML) dataset_card_data = DatasetCard.load(path).data self.assertDictEqual( dataset_card_data.to_dict(), {"language": ["zh", "en"], "task_ids": ["sentiment-classification"]} ) with open(path, "w+") as readme_file: readme_file.write(README_EMPTY_YAML) if ( sys.platform != "win32" ): # there is a bug on windows, see https://github.com/huggingface/huggingface_hub/issues/1546 dataset_card_data = DatasetCard.load(path).data self.assertDictEqual(dataset_card_data.to_dict(), {}) with open(path, "w+") as readme_file: readme_file.write(README_NO_YAML) dataset_card_data = DatasetCard.load(path).data self.assertEqual(dataset_card_data.to_dict(), {}) def test_from_yaml_string(self): valid_yaml_string = _dedent( """\ annotations_creators: - found language_creators: - found language: - en license: - unknown multilinguality: - monolingual pretty_name: Test Dataset size_categories: - 10K<n<100K source_datasets: - extended|other-yahoo-webscope-l6 task_categories: - question-answering task_ids: - open-domain-qa """ ) assert DatasetCardData(**yaml.safe_load(valid_yaml_string)).to_dict() valid_yaml_with_optional_keys = _dedent( """\ annotations_creators: - found language_creators: - found language: - en license: - unknown multilinguality: - monolingual pretty_name: Test Dataset size_categories: - 10K<n<100K source_datasets: - extended|other-yahoo-webscope-l6 task_categories: - text-classification task_ids: - multi-class-classification paperswithcode_id: - squad configs: - en train-eval-index: - config: en task: text-classification task_id: multi_class_classification splits: train_split: train eval_split: test col_mapping: text: text label: target metrics: - type: accuracy name: Accuracy extra_gated_prompt: | By clicking on “Access repository” below, you also agree to ImageNet Terms of Access: [RESEARCHER_FULLNAME] (the "Researcher") has requested permission to use the ImageNet database (the "Database") at Princeton University and Stanford University. In exchange for such permission, Researcher hereby agrees to the following terms and conditions: 1. Researcher shall use the Database only for non-commercial research and educational purposes. extra_gated_fields: Company: text Country: text I agree to use this model for non-commerical use ONLY: checkbox """ ) assert DatasetCardData(**yaml.safe_load(valid_yaml_with_optional_keys)).to_dict() @pytest.mark.parametrize( "readme_content, expected_metadata_configs_dict, expected_default_config_name", [ (README_METADATA_SINGLE_CONFIG, EXPECTED_METADATA_SINGLE_CONFIG, None), (README_METADATA_TWO_CONFIGS_WITH_DEFAULT_FLAG, EXPECTED_METADATA_TWO_CONFIGS_DEFAULT_FLAG, "v2"), (README_METADATA_TWO_CONFIGS_WITH_DEFAULT_NAME, EXPECTED_METADATA_TWO_CONFIGS_DEFAULT_NAME, "default"), ], ) def test_metadata_configs_dataset_card_data( readme_content, expected_metadata_configs_dict, expected_default_config_name ): with tempfile.TemporaryDirectory() as tmp_dir: path = Path(tmp_dir) / "README.md" with open(path, "w+") as readme_file: readme_file.write(readme_content) dataset_card_data = DatasetCard.load(path).data metadata_configs_dict = MetadataConfigs.from_dataset_card_data(dataset_card_data) assert metadata_configs_dict == expected_metadata_configs_dict assert metadata_configs_dict.get_default_config_name() == expected_default_config_name def test_metadata_configs_incorrect_yaml(): with tempfile.TemporaryDirectory() as tmp_dir: path = Path(tmp_dir) / "README.md" with open(path, "w+") as readme_file: readme_file.write(README_METADATA_CONFIG_INCORRECT_FORMAT) dataset_card_data = DatasetCard.load(path).data with pytest.raises(ValueError): _ = MetadataConfigs.from_dataset_card_data(dataset_card_data)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_metric.py
import os import pickle import tempfile import time from multiprocessing import Pool from unittest import TestCase import pytest from datasets.features import Features, Sequence, Value from datasets.metric import Metric, MetricInfo from .utils import require_tf, require_torch class DummyMetric(Metric): def _info(self): return MetricInfo( description="dummy metric for tests", citation="insert citation here", features=Features({"predictions": Value("int64"), "references": Value("int64")}), ) def _compute(self, predictions, references): return ( { "accuracy": sum(i == j for i, j in zip(predictions, references)) / len(predictions), "set_equality": set(predictions) == set(references), } if predictions else {} ) @classmethod def predictions_and_references(cls): return ([1, 2, 3, 4], [1, 2, 4, 3]) @classmethod def expected_results(cls): return {"accuracy": 0.5, "set_equality": True} @classmethod def other_predictions_and_references(cls): return ([1, 3, 4, 5], [1, 2, 3, 4]) @classmethod def other_expected_results(cls): return {"accuracy": 0.25, "set_equality": False} @classmethod def distributed_predictions_and_references(cls): return ([1, 2, 3, 4], [1, 2, 3, 4]), ([1, 2, 4, 5], [1, 2, 3, 4]) @classmethod def distributed_expected_results(cls): return {"accuracy": 0.75, "set_equality": False} @classmethod def separate_predictions_and_references(cls): return ([1, 2, 3, 4], [1, 2, 3, 4]), ([1, 2, 4, 5], [1, 2, 3, 4]) @classmethod def separate_expected_results(cls): return [{"accuracy": 1.0, "set_equality": True}, {"accuracy": 0.5, "set_equality": False}] def properly_del_metric(metric): """properly delete a metric on windows if the process is killed during multiprocessing""" if metric is not None: if metric.filelock is not None: metric.filelock.release() if metric.rendez_vous_lock is not None: metric.rendez_vous_lock.release() del metric.writer del metric.data del metric def metric_compute(arg): """Thread worker function for distributed evaluation testing. On base level to be pickable. """ metric = None try: num_process, process_id, preds, refs, exp_id, cache_dir, wait = arg metric = DummyMetric( num_process=num_process, process_id=process_id, experiment_id=exp_id, cache_dir=cache_dir, timeout=5 ) time.sleep(wait) results = metric.compute(predictions=preds, references=refs) return results finally: properly_del_metric(metric) def metric_add_batch_and_compute(arg): """Thread worker function for distributed evaluation testing. On base level to be pickable. """ metric = None try: num_process, process_id, preds, refs, exp_id, cache_dir, wait = arg metric = DummyMetric( num_process=num_process, process_id=process_id, experiment_id=exp_id, cache_dir=cache_dir, timeout=5 ) metric.add_batch(predictions=preds, references=refs) time.sleep(wait) results = metric.compute() return results finally: properly_del_metric(metric) def metric_add_and_compute(arg): """Thread worker function for distributed evaluation testing. On base level to be pickable. """ metric = None try: num_process, process_id, preds, refs, exp_id, cache_dir, wait = arg metric = DummyMetric( num_process=num_process, process_id=process_id, experiment_id=exp_id, cache_dir=cache_dir, timeout=5 ) for pred, ref in zip(preds, refs): metric.add(prediction=pred, reference=ref) time.sleep(wait) results = metric.compute() return results finally: properly_del_metric(metric) @pytest.mark.filterwarnings("ignore:Metric is deprecated:FutureWarning") class TestMetric(TestCase): def test_dummy_metric(self): preds, refs = DummyMetric.predictions_and_references() expected_results = DummyMetric.expected_results() metric = DummyMetric(experiment_id="test_dummy_metric") self.assertDictEqual(expected_results, metric.compute(predictions=preds, references=refs)) del metric metric = DummyMetric(experiment_id="test_dummy_metric") metric.add_batch(predictions=preds, references=refs) self.assertDictEqual(expected_results, metric.compute()) del metric metric = DummyMetric(experiment_id="test_dummy_metric") for pred, ref in zip(preds, refs): metric.add(prediction=pred, reference=ref) self.assertDictEqual(expected_results, metric.compute()) del metric # With keep_in_memory metric = DummyMetric(keep_in_memory=True, experiment_id="test_dummy_metric") self.assertDictEqual(expected_results, metric.compute(predictions=preds, references=refs)) del metric metric = DummyMetric(keep_in_memory=True, experiment_id="test_dummy_metric") metric.add_batch(predictions=preds, references=refs) self.assertDictEqual(expected_results, metric.compute()) del metric metric = DummyMetric(keep_in_memory=True, experiment_id="test_dummy_metric") for pred, ref in zip(preds, refs): metric.add(prediction=pred, reference=ref) self.assertDictEqual(expected_results, metric.compute()) del metric metric = DummyMetric(keep_in_memory=True, experiment_id="test_dummy_metric") self.assertDictEqual({}, metric.compute(predictions=[], references=[])) del metric metric = DummyMetric(keep_in_memory=True, experiment_id="test_dummy_metric") with self.assertRaisesRegex(ValueError, "Mismatch in the number"): metric.add_batch(predictions=[1, 2, 3], references=[1, 2, 3, 4]) del metric def test_metric_with_cache_dir(self): preds, refs = DummyMetric.predictions_and_references() expected_results = DummyMetric.expected_results() with tempfile.TemporaryDirectory() as tmp_dir: metric = DummyMetric(experiment_id="test_dummy_metric", cache_dir=tmp_dir) self.assertDictEqual(expected_results, metric.compute(predictions=preds, references=refs)) del metric def test_concurrent_metrics(self): preds, refs = DummyMetric.predictions_and_references() other_preds, other_refs = DummyMetric.other_predictions_and_references() expected_results = DummyMetric.expected_results() other_expected_results = DummyMetric.other_expected_results() metric = DummyMetric(experiment_id="test_concurrent_metrics") other_metric = DummyMetric( experiment_id="test_concurrent_metrics", ) self.assertDictEqual(expected_results, metric.compute(predictions=preds, references=refs)) self.assertDictEqual( other_expected_results, other_metric.compute(predictions=other_preds, references=other_refs) ) del metric, other_metric metric = DummyMetric( experiment_id="test_concurrent_metrics", ) other_metric = DummyMetric( experiment_id="test_concurrent_metrics", ) metric.add_batch(predictions=preds, references=refs) other_metric.add_batch(predictions=other_preds, references=other_refs) self.assertDictEqual(expected_results, metric.compute()) self.assertDictEqual(other_expected_results, other_metric.compute()) for pred, ref, other_pred, other_ref in zip(preds, refs, other_preds, other_refs): metric.add(prediction=pred, reference=ref) other_metric.add(prediction=other_pred, reference=other_ref) self.assertDictEqual(expected_results, metric.compute()) self.assertDictEqual(other_expected_results, other_metric.compute()) del metric, other_metric # With keep_in_memory metric = DummyMetric(experiment_id="test_concurrent_metrics", keep_in_memory=True) other_metric = DummyMetric(experiment_id="test_concurrent_metrics", keep_in_memory=True) self.assertDictEqual(expected_results, metric.compute(predictions=preds, references=refs)) self.assertDictEqual( other_expected_results, other_metric.compute(predictions=other_preds, references=other_refs) ) metric = DummyMetric(experiment_id="test_concurrent_metrics", keep_in_memory=True) other_metric = DummyMetric(experiment_id="test_concurrent_metrics", keep_in_memory=True) metric.add_batch(predictions=preds, references=refs) other_metric.add_batch(predictions=other_preds, references=other_refs) self.assertDictEqual(expected_results, metric.compute()) self.assertDictEqual(other_expected_results, other_metric.compute()) for pred, ref, other_pred, other_ref in zip(preds, refs, other_preds, other_refs): metric.add(prediction=pred, reference=ref) other_metric.add(prediction=other_pred, reference=other_ref) self.assertDictEqual(expected_results, metric.compute()) self.assertDictEqual(other_expected_results, other_metric.compute()) del metric, other_metric def test_separate_experiments_in_parallel(self): with tempfile.TemporaryDirectory() as tmp_dir: (preds_0, refs_0), (preds_1, refs_1) = DummyMetric.separate_predictions_and_references() expected_results = DummyMetric.separate_expected_results() pool = Pool(processes=4) results = pool.map( metric_compute, [ (1, 0, preds_0, refs_0, None, tmp_dir, 0), (1, 0, preds_1, refs_1, None, tmp_dir, 0), ], ) self.assertDictEqual(expected_results[0], results[0]) self.assertDictEqual(expected_results[1], results[1]) del results # more than one sec of waiting so that the second metric has to sample a new hashing name results = pool.map( metric_compute, [ (1, 0, preds_0, refs_0, None, tmp_dir, 2), (1, 0, preds_1, refs_1, None, tmp_dir, 2), ], ) self.assertDictEqual(expected_results[0], results[0]) self.assertDictEqual(expected_results[1], results[1]) del results results = pool.map( metric_add_and_compute, [ (1, 0, preds_0, refs_0, None, tmp_dir, 0), (1, 0, preds_1, refs_1, None, tmp_dir, 0), ], ) self.assertDictEqual(expected_results[0], results[0]) self.assertDictEqual(expected_results[1], results[1]) del results results = pool.map( metric_add_batch_and_compute, [ (1, 0, preds_0, refs_0, None, tmp_dir, 0), (1, 0, preds_1, refs_1, None, tmp_dir, 0), ], ) self.assertDictEqual(expected_results[0], results[0]) self.assertDictEqual(expected_results[1], results[1]) del results def test_distributed_metrics(self): with tempfile.TemporaryDirectory() as tmp_dir: (preds_0, refs_0), (preds_1, refs_1) = DummyMetric.distributed_predictions_and_references() expected_results = DummyMetric.distributed_expected_results() pool = Pool(processes=4) results = pool.map( metric_compute, [ (2, 0, preds_0, refs_0, "test_distributed_metrics_0", tmp_dir, 0), (2, 1, preds_1, refs_1, "test_distributed_metrics_0", tmp_dir, 0.5), ], ) self.assertDictEqual(expected_results, results[0]) self.assertIsNone(results[1]) del results results = pool.map( metric_compute, [ (2, 0, preds_0, refs_0, "test_distributed_metrics_0", tmp_dir, 0.5), (2, 1, preds_1, refs_1, "test_distributed_metrics_0", tmp_dir, 0), ], ) self.assertDictEqual(expected_results, results[0]) self.assertIsNone(results[1]) del results results = pool.map( metric_add_and_compute, [ (2, 0, preds_0, refs_0, "test_distributed_metrics_1", tmp_dir, 0), (2, 1, preds_1, refs_1, "test_distributed_metrics_1", tmp_dir, 0), ], ) self.assertDictEqual(expected_results, results[0]) self.assertIsNone(results[1]) del results results = pool.map( metric_add_batch_and_compute, [ (2, 0, preds_0, refs_0, "test_distributed_metrics_2", tmp_dir, 0), (2, 1, preds_1, refs_1, "test_distributed_metrics_2", tmp_dir, 0), ], ) self.assertDictEqual(expected_results, results[0]) self.assertIsNone(results[1]) del results # To use several distributed metrics on the same local file system, need to specify an experiment_id try: results = pool.map( metric_add_and_compute, [ (2, 0, preds_0, refs_0, "test_distributed_metrics_3", tmp_dir, 0), (2, 1, preds_1, refs_1, "test_distributed_metrics_3", tmp_dir, 0), (2, 0, preds_0, refs_0, "test_distributed_metrics_3", tmp_dir, 0), (2, 1, preds_1, refs_1, "test_distributed_metrics_3", tmp_dir, 0), ], ) except ValueError: # We are fine with either raising a ValueError or computing well the metric # Being sure we raise the error would means making the dummy dataset bigger # and the test longer... pass else: self.assertDictEqual(expected_results, results[0]) self.assertDictEqual(expected_results, results[2]) self.assertIsNone(results[1]) self.assertIsNone(results[3]) del results results = pool.map( metric_add_and_compute, [ (2, 0, preds_0, refs_0, "exp_0", tmp_dir, 0), (2, 1, preds_1, refs_1, "exp_0", tmp_dir, 0), (2, 0, preds_0, refs_0, "exp_1", tmp_dir, 0), (2, 1, preds_1, refs_1, "exp_1", tmp_dir, 0), ], ) self.assertDictEqual(expected_results, results[0]) self.assertDictEqual(expected_results, results[2]) self.assertIsNone(results[1]) self.assertIsNone(results[3]) del results # With keep_in_memory is not allowed with self.assertRaises(ValueError): DummyMetric( experiment_id="test_distributed_metrics_4", keep_in_memory=True, num_process=2, process_id=0, cache_dir=tmp_dir, ) def test_dummy_metric_pickle(self): with tempfile.TemporaryDirectory() as tmp_dir: tmp_file = os.path.join(tmp_dir, "metric.pt") preds, refs = DummyMetric.predictions_and_references() expected_results = DummyMetric.expected_results() metric = DummyMetric(experiment_id="test_dummy_metric_pickle") with open(tmp_file, "wb") as f: pickle.dump(metric, f) del metric with open(tmp_file, "rb") as f: metric = pickle.load(f) self.assertDictEqual(expected_results, metric.compute(predictions=preds, references=refs)) del metric def test_input_numpy(self): import numpy as np preds, refs = DummyMetric.predictions_and_references() expected_results = DummyMetric.expected_results() preds, refs = np.array(preds), np.array(refs) metric = DummyMetric(experiment_id="test_input_numpy") self.assertDictEqual(expected_results, metric.compute(predictions=preds, references=refs)) del metric metric = DummyMetric(experiment_id="test_input_numpy") metric.add_batch(predictions=preds, references=refs) self.assertDictEqual(expected_results, metric.compute()) del metric metric = DummyMetric(experiment_id="test_input_numpy") for pred, ref in zip(preds, refs): metric.add(prediction=pred, reference=ref) self.assertDictEqual(expected_results, metric.compute()) del metric @require_torch def test_input_torch(self): import torch preds, refs = DummyMetric.predictions_and_references() expected_results = DummyMetric.expected_results() preds, refs = torch.tensor(preds), torch.tensor(refs) metric = DummyMetric(experiment_id="test_input_torch") self.assertDictEqual(expected_results, metric.compute(predictions=preds, references=refs)) del metric metric = DummyMetric(experiment_id="test_input_torch") metric.add_batch(predictions=preds, references=refs) self.assertDictEqual(expected_results, metric.compute()) del metric metric = DummyMetric(experiment_id="test_input_torch") for pred, ref in zip(preds, refs): metric.add(prediction=pred, reference=ref) self.assertDictEqual(expected_results, metric.compute()) del metric @require_tf def test_input_tf(self): import tensorflow as tf preds, refs = DummyMetric.predictions_and_references() expected_results = DummyMetric.expected_results() preds, refs = tf.constant(preds), tf.constant(refs) metric = DummyMetric(experiment_id="test_input_tf") self.assertDictEqual(expected_results, metric.compute(predictions=preds, references=refs)) del metric metric = DummyMetric(experiment_id="test_input_tf") metric.add_batch(predictions=preds, references=refs) self.assertDictEqual(expected_results, metric.compute()) del metric metric = DummyMetric(experiment_id="test_input_tf") for pred, ref in zip(preds, refs): metric.add(prediction=pred, reference=ref) self.assertDictEqual(expected_results, metric.compute()) del metric class MetricWithMultiLabel(Metric): def _info(self): return MetricInfo( description="dummy metric for tests", citation="insert citation here", features=Features( {"predictions": Sequence(Value("int64")), "references": Sequence(Value("int64"))} if self.config_name == "multilabel" else {"predictions": Value("int64"), "references": Value("int64")} ), ) def _compute(self, predictions=None, references=None): return ( { "accuracy": sum(i == j for i, j in zip(predictions, references)) / len(predictions), } if predictions else {} ) @pytest.mark.parametrize( "config_name, predictions, references, expected", [ (None, [1, 2, 3, 4], [1, 2, 4, 3], 0.5), # Multiclass: Value("int64") ( "multilabel", [[1, 0], [1, 0], [1, 0], [1, 0]], [[1, 0], [0, 1], [1, 1], [0, 0]], 0.25, ), # Multilabel: Sequence(Value("int64")) ], ) def test_metric_with_multilabel(config_name, predictions, references, expected, tmp_path): cache_dir = tmp_path / "cache" metric = MetricWithMultiLabel(config_name, cache_dir=cache_dir) results = metric.compute(predictions=predictions, references=references) assert results["accuracy"] == expected def test_safety_checks_process_vars(): with pytest.raises(ValueError): _ = DummyMetric(process_id=-2) with pytest.raises(ValueError): _ = DummyMetric(num_process=2, process_id=3) class AccuracyWithNonStandardFeatureNames(Metric): def _info(self): return MetricInfo( description="dummy metric for tests", citation="insert citation here", features=Features({"inputs": Value("int64"), "targets": Value("int64")}), ) def _compute(self, inputs, targets): return ( { "accuracy": sum(i == j for i, j in zip(inputs, targets)) / len(targets), } if targets else {} ) @classmethod def inputs_and_targets(cls): return ([1, 2, 3, 4], [1, 2, 4, 3]) @classmethod def expected_results(cls): return {"accuracy": 0.5} def test_metric_with_non_standard_feature_names_add(tmp_path): cache_dir = tmp_path / "cache" inputs, targets = AccuracyWithNonStandardFeatureNames.inputs_and_targets() metric = AccuracyWithNonStandardFeatureNames(cache_dir=cache_dir) for input, target in zip(inputs, targets): metric.add(inputs=input, targets=target) results = metric.compute() assert results == AccuracyWithNonStandardFeatureNames.expected_results() def test_metric_with_non_standard_feature_names_add_batch(tmp_path): cache_dir = tmp_path / "cache" inputs, targets = AccuracyWithNonStandardFeatureNames.inputs_and_targets() metric = AccuracyWithNonStandardFeatureNames(cache_dir=cache_dir) metric.add_batch(inputs=inputs, targets=targets) results = metric.compute() assert results == AccuracyWithNonStandardFeatureNames.expected_results() def test_metric_with_non_standard_feature_names_compute(tmp_path): cache_dir = tmp_path / "cache" inputs, targets = AccuracyWithNonStandardFeatureNames.inputs_and_targets() metric = AccuracyWithNonStandardFeatureNames(cache_dir=cache_dir) results = metric.compute(inputs=inputs, targets=targets) assert results == AccuracyWithNonStandardFeatureNames.expected_results()
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_metric_common.py
# Copyright 2020 HuggingFace Inc. # # 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. import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration pytestmark = pytest.mark.integration REQUIRE_FAIRSEQ = {"comet"} _has_fairseq = importlib.util.find_spec("fairseq") is not None UNSUPPORTED_ON_WINDOWS = {"code_eval"} _on_windows = os.name == "nt" REQUIRE_TRANSFORMERS = {"bertscore", "frugalscore", "perplexity"} _has_transformers = importlib.util.find_spec("transformers") is not None def skip_if_metric_requires_fairseq(test_case): @wraps(test_case) def wrapper(self, metric_name): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('"test requires Fairseq"') else: test_case(self, metric_name) return wrapper def skip_if_metric_requires_transformers(test_case): @wraps(test_case) def wrapper(self, metric_name): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('"test requires transformers"') else: test_case(self, metric_name) return wrapper def skip_on_windows_if_not_windows_compatible(test_case): @wraps(test_case) def wrapper(self, metric_name): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('"test not supported on Windows"') else: test_case(self, metric_name) return wrapper def get_local_metric_names(): metrics = [metric_dir.split(os.sep)[-2] for metric_dir in glob.glob("./metrics/*/")] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names()) @for_all_test_methods( skip_if_metric_requires_fairseq, skip_if_metric_requires_transformers, skip_on_windows_if_not_windows_compatible ) @local class LocalMetricTest(parameterized.TestCase): INTENSIVE_CALLS_PATCHER = {} metric_name = None @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning") @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning") def test_load_metric(self, metric_name): doctest.ELLIPSIS_MARKER = "[...]" metric_module = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics", metric_name)).module_path ) metric = datasets.load.import_main_class(metric_module.__name__, dataset=False) # check parameters parameters = inspect.signature(metric._compute).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values())) # no **kwargs # run doctest with self.patch_intensive_calls(metric_name, metric_module.__name__): with self.use_local_metrics(): try: results = doctest.testmod(metric_module, verbose=True, raise_on_error=True) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed, 0) self.assertGreater(results.attempted, 1) @slow def test_load_real_metric(self, metric_name): doctest.ELLIPSIS_MARKER = "[...]" metric_module = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics", metric_name)).module_path ) # run doctest with self.use_local_metrics(): results = doctest.testmod(metric_module, verbose=True, raise_on_error=True) self.assertEqual(results.failed, 0) self.assertGreater(results.attempted, 1) @contextmanager def patch_intensive_calls(self, metric_name, module_name): if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](module_name): yield else: yield @contextmanager def use_local_metrics(self): def load_local_metric(metric_name, *args, **kwargs): return load_metric(os.path.join("metrics", metric_name), *args, **kwargs) with patch("datasets.load_metric") as mock_load_metric: mock_load_metric.side_effect = load_local_metric yield @classmethod def register_intensive_calls_patcher(cls, metric_name): def wrapper(patcher): patcher = contextmanager(patcher) cls.INTENSIVE_CALLS_PATCHER[metric_name] = patcher return patcher return wrapper # Metrics intensive calls patchers # -------------------------------- @LocalMetricTest.register_intensive_calls_patcher("bleurt") def patch_bleurt(module_name): import tensorflow.compat.v1 as tf from bleurt.score import Predictor tf.flags.DEFINE_string("sv", "", "") # handle pytest cli flags class MockedPredictor(Predictor): def predict(self, input_dict): assert len(input_dict["input_ids"]) == 2 return np.array([1.03, 1.04]) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch("bleurt.score._create_predictor") as mock_create_predictor: mock_create_predictor.return_value = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("bertscore") def patch_bertscore(module_name): import torch def bert_cos_score_idf(model, refs, *args, **kwargs): return torch.tensor([[1.0, 1.0, 1.0]] * len(refs)) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch("bert_score.scorer.get_model"), patch( "bert_score.scorer.bert_cos_score_idf" ) as mock_bert_cos_score_idf: mock_bert_cos_score_idf.side_effect = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("comet") def patch_comet(module_name): def load_from_checkpoint(model_path): class Model: def predict(self, data, *args, **kwargs): assert len(data) == 2 scores = [0.19, 0.92] return scores, sum(scores) / len(scores) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch("comet.download_model") as mock_download_model: mock_download_model.return_value = None with patch("comet.load_from_checkpoint") as mock_load_from_checkpoint: mock_load_from_checkpoint.side_effect = load_from_checkpoint yield def test_seqeval_raises_when_incorrect_scheme(): metric = load_metric(os.path.join("metrics", "seqeval")) wrong_scheme = "ERROR" error_message = f"Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}" with pytest.raises(ValueError, match=re.escape(error_message)): metric.compute(predictions=[], references=[], scheme=wrong_scheme)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_offline_util.py
import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def test_offline_with_timeout(): with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT): with pytest.raises(RequestWouldHangIndefinitelyError): requests.request("GET", "https://huggingface.co") with pytest.raises(requests.exceptions.ConnectTimeout): requests.request("GET", "https://huggingface.co", timeout=1.0) @pytest.mark.integration def test_offline_with_connection_error(): with offline(OfflineSimulationMode.CONNECTION_FAILS): with pytest.raises(requests.exceptions.ConnectionError): requests.request("GET", "https://huggingface.co") def test_offline_with_datasets_offline_mode_enabled(): with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1): with pytest.raises(ConnectionError): http_head("https://huggingface.co")
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_parallel.py
import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def add_one(i): # picklable for multiprocessing return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def test_parallel_backend_input(): with parallel_backend("spark"): assert ParallelBackendConfig.backend_name == "spark" lst = [1, 2, 3] with pytest.raises(ValueError): with parallel_backend("unsupported backend"): map_nested(add_one, lst, num_proc=2) with pytest.raises(ValueError): with parallel_backend("unsupported backend"): map_nested(add_one, lst, num_proc=-1) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("num_proc", [2, -1]) def test_parallel_backend_map_nested(num_proc): s1 = [1, 2] s2 = {"a": 1, "b": 2} s3 = {"a": [1, 2], "b": [3, 4]} s4 = {"a": {"1": 1}, "b": 2} s5 = {"a": 1, "b": 2, "c": 3, "d": 4} expected_map_nested_s1 = [2, 3] expected_map_nested_s2 = {"a": 2, "b": 3} expected_map_nested_s3 = {"a": [2, 3], "b": [4, 5]} expected_map_nested_s4 = {"a": {"1": 2}, "b": 3} expected_map_nested_s5 = {"a": 2, "b": 3, "c": 4, "d": 5} with parallel_backend("spark"): assert map_nested(add_one, s1, num_proc=num_proc) == expected_map_nested_s1 assert map_nested(add_one, s2, num_proc=num_proc) == expected_map_nested_s2 assert map_nested(add_one, s3, num_proc=num_proc) == expected_map_nested_s3 assert map_nested(add_one, s4, num_proc=num_proc) == expected_map_nested_s4 assert map_nested(add_one, s5, num_proc=num_proc) == expected_map_nested_s5
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_patching.py
from datasets.utils.patching import _PatchedModuleObj, patch_submodule from . import _test_patching def test_patch_submodule(): import os as original_os from os import path as original_path from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join mock = "__test_patch_submodule_mock__" with patch_submodule(_test_patching, "os.path.join", mock): # Every way to access os.path.join must be patched, and the rest must stay untouched # check os.path.join assert isinstance(_test_patching.os, _PatchedModuleObj) assert isinstance(_test_patching.os.path, _PatchedModuleObj) assert _test_patching.os.path.join is mock # check path.join assert isinstance(_test_patching.path, _PatchedModuleObj) assert _test_patching.path.join is mock # check join assert _test_patching.join is mock # check that the other attributes are untouched assert _test_patching.os.rename is original_rename assert _test_patching.path.dirname is original_dirname assert _test_patching.os.path.dirname is original_dirname # Even renamed modules or objects must be patched # check renamed_os.path.join assert isinstance(_test_patching.renamed_os, _PatchedModuleObj) assert isinstance(_test_patching.renamed_os.path, _PatchedModuleObj) assert _test_patching.renamed_os.path.join is mock # check renamed_path.join assert isinstance(_test_patching.renamed_path, _PatchedModuleObj) assert _test_patching.renamed_path.join is mock # check renamed_join assert _test_patching.renamed_join is mock # check that the other attributes are untouched assert _test_patching.renamed_os.rename is original_rename assert _test_patching.renamed_path.dirname is original_dirname assert _test_patching.renamed_os.path.dirname is original_dirname # check that everthing is back to normal when the patch is over assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join def test_patch_submodule_builtin(): assert _test_patching.open is open mock = "__test_patch_submodule_builtin_mock__" # _test_patching has "open" in its globals assert _test_patching.open is open with patch_submodule(_test_patching, "open", mock): assert _test_patching.open is mock # check that everthing is back to normal when the patch is over assert _test_patching.open is open def test_patch_submodule_missing(): # pandas.read_csv is not present in _test_patching mock = "__test_patch_submodule_missing_mock__" with patch_submodule(_test_patching, "pandas.read_csv", mock): pass def test_patch_submodule_missing_builtin(): # builtin should always be mocked even if they're not in the globals # in case they're loaded at one point mock = "__test_patch_submodule_missing_builtin_mock__" # _test_patching doesn't have "len" in its globals assert getattr(_test_patching, "len", None) is None with patch_submodule(_test_patching, "len", mock): assert _test_patching.len is mock assert _test_patching.len is len def test_patch_submodule_start_and_stop(): mock = "__test_patch_submodule_start_and_stop_mock__" patch = patch_submodule(_test_patching, "open", mock) assert _test_patching.open is open patch.start() assert _test_patching.open is mock patch.stop() assert _test_patching.open is open def test_patch_submodule_successive(): from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join mock_join = "__test_patch_submodule_successive_join__" mock_dirname = "__test_patch_submodule_successive_dirname__" mock_rename = "__test_patch_submodule_successive_rename__" assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename with patch_submodule(_test_patching, "os.path.join", mock_join): with patch_submodule(_test_patching, "os.rename", mock_rename): with patch_submodule(_test_patching, "os.path.dirname", mock_dirname): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename # try another order with patch_submodule(_test_patching, "os.rename", mock_rename): with patch_submodule(_test_patching, "os.path.join", mock_join): with patch_submodule(_test_patching, "os.path.dirname", mock_dirname): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename def test_patch_submodule_doesnt_exist(): mock = "__test_patch_submodule_doesnt_exist_mock__" with patch_submodule(_test_patching, "__module_that_doesn_exist__.__attribute_that_doesn_exist__", mock): pass with patch_submodule(_test_patching, "os.__attribute_that_doesn_exist__", mock): pass
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_py_utils.py
import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, temp_seed, temporary_assignment, zip_dict, ) from .utils import require_tf, require_torch def np_sum(x): # picklable for multiprocessing return x.sum() def add_one(i): # picklable for multiprocessing return i + 1 @dataclass class A: x: int y: str class PyUtilsTest(TestCase): def test_map_nested(self): s1 = {} s2 = [] s3 = 1 s4 = [1, 2] s5 = {"a": 1, "b": 2} s6 = {"a": [1, 2], "b": [3, 4]} s7 = {"a": {"1": 1}, "b": 2} s8 = {"a": 1, "b": 2, "c": 3, "d": 4} expected_map_nested_s1 = {} expected_map_nested_s2 = [] expected_map_nested_s3 = 2 expected_map_nested_s4 = [2, 3] expected_map_nested_s5 = {"a": 2, "b": 3} expected_map_nested_s6 = {"a": [2, 3], "b": [4, 5]} expected_map_nested_s7 = {"a": {"1": 2}, "b": 3} expected_map_nested_s8 = {"a": 2, "b": 3, "c": 4, "d": 5} self.assertEqual(map_nested(add_one, s1), expected_map_nested_s1) self.assertEqual(map_nested(add_one, s2), expected_map_nested_s2) self.assertEqual(map_nested(add_one, s3), expected_map_nested_s3) self.assertEqual(map_nested(add_one, s4), expected_map_nested_s4) self.assertEqual(map_nested(add_one, s5), expected_map_nested_s5) self.assertEqual(map_nested(add_one, s6), expected_map_nested_s6) self.assertEqual(map_nested(add_one, s7), expected_map_nested_s7) self.assertEqual(map_nested(add_one, s8), expected_map_nested_s8) num_proc = 2 self.assertEqual(map_nested(add_one, s1, num_proc=num_proc), expected_map_nested_s1) self.assertEqual(map_nested(add_one, s2, num_proc=num_proc), expected_map_nested_s2) self.assertEqual(map_nested(add_one, s3, num_proc=num_proc), expected_map_nested_s3) self.assertEqual(map_nested(add_one, s4, num_proc=num_proc), expected_map_nested_s4) self.assertEqual(map_nested(add_one, s5, num_proc=num_proc), expected_map_nested_s5) self.assertEqual(map_nested(add_one, s6, num_proc=num_proc), expected_map_nested_s6) self.assertEqual(map_nested(add_one, s7, num_proc=num_proc), expected_map_nested_s7) self.assertEqual(map_nested(add_one, s8, num_proc=num_proc), expected_map_nested_s8) sn1 = {"a": np.eye(2), "b": np.zeros(3), "c": np.ones(2)} expected_map_nested_sn1_sum = {"a": 2, "b": 0, "c": 2} expected_map_nested_sn1_int = { "a": np.eye(2).astype(int), "b": np.zeros(3).astype(int), "c": np.ones(2).astype(int), } self.assertEqual(map_nested(np_sum, sn1, map_numpy=False), expected_map_nested_sn1_sum) self.assertEqual( {k: v.tolist() for k, v in map_nested(int, sn1, map_numpy=True).items()}, {k: v.tolist() for k, v in expected_map_nested_sn1_int.items()}, ) self.assertEqual(map_nested(np_sum, sn1, map_numpy=False, num_proc=num_proc), expected_map_nested_sn1_sum) self.assertEqual( {k: v.tolist() for k, v in map_nested(int, sn1, map_numpy=True, num_proc=num_proc).items()}, {k: v.tolist() for k, v in expected_map_nested_sn1_int.items()}, ) with self.assertRaises(AttributeError): # can't pickle a local lambda map_nested(lambda x: x + 1, sn1, num_proc=num_proc) def test_zip_dict(self): d1 = {"a": 1, "b": 2} d2 = {"a": 3, "b": 4} d3 = {"a": 5, "b": 6} expected_zip_dict_result = sorted([("a", (1, 3, 5)), ("b", (2, 4, 6))]) self.assertEqual(sorted(zip_dict(d1, d2, d3)), expected_zip_dict_result) def test_temporary_assignment(self): class Foo: my_attr = "bar" foo = Foo() self.assertEqual(foo.my_attr, "bar") with temporary_assignment(foo, "my_attr", "BAR"): self.assertEqual(foo.my_attr, "BAR") self.assertEqual(foo.my_attr, "bar") @pytest.mark.parametrize( "iterable_length, num_proc, expected_num_proc", [ (1, None, 1), (1, 1, 1), (2, None, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 2, 1), (16, 16, 16), (16, 17, 16), (17, 16, 16), ], ) def test_map_nested_num_proc(iterable_length, num_proc, expected_num_proc): with patch("datasets.utils.py_utils._single_map_nested") as mock_single_map_nested, patch( "datasets.parallel.parallel.Pool" ) as mock_multiprocessing_pool: data_struct = {f"{i}": i for i in range(iterable_length)} _ = map_nested(lambda x: x + 10, data_struct, num_proc=num_proc, parallel_min_length=16) if expected_num_proc == 1: assert mock_single_map_nested.called assert not mock_multiprocessing_pool.called else: assert not mock_single_map_nested.called assert mock_multiprocessing_pool.called assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc class TempSeedTest(TestCase): @require_tf def test_tensorflow(self): import tensorflow as tf from tensorflow.keras import layers model = layers.Dense(2) def gen_random_output(): x = tf.random.uniform((1, 3)) return model(x).numpy() with temp_seed(42, set_tensorflow=True): out1 = gen_random_output() with temp_seed(42, set_tensorflow=True): out2 = gen_random_output() out3 = gen_random_output() np.testing.assert_equal(out1, out2) self.assertGreater(np.abs(out1 - out3).sum(), 0) @require_torch def test_torch(self): import torch def gen_random_output(): model = torch.nn.Linear(3, 2) x = torch.rand(1, 3) return model(x).detach().numpy() with temp_seed(42, set_pytorch=True): out1 = gen_random_output() with temp_seed(42, set_pytorch=True): out2 = gen_random_output() out3 = gen_random_output() np.testing.assert_equal(out1, out2) self.assertGreater(np.abs(out1 - out3).sum(), 0) def test_numpy(self): def gen_random_output(): return np.random.rand(1, 3) with temp_seed(42): out1 = gen_random_output() with temp_seed(42): out2 = gen_random_output() out3 = gen_random_output() np.testing.assert_equal(out1, out2) self.assertGreater(np.abs(out1 - out3).sum(), 0) @pytest.mark.parametrize("input_data", [{}]) def test_nested_data_structure_data(input_data): output_data = NestedDataStructure(input_data).data assert output_data == input_data @pytest.mark.parametrize( "data, expected_output", [ ({}, []), ([], []), ("foo", ["foo"]), (["foo", "bar"], ["foo", "bar"]), ([["foo", "bar"]], ["foo", "bar"]), ([[["foo"], ["bar"]]], ["foo", "bar"]), ([[["foo"], "bar"]], ["foo", "bar"]), ({"a": 1, "b": 2}, [1, 2]), ({"a": [1, 2], "b": [3, 4]}, [1, 2, 3, 4]), ({"a": [[1, 2]], "b": [[3, 4]]}, [1, 2, 3, 4]), ({"a": [[1, 2]], "b": [3, 4]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [[[3], [4]]]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [[3, 4]]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [3, 4]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [3, [4]]}, [1, 2, 3, 4]), ({"a": {"1": 1}, "b": 2}, [1, 2]), ({"a": {"1": [1]}, "b": 2}, [1, 2]), ({"a": {"1": [1]}, "b": [2]}, [1, 2]), ], ) def test_flatten(data, expected_output): output = NestedDataStructure(data).flatten() assert output == expected_output def test_asdict(): input = A(x=1, y="foobar") expected_output = {"x": 1, "y": "foobar"} assert asdict(input) == expected_output input = {"a": {"b": A(x=10, y="foo")}, "c": [A(x=20, y="bar")]} expected_output = {"a": {"b": {"x": 10, "y": "foo"}}, "c": [{"x": 20, "y": "bar"}]} assert asdict(input) == expected_output with pytest.raises(TypeError): asdict([1, A(x=10, y="foo")]) def _split_text(text: str): return text.split() def _2seconds_generator_of_2items_with_timing(content): yield (time.time(), content) time.sleep(2) yield (time.time(), content) def test_iflatmap_unordered(): with Pool(2) as pool: out = list(iflatmap_unordered(pool, _split_text, kwargs_iterable=[{"text": "hello there"}] * 10)) assert out.count("hello") == 10 assert out.count("there") == 10 assert len(out) == 20 # check multiprocess from pathos (uses dill for pickling) with multiprocess.Pool(2) as pool: out = list(iflatmap_unordered(pool, _split_text, kwargs_iterable=[{"text": "hello there"}] * 10)) assert out.count("hello") == 10 assert out.count("there") == 10 assert len(out) == 20 # check that we get items as fast as possible with Pool(2) as pool: out = [] for yield_time, content in iflatmap_unordered( pool, _2seconds_generator_of_2items_with_timing, kwargs_iterable=[{"content": "a"}, {"content": "b"}] ): assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded" out.append(content) assert out.count("a") == 2 assert out.count("b") == 2 assert len(out) == 4
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_readme_util.py
import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): example_yaml_structure = yaml.safe_load( """\ name: "" allow_empty: false allow_empty_text: true subsections: - name: "Dataset Card for X" # First-level markdown heading allow_empty: false allow_empty_text: true subsections: - name: "Table of Contents" allow_empty: false allow_empty_text: false subsections: null - name: "Dataset Description" allow_empty: false allow_empty_text: false subsections: - name: "Dataset Summary" allow_empty: false allow_empty_text: false subsections: null - name: "Supported Tasks and Leaderboards" allow_empty: true allow_empty_text: true subsections: null - name: Languages allow_empty: false allow_empty_text: true subsections: null """ ) CORRECT_DICT = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } README_CORRECT = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ README_CORRECT_FOUR_LEVEL = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. #### Extra Ignored Subsection ### Supported Tasks and Leaderboards ### Languages Language Text """ CORRECT_DICT_FOUR_LEVEL = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Extra Ignored Subsection", "text": "", "is_empty_text": True, "subsections": [], } ], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } README_EMPTY_YAML = """\ --- --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ EXPECTED_ERROR_README_EMPTY_YAML = ( "The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README." ) README_NO_YAML = """\ # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ EXPECTED_ERROR_README_NO_YAML = ( "The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README." ) README_INCORRECT_YAML = """\ --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ EXPECTED_ERROR_README_INCORRECT_YAML = "The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README." README_MISSING_TEXT = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary ### Supported Tasks and Leaderboards ### Languages Language Text """ EXPECTED_ERROR_README_MISSING_TEXT = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored)." README_NONE_SUBSECTION = """\ --- language: - zh - en --- # Dataset Card for My Dataset """ EXPECTED_ERROR_README_NONE_SUBSECTION = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found 'None'." README_MISSING_SUBSECTION = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Languages Language Text """ EXPECTED_ERROR_README_MISSING_SUBSECTION = "The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`." README_MISSING_CONTENT = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages """ EXPECTED_ERROR_README_MISSING_CONTENT = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty." README_MISSING_FIRST_LEVEL = """\ --- language: - zh - en --- ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ EXPECTED_ERROR_README_MISSING_FIRST_LEVEL = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README." README_MULTIPLE_WRONG_FIRST_LEVEL = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text # Dataset Card My Dataset """ EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL = "The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README." README_WRONG_FIRST_LEVEL = """\ --- language: - zh - en --- # Dataset Card My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ EXPECTED_ERROR_README_WRONG_FIRST_LEVEL = "The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README." README_EMPTY = "" EXPECTED_ERROR_README_EMPTY = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README." README_MULTIPLE_SAME_HEADING_1 = """\ --- language: - zh - en --- # Dataset Card for My Dataset # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1 = "The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections." @pytest.mark.parametrize( "readme_md, expected_dict", [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ], ) def test_readme_from_string_correct(readme_md, expected_dict): assert ReadMe.from_string(readme_md, example_yaml_structure).to_dict() == expected_dict @pytest.mark.parametrize( "readme_md, expected_error", [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ], ) def test_readme_from_string_validation_errors(readme_md, expected_error): with pytest.raises(ValueError, match=re.escape(expected_error.format(path="root"))): readme = ReadMe.from_string(readme_md, example_yaml_structure) readme.validate() @pytest.mark.parametrize( "readme_md, expected_error", [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ], ) def test_readme_from_string_parsing_errors(readme_md, expected_error): with pytest.raises(ValueError, match=re.escape(expected_error.format(path="root"))): ReadMe.from_string(readme_md, example_yaml_structure) @pytest.mark.parametrize( "readme_md,", [ (README_MULTIPLE_SAME_HEADING_1), ], ) def test_readme_from_string_suppress_parsing_errors(readme_md): ReadMe.from_string(readme_md, example_yaml_structure, suppress_parsing_errors=True) @pytest.mark.parametrize( "readme_md, expected_dict", [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ], ) def test_readme_from_readme_correct(readme_md, expected_dict): with tempfile.TemporaryDirectory() as tmp_dir: path = Path(tmp_dir) / "README.md" with open(path, "w+") as readme_file: readme_file.write(readme_md) out = ReadMe.from_readme(path, example_yaml_structure).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( "readme_md, expected_error", [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ], ) def test_readme_from_readme_error(readme_md, expected_error): with tempfile.TemporaryDirectory() as tmp_dir: path = Path(tmp_dir) / "README.md" with open(path, "w+") as readme_file: readme_file.write(readme_md) expected_error = expected_error.format(path=path) with pytest.raises(ValueError, match=re.escape(expected_error)): readme = ReadMe.from_readme(path, example_yaml_structure) readme.validate() @pytest.mark.parametrize( "readme_md, expected_error", [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ], ) def test_readme_from_readme_parsing_errors(readme_md, expected_error): with tempfile.TemporaryDirectory() as tmp_dir: path = Path(tmp_dir) / "README.md" with open(path, "w+") as readme_file: readme_file.write(readme_md) expected_error = expected_error.format(path=path) with pytest.raises(ValueError, match=re.escape(expected_error)): ReadMe.from_readme(path, example_yaml_structure) @pytest.mark.parametrize( "readme_md,", [ (README_MULTIPLE_SAME_HEADING_1), ], ) def test_readme_from_readme_suppress_parsing_errors(readme_md): with tempfile.TemporaryDirectory() as tmp_dir: path = Path(tmp_dir) / "README.md" with open(path, "w+") as readme_file: readme_file.write(readme_md) ReadMe.from_readme(path, example_yaml_structure, suppress_parsing_errors=True)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_search.py
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss pytestmark = pytest.mark.integration @require_faiss class IndexableDatasetTest(TestCase): def _create_dummy_dataset(self): dset = Dataset.from_dict({"filename": ["my_name-train" + "_" + str(x) for x in np.arange(30).tolist()]}) return dset def test_add_faiss_index(self): import faiss dset: Dataset = self._create_dummy_dataset() dset = dset.map( lambda ex, i: {"vecs": i * np.ones(5, dtype=np.float32)}, with_indices=True, keep_in_memory=True ) dset = dset.add_faiss_index("vecs", batch_size=100, metric_type=faiss.METRIC_INNER_PRODUCT) scores, examples = dset.get_nearest_examples("vecs", np.ones(5, dtype=np.float32)) self.assertEqual(examples["filename"][0], "my_name-train_29") dset.drop_index("vecs") def test_add_faiss_index_from_external_arrays(self): import faiss dset: Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5)) * np.arange(30).reshape(-1, 1), index_name="vecs", batch_size=100, metric_type=faiss.METRIC_INNER_PRODUCT, ) scores, examples = dset.get_nearest_examples("vecs", np.ones(5, dtype=np.float32)) self.assertEqual(examples["filename"][0], "my_name-train_29") def test_serialization(self): import faiss dset: Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5)) * np.arange(30).reshape(-1, 1), index_name="vecs", metric_type=faiss.METRIC_INNER_PRODUCT, ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=False) as tmp_file: dset.save_faiss_index("vecs", tmp_file.name) dset.load_faiss_index("vecs2", tmp_file.name) os.unlink(tmp_file.name) scores, examples = dset.get_nearest_examples("vecs2", np.ones(5, dtype=np.float32)) self.assertEqual(examples["filename"][0], "my_name-train_29") def test_drop_index(self): dset: Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5)) * np.arange(30).reshape(-1, 1), index_name="vecs" ) dset.drop_index("vecs") self.assertRaises(MissingIndex, partial(dset.get_nearest_examples, "vecs2", np.ones(5, dtype=np.float32))) def test_add_elasticsearch_index(self): from elasticsearch import Elasticsearch dset: Dataset = self._create_dummy_dataset() with patch("elasticsearch.Elasticsearch.search") as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk") as mocked_bulk: mocked_index_create.return_value = {"acknowledged": True} mocked_bulk.return_value([(True, None)] * 30) mocked_search.return_value = {"hits": {"hits": [{"_score": 1, "_id": 29}]}} es_client = Elasticsearch() dset.add_elasticsearch_index("filename", es_client=es_client) scores, examples = dset.get_nearest_examples("filename", "my_name-train_29") self.assertEqual(examples["filename"][0], "my_name-train_29") @require_faiss class FaissIndexTest(TestCase): def test_flat_ip(self): import faiss index = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT) # add vectors index.add_vectors(np.eye(5, dtype=np.float32)) self.assertIsNotNone(index.faiss_index) self.assertEqual(index.faiss_index.ntotal, 5) index.add_vectors(np.zeros((5, 5), dtype=np.float32)) self.assertEqual(index.faiss_index.ntotal, 10) # single query query = np.zeros(5, dtype=np.float32) query[1] = 1 scores, indices = index.search(query) self.assertRaises(ValueError, index.search, query.reshape(-1, 1)) self.assertGreater(scores[0], 0) self.assertEqual(indices[0], 1) # batched queries queries = np.eye(5, dtype=np.float32)[::-1] total_scores, total_indices = index.search_batch(queries) self.assertRaises(ValueError, index.search_batch, queries[0]) best_scores = [scores[0] for scores in total_scores] best_indices = [indices[0] for indices in total_indices] self.assertGreater(np.min(best_scores), 0) self.assertListEqual([4, 3, 2, 1, 0], best_indices) def test_factory(self): import faiss index = FaissIndex(string_factory="Flat") index.add_vectors(np.eye(5, dtype=np.float32)) self.assertIsInstance(index.faiss_index, faiss.IndexFlat) index = FaissIndex(string_factory="LSH") index.add_vectors(np.eye(5, dtype=np.float32)) self.assertIsInstance(index.faiss_index, faiss.IndexLSH) with self.assertRaises(ValueError): _ = FaissIndex(string_factory="Flat", custom_index=faiss.IndexFlat(5)) def test_custom(self): import faiss custom_index = faiss.IndexFlat(5) index = FaissIndex(custom_index=custom_index) index.add_vectors(np.eye(5, dtype=np.float32)) self.assertIsInstance(index.faiss_index, faiss.IndexFlat) def test_serialization(self): import faiss index = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT) index.add_vectors(np.eye(5, dtype=np.float32)) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=False) as tmp_file: index.save(tmp_file.name) index = FaissIndex.load(tmp_file.name) os.unlink(tmp_file.name) query = np.zeros(5, dtype=np.float32) query[1] = 1 scores, indices = index.search(query) self.assertGreater(scores[0], 0) self.assertEqual(indices[0], 1) @require_faiss def test_serialization_fs(mockfs): import faiss index = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT) index.add_vectors(np.eye(5, dtype=np.float32)) index_name = "index.faiss" path = f"mock://{index_name}" index.save(path, storage_options=mockfs.storage_options) index = FaissIndex.load(path, storage_options=mockfs.storage_options) query = np.zeros(5, dtype=np.float32) query[1] = 1 scores, indices = index.search(query) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class ElasticSearchIndexTest(TestCase): def test_elasticsearch(self): from elasticsearch import Elasticsearch with patch("elasticsearch.Elasticsearch.search") as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk") as mocked_bulk: es_client = Elasticsearch() mocked_index_create.return_value = {"acknowledged": True} index = ElasticSearchIndex(es_client=es_client) mocked_bulk.return_value([(True, None)] * 3) index.add_documents(["foo", "bar", "foobar"]) # single query query = "foo" mocked_search.return_value = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} scores, indices = index.search(query) self.assertEqual(scores[0], 1) self.assertEqual(indices[0], 0) # single query with timeout query = "foo" mocked_search.return_value = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} scores, indices = index.search(query, request_timeout=30) self.assertEqual(scores[0], 1) self.assertEqual(indices[0], 0) # batched queries queries = ["foo", "bar", "foobar"] mocked_search.return_value = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} total_scores, total_indices = index.search_batch(queries) best_scores = [scores[0] for scores in total_scores] best_indices = [indices[0] for indices in total_indices] self.assertGreater(np.min(best_scores), 0) self.assertListEqual([1, 1, 1], best_indices) # batched queries with timeout queries = ["foo", "bar", "foobar"] mocked_search.return_value = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} total_scores, total_indices = index.search_batch(queries, request_timeout=30) best_scores = [scores[0] for scores in total_scores] best_indices = [indices[0] for indices in total_indices] self.assertGreater(np.min(best_scores), 0) self.assertListEqual([1, 1, 1], best_indices)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_sharding_utils.py
import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( "kwargs, expected", [ ({"num_shards": 0, "max_num_jobs": 1}, []), ({"num_shards": 10, "max_num_jobs": 1}, [range(10)]), ({"num_shards": 10, "max_num_jobs": 10}, [range(i, i + 1) for i in range(10)]), ({"num_shards": 1, "max_num_jobs": 10}, [range(1)]), ({"num_shards": 10, "max_num_jobs": 3}, [range(0, 4), range(4, 7), range(7, 10)]), ({"num_shards": 3, "max_num_jobs": 10}, [range(0, 1), range(1, 2), range(2, 3)]), ], ) def test_distribute_shards(kwargs, expected): out = _distribute_shards(**kwargs) assert out == expected @pytest.mark.parametrize( "gen_kwargs, max_num_jobs, expected", [ ({"foo": 0}, 10, [{"foo": 0}]), ({"shards": [0, 1, 2, 3]}, 1, [{"shards": [0, 1, 2, 3]}]), ({"shards": [0, 1, 2, 3]}, 4, [{"shards": [0]}, {"shards": [1]}, {"shards": [2]}, {"shards": [3]}]), ({"shards": [0, 1]}, 4, [{"shards": [0]}, {"shards": [1]}]), ({"shards": [0, 1, 2, 3]}, 2, [{"shards": [0, 1]}, {"shards": [2, 3]}]), ], ) def test_split_gen_kwargs(gen_kwargs, max_num_jobs, expected): out = _split_gen_kwargs(gen_kwargs, max_num_jobs) assert out == expected @pytest.mark.parametrize( "gen_kwargs, expected", [ ({"foo": 0}, 1), ({"shards": [0]}, 1), ({"shards": [0, 1, 2, 3]}, 4), ({"shards": [0, 1, 2, 3], "foo": 0}, 4), ({"shards": [0, 1, 2, 3], "other": (0, 1)}, 4), ({"shards": [0, 1, 2, 3], "shards2": [0, 1]}, RuntimeError), ], ) def test_number_of_shards_in_gen_kwargs(gen_kwargs, expected): if expected is RuntimeError: with pytest.raises(expected): _number_of_shards_in_gen_kwargs(gen_kwargs) else: out = _number_of_shards_in_gen_kwargs(gen_kwargs) assert out == expected
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_splits.py
import pytest from datasets.splits import SplitDict, SplitInfo from datasets.utils.py_utils import asdict @pytest.mark.parametrize( "split_dict", [ SplitDict(), SplitDict({"train": SplitInfo(name="train", num_bytes=1337, num_examples=42, dataset_name="my_dataset")}), SplitDict({"train": SplitInfo(name="train", num_bytes=1337, num_examples=42)}), SplitDict({"train": SplitInfo()}), ], ) def test_split_dict_to_yaml_list(split_dict: SplitDict): split_dict_yaml_list = split_dict._to_yaml_list() assert len(split_dict_yaml_list) == len(split_dict) reloaded = SplitDict._from_yaml_list(split_dict_yaml_list) for split_name, split_info in split_dict.items(): # dataset_name field is deprecated, and is therefore not part of the YAML dump split_info.dataset_name = None # the split name of split_dict takes over the name of the split info object split_info.name = split_name assert split_dict == reloaded @pytest.mark.parametrize( "split_info", [SplitInfo(), SplitInfo(dataset_name=None), SplitInfo(dataset_name="my_dataset")] ) def test_split_dict_asdict_has_dataset_name(split_info): # For backward compatibility, we need asdict(split_dict) to return split info dictrionaries with the "dataset_name" # field even if it's deprecated. This way old versionso of `datasets` can still reload dataset_infos.json files split_dict_asdict = asdict(SplitDict({"train": split_info})) assert "dataset_name" in split_dict_asdict["train"] assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_streaming_download_manager.py
import json import os import re from pathlib import Path import pytest from fsspec.registry import _registry as _fsspec_registry from fsspec.spec import AbstractBufferedFile, AbstractFileSystem from datasets.download.download_config import DownloadConfig from datasets.download.streaming_download_manager import ( StreamingDownloadManager, _get_extraction_protocol, xbasename, xexists, xgetsize, xglob, xisdir, xisfile, xjoin, xlistdir, xnumpy_load, xopen, xPath, xrelpath, xsplit, xsplitext, xwalk, ) from datasets.filesystems import COMPRESSION_FILESYSTEMS from datasets.utils.hub import hf_hub_url from .utils import require_lz4, require_zstandard, slow TEST_URL = "https://huggingface.co/datasets/lhoestq/test/raw/main/some_text.txt" TEST_URL_CONTENT = "foo\nbar\nfoobar" TEST_GG_DRIVE_FILENAME = "train.tsv" TEST_GG_DRIVE_URL = "https://drive.google.com/uc?export=download&id=17bOgBDc3hRCoPZ89EYtKDzK-yXAWat94" TEST_GG_DRIVE_GZIPPED_URL = "https://drive.google.com/uc?export=download&id=1Bt4Garpf0QLiwkJhHJzXaVa0I0H5Qhwz" TEST_GG_DRIVE_ZIPPED_URL = "https://drive.google.com/uc?export=download&id=1k92sUfpHxKq8PXWRr7Y5aNHXwOCNUmqh" TEST_GG_DRIVE_CONTENT = """\ pokemon_name, type Charmander, fire Squirtle, water Bulbasaur, grass""" class DummyTestFS(AbstractFileSystem): protocol = "mock" _file_class = AbstractBufferedFile _fs_contents = ( {"name": "top_level", "type": "directory"}, {"name": "top_level/second_level", "type": "directory"}, {"name": "top_level/second_level/date=2019-10-01", "type": "directory"}, { "name": "top_level/second_level/date=2019-10-01/a.parquet", "type": "file", "size": 100, }, { "name": "top_level/second_level/date=2019-10-01/b.parquet", "type": "file", "size": 100, }, {"name": "top_level/second_level/date=2019-10-02", "type": "directory"}, { "name": "top_level/second_level/date=2019-10-02/a.parquet", "type": "file", "size": 100, }, {"name": "top_level/second_level/date=2019-10-04", "type": "directory"}, { "name": "top_level/second_level/date=2019-10-04/a.parquet", "type": "file", "size": 100, }, {"name": "misc", "type": "directory"}, {"name": "misc/foo.txt", "type": "file", "size": 100}, {"name": "glob_test", "type": "directory", "size": 0}, {"name": "glob_test/hat", "type": "directory", "size": 0}, {"name": "glob_test/hat/^foo.txt", "type": "file", "size": 100}, {"name": "glob_test/dollar", "type": "directory", "size": 0}, {"name": "glob_test/dollar/$foo.txt", "type": "file", "size": 100}, {"name": "glob_test/lbrace", "type": "directory", "size": 0}, {"name": "glob_test/lbrace/{foo.txt", "type": "file", "size": 100}, {"name": "glob_test/rbrace", "type": "directory", "size": 0}, {"name": "glob_test/rbrace/}foo.txt", "type": "file", "size": 100}, ) def __getitem__(self, name): for item in self._fs_contents: if item["name"] == name: return item raise IndexError(f"{name} not found!") def ls(self, path, detail=True, refresh=True, **kwargs): if kwargs.pop("strip_proto", True): path = self._strip_protocol(path) files = not refresh and self._ls_from_cache(path) if not files: files = [file for file in self._fs_contents if path == self._parent(file["name"])] files.sort(key=lambda file: file["name"]) self.dircache[path.rstrip("/")] = files if detail: return files return [file["name"] for file in files] def _open( self, path, mode="rb", block_size=None, autocommit=True, cache_options=None, **kwargs, ): return self._file_class( self, path, mode, block_size, autocommit, cache_options=cache_options, **kwargs, ) @pytest.fixture def mock_fsspec(): _fsspec_registry["mock"] = DummyTestFS yield del _fsspec_registry["mock"] def _readd_double_slash_removed_by_path(path_as_posix: str) -> str: """Path(...) on an url path like zip://file.txt::http://host.com/data.zip converts the :// to :/ This function readds the :// It handles cases like: - https://host.com/data.zip - C://data.zip - zip://file.txt::https://host.com/data.zip - zip://file.txt::/Users/username/data.zip - zip://file.txt::C://data.zip Args: path_as_posix (str): output of Path(...).as_posix() Returns: str: the url path with :// instead of :/ """ return re.sub("([A-z]:/)([A-z:])", r"\g<1>/\g<2>", path_as_posix) @pytest.mark.parametrize( "input_path, paths_to_join, expected_path", [ ( "https://host.com/archive.zip", ("file.txt",), "https://host.com/archive.zip/file.txt", ), ( "zip://::https://host.com/archive.zip", ("file.txt",), "zip://file.txt::https://host.com/archive.zip", ), ( "zip://folder::https://host.com/archive.zip", ("file.txt",), "zip://folder/file.txt::https://host.com/archive.zip", ), ( ".", ("file.txt",), os.path.join(".", "file.txt"), ), ( str(Path().resolve()), ("file.txt",), str((Path().resolve() / "file.txt")), ), ], ) def test_xjoin(input_path, paths_to_join, expected_path): output_path = xjoin(input_path, *paths_to_join) assert output_path == expected_path output_path = xPath(input_path).joinpath(*paths_to_join) assert output_path == xPath(expected_path) @pytest.mark.parametrize( "input_path, expected_path", [ (str(Path(__file__).resolve()), str(Path(__file__).resolve().parent)), ("https://host.com/archive.zip", "https://host.com"), ( "zip://file.txt::https://host.com/archive.zip", "zip://::https://host.com/archive.zip", ), ( "zip://folder/file.txt::https://host.com/archive.zip", "zip://folder::https://host.com/archive.zip", ), ], ) def test_xdirname(input_path, expected_path): from datasets.download.streaming_download_manager import xdirname output_path = xdirname(input_path) output_path = _readd_double_slash_removed_by_path(Path(output_path).as_posix()) assert output_path == _readd_double_slash_removed_by_path(Path(expected_path).as_posix()) @pytest.mark.parametrize( "input_path, exists", [ ("tmp_path/file.txt", True), ("tmp_path/file_that_doesnt_exist.txt", False), ("mock://top_level/second_level/date=2019-10-01/a.parquet", True), ("mock://top_level/second_level/date=2019-10-01/file_that_doesnt_exist.parquet", False), ], ) def test_xexists(input_path, exists, tmp_path, mock_fsspec): if input_path.startswith("tmp_path"): input_path = input_path.replace("/", os.sep).replace("tmp_path", str(tmp_path)) (tmp_path / "file.txt").touch() assert xexists(input_path) is exists @pytest.mark.integration def test_xexists_private(hf_private_dataset_repo_txt_data, hf_token): root_url = hf_hub_url(hf_private_dataset_repo_txt_data, "") download_config = DownloadConfig(token=hf_token) assert xexists(root_url + "data/text_data.txt", download_config=download_config) assert not xexists(root_url + "file_that_doesnt_exist.txt", download_config=download_config) @pytest.mark.parametrize( "input_path, expected_head_and_tail", [ ( str(Path(__file__).resolve()), (str(Path(__file__).resolve().parent), str(Path(__file__).resolve().name)), ), ("https://host.com/archive.zip", ("https://host.com", "archive.zip")), ("zip://file.txt::https://host.com/archive.zip", ("zip://::https://host.com/archive.zip", "file.txt")), ("zip://folder::https://host.com/archive.zip", ("zip://::https://host.com/archive.zip", "folder")), ("zip://::https://host.com/archive.zip", ("zip://::https://host.com/archive.zip", "")), ], ) def test_xsplit(input_path, expected_head_and_tail): output_path, tail = xsplit(input_path) expected_path, expected_tail = expected_head_and_tail output_path = _readd_double_slash_removed_by_path(Path(output_path).as_posix()) expected_path = _readd_double_slash_removed_by_path(Path(expected_path).as_posix()) assert output_path == expected_path assert tail == expected_tail @pytest.mark.parametrize( "input_path, expected_path_and_ext", [ ( str(Path(__file__).resolve()), (str(Path(__file__).resolve().with_suffix("")), str(Path(__file__).resolve().suffix)), ), ("https://host.com/archive.zip", ("https://host.com/archive", ".zip")), ("zip://file.txt::https://host.com/archive.zip", ("zip://file::https://host.com/archive.zip", ".txt")), ("zip://folder::https://host.com/archive.zip", ("zip://folder::https://host.com/archive.zip", "")), ("zip://::https://host.com/archive.zip", ("zip://::https://host.com/archive.zip", "")), ], ) def test_xsplitext(input_path, expected_path_and_ext): output_path, ext = xsplitext(input_path) expected_path, expected_ext = expected_path_and_ext output_path = _readd_double_slash_removed_by_path(Path(output_path).as_posix()) expected_path = _readd_double_slash_removed_by_path(Path(expected_path).as_posix()) assert output_path == expected_path assert ext == expected_ext def test_xopen_local(text_path): with xopen(text_path, "r", encoding="utf-8") as f, open(text_path, encoding="utf-8") as expected_file: assert list(f) == list(expected_file) with xPath(text_path).open("r", encoding="utf-8") as f, open(text_path, encoding="utf-8") as expected_file: assert list(f) == list(expected_file) @pytest.mark.integration def test_xopen_remote(): with xopen(TEST_URL, "r", encoding="utf-8") as f: assert list(f) == TEST_URL_CONTENT.splitlines(keepends=True) with xPath(TEST_URL).open("r", encoding="utf-8") as f: assert list(f) == TEST_URL_CONTENT.splitlines(keepends=True) @pytest.mark.parametrize( "input_path, expected_paths", [ ("tmp_path", ["file1.txt", "file2.txt"]), ("mock://", ["glob_test", "misc", "top_level"]), ("mock://top_level", ["second_level"]), ("mock://top_level/second_level/date=2019-10-01", ["a.parquet", "b.parquet"]), ], ) def test_xlistdir(input_path, expected_paths, tmp_path, mock_fsspec): if input_path.startswith("tmp_path"): input_path = input_path.replace("/", os.sep).replace("tmp_path", str(tmp_path)) for file in ["file1.txt", "file2.txt"]: (tmp_path / file).touch() output_paths = sorted(xlistdir(input_path)) assert output_paths == expected_paths @pytest.mark.integration def test_xlistdir_private(hf_private_dataset_repo_zipped_txt_data, hf_token): root_url = hf_hub_url(hf_private_dataset_repo_zipped_txt_data, "data.zip") download_config = DownloadConfig(token=hf_token) assert len(xlistdir("zip://::" + root_url, download_config=download_config)) == 1 assert len(xlistdir("zip://main_dir::" + root_url, download_config=download_config)) == 2 with pytest.raises(FileNotFoundError): xlistdir("zip://qwertyuiop::" + root_url, download_config=download_config) with pytest.raises(FileNotFoundError): xlistdir(root_url, download_config=download_config) @pytest.mark.parametrize( "input_path, isdir", [ ("tmp_path", True), ("tmp_path/file.txt", False), ("mock://", True), ("mock://top_level", True), ("mock://dir_that_doesnt_exist", False), ], ) def test_xisdir(input_path, isdir, tmp_path, mock_fsspec): if input_path.startswith("tmp_path"): input_path = input_path.replace("/", os.sep).replace("tmp_path", str(tmp_path)) (tmp_path / "file.txt").touch() assert xisdir(input_path) == isdir @pytest.mark.integration def test_xisdir_private(hf_private_dataset_repo_zipped_txt_data, hf_token): root_url = hf_hub_url(hf_private_dataset_repo_zipped_txt_data, "data.zip") download_config = DownloadConfig(token=hf_token) assert xisdir("zip://::" + root_url, download_config=download_config) is True assert xisdir("zip://main_dir::" + root_url, download_config=download_config) is True assert xisdir("zip://qwertyuiop::" + root_url, download_config=download_config) is False assert xisdir(root_url, download_config=download_config) is False @pytest.mark.parametrize( "input_path, isfile", [ ("tmp_path/file.txt", True), ("tmp_path/file_that_doesnt_exist.txt", False), ("mock://", False), ("mock://top_level/second_level/date=2019-10-01/a.parquet", True), ], ) def test_xisfile(input_path, isfile, tmp_path, mock_fsspec): if input_path.startswith("tmp_path"): input_path = input_path.replace("/", os.sep).replace("tmp_path", str(tmp_path)) (tmp_path / "file.txt").touch() assert xisfile(input_path) == isfile @pytest.mark.integration def test_xisfile_private(hf_private_dataset_repo_txt_data, hf_token): root_url = hf_hub_url(hf_private_dataset_repo_txt_data, "") download_config = DownloadConfig(token=hf_token) assert xisfile(root_url + "data/text_data.txt", download_config=download_config) is True assert xisfile(root_url + "qwertyuiop", download_config=download_config) is False @pytest.mark.parametrize( "input_path, size", [ ("tmp_path/file.txt", 100), ("mock://", 0), ("mock://top_level/second_level/date=2019-10-01/a.parquet", 100), ], ) def test_xgetsize(input_path, size, tmp_path, mock_fsspec): if input_path.startswith("tmp_path"): input_path = input_path.replace("/", os.sep).replace("tmp_path", str(tmp_path)) (tmp_path / "file.txt").touch() (tmp_path / "file.txt").write_bytes(b"x" * 100) assert xgetsize(input_path) == size @pytest.mark.integration def test_xgetsize_private(hf_private_dataset_repo_txt_data, hf_token): root_url = hf_hub_url(hf_private_dataset_repo_txt_data, "") download_config = DownloadConfig(token=hf_token) assert xgetsize(root_url + "data/text_data.txt", download_config=download_config) == 39 with pytest.raises(FileNotFoundError): xgetsize(root_url + "qwertyuiop", download_config=download_config) @pytest.mark.parametrize( "input_path, expected_paths", [ ("tmp_path/*.txt", ["file1.txt", "file2.txt"]), ("mock://*", ["mock://glob_test", "mock://misc", "mock://top_level"]), ("mock://top_*", ["mock://top_level"]), ( "mock://top_level/second_level/date=2019-10-0[1-4]", [ "mock://top_level/second_level/date=2019-10-01", "mock://top_level/second_level/date=2019-10-02", "mock://top_level/second_level/date=2019-10-04", ], ), ( "mock://top_level/second_level/date=2019-10-0[1-4]/*", [ "mock://top_level/second_level/date=2019-10-01/a.parquet", "mock://top_level/second_level/date=2019-10-01/b.parquet", "mock://top_level/second_level/date=2019-10-02/a.parquet", "mock://top_level/second_level/date=2019-10-04/a.parquet", ], ), ], ) def test_xglob(input_path, expected_paths, tmp_path, mock_fsspec): if input_path.startswith("tmp_path"): input_path = input_path.replace("/", os.sep).replace("tmp_path", str(tmp_path)) expected_paths = [str(tmp_path / file) for file in expected_paths] for file in ["file1.txt", "file2.txt", "README.md"]: (tmp_path / file).touch() output_paths = sorted(xglob(input_path)) assert output_paths == expected_paths @pytest.mark.integration def test_xglob_private(hf_private_dataset_repo_zipped_txt_data, hf_token): root_url = hf_hub_url(hf_private_dataset_repo_zipped_txt_data, "data.zip") download_config = DownloadConfig(token=hf_token) assert len(xglob("zip://**::" + root_url, download_config=download_config)) == 3 assert len(xglob("zip://qwertyuiop/*::" + root_url, download_config=download_config)) == 0 @pytest.mark.parametrize( "input_path, expected_outputs", [ ("tmp_path", [("", [], ["file1.txt", "file2.txt", "README.md"])]), ( "mock://top_level/second_level", [ ("mock://top_level/second_level", ["date=2019-10-01", "date=2019-10-02", "date=2019-10-04"], []), ("mock://top_level/second_level/date=2019-10-01", [], ["a.parquet", "b.parquet"]), ("mock://top_level/second_level/date=2019-10-02", [], ["a.parquet"]), ("mock://top_level/second_level/date=2019-10-04", [], ["a.parquet"]), ], ), ], ) def test_xwalk(input_path, expected_outputs, tmp_path, mock_fsspec): if input_path.startswith("tmp_path"): input_path = input_path.replace("/", os.sep).replace("tmp_path", str(tmp_path)) expected_outputs = sorted( [ (str(tmp_path / dirpath).rstrip("/"), sorted(dirnames), sorted(filenames)) for dirpath, dirnames, filenames in expected_outputs ] ) for file in ["file1.txt", "file2.txt", "README.md"]: (tmp_path / file).touch() outputs = sorted(xwalk(input_path)) outputs = [(dirpath, sorted(dirnames), sorted(filenames)) for dirpath, dirnames, filenames in outputs] assert outputs == expected_outputs @pytest.mark.integration def test_xwalk_private(hf_private_dataset_repo_zipped_txt_data, hf_token): root_url = hf_hub_url(hf_private_dataset_repo_zipped_txt_data, "data.zip") download_config = DownloadConfig(token=hf_token) assert len(list(xwalk("zip://::" + root_url, download_config=download_config))) == 2 assert len(list(xwalk("zip://main_dir::" + root_url, download_config=download_config))) == 1 assert len(list(xwalk("zip://qwertyuiop::" + root_url, download_config=download_config))) == 0 @pytest.mark.parametrize( "input_path, start_path, expected_path", [ ("dir1/dir2/file.txt".replace("/", os.path.sep), "dir1", "dir2/file.txt".replace("/", os.path.sep)), ("dir1/dir2/file.txt".replace("/", os.path.sep), "dir1/dir2".replace("/", os.path.sep), "file.txt"), ("zip://file.txt::https://host.com/archive.zip", "zip://::https://host.com/archive.zip", "file.txt"), ( "zip://folder/file.txt::https://host.com/archive.zip", "zip://::https://host.com/archive.zip", "folder/file.txt", ), ( "zip://folder/file.txt::https://host.com/archive.zip", "zip://folder::https://host.com/archive.zip", "file.txt", ), ], ) def test_xrelpath(input_path, start_path, expected_path): output_path = xrelpath(input_path, start=start_path) assert output_path == expected_path class TestxPath: @pytest.mark.parametrize( "input_path", [ "https://host.com/archive.zip", "zip://file.txt::https://host.com/archive.zip", "zip://dir/file.txt::https://host.com/archive.zip", "file.txt", str(Path().resolve() / "file.txt"), ], ) def test_xpath_str(self, input_path): assert str(xPath(input_path)) == input_path @pytest.mark.parametrize( "input_path, expected_path", [ ("https://host.com/archive.zip", "https://host.com/archive.zip"), ("zip://file.txt::https://host.com/archive.zip", "zip://file.txt::https://host.com/archive.zip"), ("zip://dir/file.txt::https://host.com/archive.zip", "zip://dir/file.txt::https://host.com/archive.zip"), ("file.txt", "file.txt"), (str(Path().resolve() / "file.txt"), (Path().resolve() / "file.txt").as_posix()), ], ) def test_xpath_as_posix(self, input_path, expected_path): assert xPath(input_path).as_posix() == expected_path @pytest.mark.parametrize( "input_path, exists", [ ("tmp_path/file.txt", True), ("tmp_path/file_that_doesnt_exist.txt", False), ("mock://top_level/second_level/date=2019-10-01/a.parquet", True), ("mock://top_level/second_level/date=2019-10-01/file_that_doesnt_exist.parquet", False), ], ) def test_xpath_exists(self, input_path, exists, tmp_path, mock_fsspec): if input_path.startswith("tmp_path"): input_path = input_path.replace("/", os.sep).replace("tmp_path", str(tmp_path)) (tmp_path / "file.txt").touch() assert xexists(input_path) is exists @pytest.mark.parametrize( "input_path, pattern, expected_paths", [ ("tmp_path", "*.txt", ["file1.txt", "file2.txt"]), ("mock://", "*", ["mock://glob_test", "mock://misc", "mock://top_level"]), ("mock://", "top_*", ["mock://top_level"]), ( "mock://top_level/second_level", "date=2019-10-0[1-4]", [ "mock://top_level/second_level/date=2019-10-01", "mock://top_level/second_level/date=2019-10-02", "mock://top_level/second_level/date=2019-10-04", ], ), ( "mock://top_level/second_level", "date=2019-10-0[1-4]/*", [ "mock://top_level/second_level/date=2019-10-01/a.parquet", "mock://top_level/second_level/date=2019-10-01/b.parquet", "mock://top_level/second_level/date=2019-10-02/a.parquet", "mock://top_level/second_level/date=2019-10-04/a.parquet", ], ), ], ) def test_xpath_glob(self, input_path, pattern, expected_paths, tmp_path, mock_fsspec): if input_path == "tmp_path": input_path = tmp_path expected_paths = [tmp_path / file for file in expected_paths] for file in ["file1.txt", "file2.txt", "README.md"]: (tmp_path / file).touch() else: expected_paths = [Path(file) for file in expected_paths] output_paths = sorted(xPath(input_path).glob(pattern)) assert output_paths == expected_paths @pytest.mark.parametrize( "input_path, pattern, expected_paths", [ ("tmp_path", "*.txt", ["file1.txt", "file2.txt"]), ( "mock://", "date=2019-10-0[1-4]", [ "mock://top_level/second_level/date=2019-10-01", "mock://top_level/second_level/date=2019-10-02", "mock://top_level/second_level/date=2019-10-04", ], ), ( "mock://top_level", "date=2019-10-0[1-4]", [ "mock://top_level/second_level/date=2019-10-01", "mock://top_level/second_level/date=2019-10-02", "mock://top_level/second_level/date=2019-10-04", ], ), ( "mock://", "date=2019-10-0[1-4]/*", [ "mock://top_level/second_level/date=2019-10-01/a.parquet", "mock://top_level/second_level/date=2019-10-01/b.parquet", "mock://top_level/second_level/date=2019-10-02/a.parquet", "mock://top_level/second_level/date=2019-10-04/a.parquet", ], ), ( "mock://top_level", "date=2019-10-0[1-4]/*", [ "mock://top_level/second_level/date=2019-10-01/a.parquet", "mock://top_level/second_level/date=2019-10-01/b.parquet", "mock://top_level/second_level/date=2019-10-02/a.parquet", "mock://top_level/second_level/date=2019-10-04/a.parquet", ], ), ], ) def test_xpath_rglob(self, input_path, pattern, expected_paths, tmp_path, mock_fsspec): if input_path == "tmp_path": input_path = tmp_path dir_path = tmp_path / "dir" dir_path.mkdir() expected_paths = [dir_path / file for file in expected_paths] for file in ["file1.txt", "file2.txt", "README.md"]: (dir_path / file).touch() else: expected_paths = [Path(file) for file in expected_paths] output_paths = sorted(xPath(input_path).rglob(pattern)) assert output_paths == expected_paths @pytest.mark.parametrize( "input_path, expected_path", [ ("https://host.com/archive.zip", "https://host.com"), ("zip://file.txt::https://host.com/archive.zip", "zip://::https://host.com/archive.zip"), ("zip://dir/file.txt::https://host.com/archive.zip", "zip://dir::https://host.com/archive.zip"), ("file.txt", ""), (str(Path().resolve() / "file.txt"), str(Path().resolve())), ], ) def test_xpath_parent(self, input_path, expected_path): assert xPath(input_path).parent == xPath(expected_path) @pytest.mark.parametrize( "input_path, expected", [ ("https://host.com/archive.zip", "archive.zip"), ("zip://file.txt::https://host.com/archive.zip", "file.txt"), ("zip://dir/file.txt::https://host.com/archive.zip", "file.txt"), ("file.txt", "file.txt"), (str(Path().resolve() / "file.txt"), "file.txt"), ], ) def test_xpath_name(self, input_path, expected): assert xPath(input_path).name == expected @pytest.mark.parametrize( "input_path, expected", [ ("https://host.com/archive.zip", "archive"), ("zip://file.txt::https://host.com/archive.zip", "file"), ("zip://dir/file.txt::https://host.com/archive.zip", "file"), ("file.txt", "file"), (str(Path().resolve() / "file.txt"), "file"), ], ) def test_xpath_stem(self, input_path, expected): assert xPath(input_path).stem == expected @pytest.mark.parametrize( "input_path, expected", [ ("https://host.com/archive.zip", ".zip"), ("zip://file.txt::https://host.com/archive.zip", ".txt"), ("zip://dir/file.txt::https://host.com/archive.zip", ".txt"), ("file.txt", ".txt"), (str(Path().resolve() / "file.txt"), ".txt"), ], ) def test_xpath_suffix(self, input_path, expected): assert xPath(input_path).suffix == expected @pytest.mark.parametrize( "input_path, suffix, expected", [ ("https://host.com/archive.zip", ".ann", "https://host.com/archive.ann"), ("zip://file.txt::https://host.com/archive.zip", ".ann", "zip://file.ann::https://host.com/archive.zip"), ( "zip://dir/file.txt::https://host.com/archive.zip", ".ann", "zip://dir/file.ann::https://host.com/archive.zip", ), ("file.txt", ".ann", "file.ann"), (str(Path().resolve() / "file.txt"), ".ann", str(Path().resolve() / "file.ann")), ], ) def test_xpath_with_suffix(self, input_path, suffix, expected): assert xPath(input_path).with_suffix(suffix) == xPath(expected) @pytest.mark.parametrize("urlpath", [r"C:\\foo\bar.txt", "/foo/bar.txt", "https://f.oo/bar.txt"]) def test_streaming_dl_manager_download_dummy_path(urlpath): dl_manager = StreamingDownloadManager() assert dl_manager.download(urlpath) == urlpath def test_streaming_dl_manager_download(text_path): dl_manager = StreamingDownloadManager() out = dl_manager.download(text_path) assert out == text_path with xopen(out, encoding="utf-8") as f, open(text_path, encoding="utf-8") as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize("urlpath", [r"C:\\foo\bar.txt", "/foo/bar.txt", "https://f.oo/bar.txt"]) def test_streaming_dl_manager_download_and_extract_no_extraction(urlpath): dl_manager = StreamingDownloadManager() assert dl_manager.download_and_extract(urlpath) == urlpath def test_streaming_dl_manager_extract(text_gz_path, text_path): dl_manager = StreamingDownloadManager() output_path = dl_manager.extract(text_gz_path) path = os.path.basename(text_gz_path) path = path[: path.rindex(".")] assert output_path == f"gzip://{path}::{text_gz_path}" fsspec_open_file = xopen(output_path, encoding="utf-8") with fsspec_open_file as f, open(text_path, encoding="utf-8") as expected_file: assert f.read() == expected_file.read() def test_streaming_dl_manager_download_and_extract_with_extraction(text_gz_path, text_path): dl_manager = StreamingDownloadManager() output_path = dl_manager.download_and_extract(text_gz_path) path = os.path.basename(text_gz_path) path = path[: path.rindex(".")] assert output_path == f"gzip://{path}::{text_gz_path}" fsspec_open_file = xopen(output_path, encoding="utf-8") with fsspec_open_file as f, open(text_path, encoding="utf-8") as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize( "input_path, filename, expected_path", [("https://domain.org/archive.zip", "filename.jsonl", "zip://filename.jsonl::https://domain.org/archive.zip")], ) def test_streaming_dl_manager_download_and_extract_with_join(input_path, filename, expected_path): dl_manager = StreamingDownloadManager() extracted_path = dl_manager.download_and_extract(input_path) output_path = xjoin(extracted_path, filename) assert output_path == expected_path @pytest.mark.parametrize("compression_fs_class", COMPRESSION_FILESYSTEMS) def test_streaming_dl_manager_extract_all_supported_single_file_compression_types( compression_fs_class, gz_file, xz_file, zstd_file, bz2_file, lz4_file, text_file ): input_paths = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_file, "bz2": bz2_file, "lz4": lz4_file} input_path = input_paths[compression_fs_class.protocol] if input_path is None: reason = f"for '{compression_fs_class.protocol}' compression protocol, " if compression_fs_class.protocol == "lz4": reason += require_lz4.kwargs["reason"] elif compression_fs_class.protocol == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(reason) dl_manager = StreamingDownloadManager() output_path = dl_manager.extract(input_path) path = os.path.basename(input_path) path = path[: path.rindex(".")] assert output_path == f"{compression_fs_class.protocol}://{path}::{input_path}" fsspec_open_file = xopen(output_path, encoding="utf-8") with fsspec_open_file as f, open(text_file, encoding="utf-8") as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize( "urlpath, expected_protocol", [ ("zip://train-00000.json.gz::https://foo.bar/data.zip", "gzip"), ("https://foo.bar/train.json.gz?dl=1", "gzip"), ("http://opus.nlpl.eu/download.php?f=Bianet/v1/moses/en-ku.txt.zip", "zip"), ("https://github.com/user/what-time-is-it/blob/master/gutenberg_time_phrases.zip?raw=true", "zip"), ("https://github.com/user/repo/blob/master/data/morph_train.tsv?raw=true", None), ("https://repo.org/bitstream/handle/20.500.12185/346/annotated_corpus.zip?sequence=3&isAllowed=y", "zip"), ("https://zenodo.org/record/2787612/files/SICK.zip?download=1", "zip"), ], ) def test_streaming_dl_manager_get_extraction_protocol(urlpath, expected_protocol): assert _get_extraction_protocol(urlpath) == expected_protocol @pytest.mark.parametrize( "urlpath, expected_protocol", [ (TEST_GG_DRIVE_GZIPPED_URL, "gzip"), (TEST_GG_DRIVE_ZIPPED_URL, "zip"), ], ) @slow # otherwise it spams Google Drive and the CI gets banned def test_streaming_dl_manager_get_extraction_protocol_gg_drive(urlpath, expected_protocol): assert _get_extraction_protocol(urlpath) == expected_protocol @pytest.mark.parametrize( "urlpath", [ "zip://train-00000.tar.gz::https://foo.bar/data.zip", "https://foo.bar/train.tar.gz", "https://foo.bar/train.tgz", "https://foo.bar/train.tar", ], ) def test_streaming_dl_manager_extract_throws(urlpath): with pytest.raises(NotImplementedError): _ = StreamingDownloadManager().extract(urlpath) @slow # otherwise it spams Google Drive and the CI gets banned @pytest.mark.integration def test_streaming_gg_drive(): with xopen(TEST_GG_DRIVE_URL) as f: assert f.read() == TEST_GG_DRIVE_CONTENT @slow # otherwise it spams Google Drive and the CI gets banned @pytest.mark.integration def test_streaming_gg_drive_no_extract(): urlpath = StreamingDownloadManager().download_and_extract(TEST_GG_DRIVE_URL) with xopen(urlpath) as f: assert f.read() == TEST_GG_DRIVE_CONTENT @slow # otherwise it spams Google Drive and the CI gets banned @pytest.mark.integration def test_streaming_gg_drive_gzipped(): urlpath = StreamingDownloadManager().download_and_extract(TEST_GG_DRIVE_GZIPPED_URL) with xopen(urlpath) as f: assert f.read() == TEST_GG_DRIVE_CONTENT @slow # otherwise it spams Google Drive and the CI gets banned @pytest.mark.integration def test_streaming_gg_drive_zipped(): urlpath = StreamingDownloadManager().download_and_extract(TEST_GG_DRIVE_ZIPPED_URL) all_files = list(xglob(xjoin(urlpath, "*"))) assert len(all_files) == 1 assert xbasename(all_files[0]) == TEST_GG_DRIVE_FILENAME with xopen(all_files[0]) as f: assert f.read() == TEST_GG_DRIVE_CONTENT def _test_jsonl(path, file): assert path.endswith(".jsonl") for num_items, line in enumerate(file, start=1): item = json.loads(line.decode("utf-8")) assert item.keys() == {"col_1", "col_2", "col_3"} assert num_items == 4 @pytest.mark.parametrize("archive_jsonl", ["tar_jsonl_path", "zip_jsonl_path"]) def test_iter_archive_path(archive_jsonl, request): archive_jsonl_path = request.getfixturevalue(archive_jsonl) dl_manager = StreamingDownloadManager() archive_iterable = dl_manager.iter_archive(archive_jsonl_path) num_jsonl = 0 for num_jsonl, (path, file) in enumerate(archive_iterable, start=1): _test_jsonl(path, file) assert num_jsonl == 2 # do it twice to make sure it's reset correctly num_jsonl = 0 for num_jsonl, (path, file) in enumerate(archive_iterable, start=1): _test_jsonl(path, file) assert num_jsonl == 2 @pytest.mark.parametrize("archive_nested_jsonl", ["tar_nested_jsonl_path", "zip_nested_jsonl_path"]) def test_iter_archive_file(archive_nested_jsonl, request): archive_nested_jsonl_path = request.getfixturevalue(archive_nested_jsonl) dl_manager = StreamingDownloadManager() files_iterable = dl_manager.iter_archive(archive_nested_jsonl_path) num_tar, num_jsonl = 0, 0 for num_tar, (path, file) in enumerate(files_iterable, start=1): for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(file), start=1): _test_jsonl(subpath, subfile) assert num_tar == 1 assert num_jsonl == 2 # do it twice to make sure it's reset correctly num_tar, num_jsonl = 0, 0 for num_tar, (path, file) in enumerate(files_iterable, start=1): for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(file), start=1): _test_jsonl(subpath, subfile) assert num_tar == 1 assert num_jsonl == 2 def test_iter_files(data_dir_with_hidden_files): dl_manager = StreamingDownloadManager() for num_file, file in enumerate(dl_manager.iter_files(data_dir_with_hidden_files), start=1): assert os.path.basename(file) == ("test.txt" if num_file == 1 else "train.txt") assert num_file == 2 def test_xnumpy_load(tmp_path): import numpy as np expected_x = np.arange(10) npy_path = tmp_path / "data-x.npy" np.save(npy_path, expected_x) x = xnumpy_load(npy_path) assert np.array_equal(x, expected_x) npz_path = tmp_path / "data.npz" np.savez(npz_path, x=expected_x) with xnumpy_load(npz_path) as f: x = f["x"] assert np.array_equal(x, expected_x)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_table.py
import copy import pickle import warnings from typing import List, Union import numpy as np import pyarrow as pa import pytest import datasets from datasets import Sequence, Value from datasets.features.features import Array2DExtensionType, ClassLabel, Features, Image from datasets.table import ( ConcatenationTable, InMemoryTable, MemoryMappedTable, Table, TableBlock, _in_memory_arrow_table_from_buffer, _in_memory_arrow_table_from_file, _interpolation_search, _is_extension_type, _memory_mapped_arrow_table_from_file, array_concat, cast_array_to_feature, concat_tables, embed_array_storage, embed_table_storage, inject_arrow_table_documentation, table_cast, table_iter, ) from .utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, slow @pytest.fixture(scope="session") def in_memory_pa_table(arrow_file) -> pa.Table: return pa.ipc.open_stream(arrow_file).read_all() def _to_testing_blocks(table: TableBlock) -> List[List[TableBlock]]: assert len(table) > 2 blocks = [ [table.slice(0, 2)], [table.slice(2).drop([c for c in table.column_names if c != "tokens"]), table.slice(2).drop(["tokens"])], ] return blocks @pytest.fixture(scope="session") def in_memory_blocks(in_memory_pa_table): table = InMemoryTable(in_memory_pa_table) return _to_testing_blocks(table) @pytest.fixture(scope="session") def memory_mapped_blocks(arrow_file): table = MemoryMappedTable.from_file(arrow_file) return _to_testing_blocks(table) @pytest.fixture(scope="session") def mixed_in_memory_and_memory_mapped_blocks(in_memory_blocks, memory_mapped_blocks): return in_memory_blocks[:1] + memory_mapped_blocks[1:] def assert_deepcopy_without_bringing_data_in_memory(table: MemoryMappedTable): with assert_arrow_memory_doesnt_increase(): copied_table = copy.deepcopy(table) assert isinstance(copied_table, MemoryMappedTable) assert copied_table.table == table.table def assert_deepcopy_does_bring_data_in_memory(table: MemoryMappedTable): with assert_arrow_memory_increases(): copied_table = copy.deepcopy(table) assert isinstance(copied_table, MemoryMappedTable) assert copied_table.table == table.table def assert_pickle_without_bringing_data_in_memory(table: MemoryMappedTable): with assert_arrow_memory_doesnt_increase(): pickled_table = pickle.dumps(table) unpickled_table = pickle.loads(pickled_table) assert isinstance(unpickled_table, MemoryMappedTable) assert unpickled_table.table == table.table def assert_pickle_does_bring_data_in_memory(table: MemoryMappedTable): with assert_arrow_memory_increases(): pickled_table = pickle.dumps(table) unpickled_table = pickle.loads(pickled_table) assert isinstance(unpickled_table, MemoryMappedTable) assert unpickled_table.table == table.table def assert_index_attributes_equal(table: Table, other: Table): assert table._batches == other._batches np.testing.assert_array_equal(table._offsets, other._offsets) assert table._schema == other._schema def add_suffix_to_column_names(table, suffix): return table.rename_columns([f"{name}{suffix}" for name in table.column_names]) def test_inject_arrow_table_documentation(in_memory_pa_table): method = pa.Table.slice def function_to_wrap(*args): return method(*args) args = (0, 1) wrapped_method = inject_arrow_table_documentation(method)(function_to_wrap) assert method(in_memory_pa_table, *args) == wrapped_method(in_memory_pa_table, *args) assert "pyarrow.Table" not in wrapped_method.__doc__ assert "Table" in wrapped_method.__doc__ def test_in_memory_arrow_table_from_file(arrow_file, in_memory_pa_table): with assert_arrow_memory_increases(): pa_table = _in_memory_arrow_table_from_file(arrow_file) assert in_memory_pa_table == pa_table def test_in_memory_arrow_table_from_buffer(in_memory_pa_table): with assert_arrow_memory_increases(): buf_writer = pa.BufferOutputStream() writer = pa.RecordBatchStreamWriter(buf_writer, schema=in_memory_pa_table.schema) writer.write_table(in_memory_pa_table) writer.close() buf_writer.close() pa_table = _in_memory_arrow_table_from_buffer(buf_writer.getvalue()) assert in_memory_pa_table == pa_table def test_memory_mapped_arrow_table_from_file(arrow_file, in_memory_pa_table): with assert_arrow_memory_doesnt_increase(): pa_table = _memory_mapped_arrow_table_from_file(arrow_file) assert in_memory_pa_table == pa_table def test_table_init(in_memory_pa_table): table = Table(in_memory_pa_table) assert table.table == in_memory_pa_table def test_table_validate(in_memory_pa_table): table = Table(in_memory_pa_table) assert table.validate() == in_memory_pa_table.validate() def test_table_equals(in_memory_pa_table): table = Table(in_memory_pa_table) assert table.equals(in_memory_pa_table) def test_table_to_batches(in_memory_pa_table): table = Table(in_memory_pa_table) assert table.to_batches() == in_memory_pa_table.to_batches() def test_table_to_pydict(in_memory_pa_table): table = Table(in_memory_pa_table) assert table.to_pydict() == in_memory_pa_table.to_pydict() def test_table_to_string(in_memory_pa_table): table = Table(in_memory_pa_table) assert table.to_string() == in_memory_pa_table.to_string() def test_table_field(in_memory_pa_table): assert "tokens" in in_memory_pa_table.column_names table = Table(in_memory_pa_table) assert table.field("tokens") == in_memory_pa_table.field("tokens") def test_table_column(in_memory_pa_table): assert "tokens" in in_memory_pa_table.column_names table = Table(in_memory_pa_table) assert table.column("tokens") == in_memory_pa_table.column("tokens") def test_table_itercolumns(in_memory_pa_table): table = Table(in_memory_pa_table) assert isinstance(table.itercolumns(), type(in_memory_pa_table.itercolumns())) assert list(table.itercolumns()) == list(in_memory_pa_table.itercolumns()) def test_table_getitem(in_memory_pa_table): table = Table(in_memory_pa_table) assert table[0] == in_memory_pa_table[0] def test_table_len(in_memory_pa_table): table = Table(in_memory_pa_table) assert len(table) == len(in_memory_pa_table) def test_table_str(in_memory_pa_table): table = Table(in_memory_pa_table) assert str(table) == str(in_memory_pa_table).replace("pyarrow.Table", "Table") assert repr(table) == repr(in_memory_pa_table).replace("pyarrow.Table", "Table") @pytest.mark.parametrize( "attribute", ["schema", "columns", "num_columns", "num_rows", "shape", "nbytes", "column_names"] ) def test_table_attributes(in_memory_pa_table, attribute): table = Table(in_memory_pa_table) assert getattr(table, attribute) == getattr(in_memory_pa_table, attribute) def test_in_memory_table_from_file(arrow_file, in_memory_pa_table): with assert_arrow_memory_increases(): table = InMemoryTable.from_file(arrow_file) assert table.table == in_memory_pa_table assert isinstance(table, InMemoryTable) def test_in_memory_table_from_buffer(in_memory_pa_table): with assert_arrow_memory_increases(): buf_writer = pa.BufferOutputStream() writer = pa.RecordBatchStreamWriter(buf_writer, schema=in_memory_pa_table.schema) writer.write_table(in_memory_pa_table) writer.close() buf_writer.close() table = InMemoryTable.from_buffer(buf_writer.getvalue()) assert table.table == in_memory_pa_table assert isinstance(table, InMemoryTable) def test_in_memory_table_from_pandas(in_memory_pa_table): df = in_memory_pa_table.to_pandas() with assert_arrow_memory_increases(): # with no schema it might infer another order of the fields in the schema table = InMemoryTable.from_pandas(df) assert isinstance(table, InMemoryTable) # by specifying schema we get the same order of features, and so the exact same table table = InMemoryTable.from_pandas(df, schema=in_memory_pa_table.schema) assert table.table == in_memory_pa_table assert isinstance(table, InMemoryTable) def test_in_memory_table_from_arrays(in_memory_pa_table): arrays = list(in_memory_pa_table.columns) names = list(in_memory_pa_table.column_names) table = InMemoryTable.from_arrays(arrays, names=names) assert table.table == in_memory_pa_table assert isinstance(table, InMemoryTable) def test_in_memory_table_from_pydict(in_memory_pa_table): pydict = in_memory_pa_table.to_pydict() with assert_arrow_memory_increases(): table = InMemoryTable.from_pydict(pydict) assert isinstance(table, InMemoryTable) assert table.table == pa.Table.from_pydict(pydict) def test_in_memory_table_from_pylist(in_memory_pa_table): pylist = InMemoryTable(in_memory_pa_table).to_pylist() table = InMemoryTable.from_pylist(pylist) assert isinstance(table, InMemoryTable) assert pylist == table.to_pylist() def test_in_memory_table_from_batches(in_memory_pa_table): batches = list(in_memory_pa_table.to_batches()) table = InMemoryTable.from_batches(batches) assert table.table == in_memory_pa_table assert isinstance(table, InMemoryTable) def test_in_memory_table_deepcopy(in_memory_pa_table): table = InMemoryTable(in_memory_pa_table) copied_table = copy.deepcopy(table) assert table.table == copied_table.table assert_index_attributes_equal(table, copied_table) # deepcopy must return the exact same arrow objects since they are immutable assert table.table is copied_table.table assert all(batch1 is batch2 for batch1, batch2 in zip(table._batches, copied_table._batches)) def test_in_memory_table_pickle(in_memory_pa_table): table = InMemoryTable(in_memory_pa_table) pickled_table = pickle.dumps(table) unpickled_table = pickle.loads(pickled_table) assert unpickled_table.table == table.table assert_index_attributes_equal(table, unpickled_table) @slow def test_in_memory_table_pickle_big_table(): big_table_4GB = InMemoryTable.from_pydict({"col": [0] * ((4 * 8 << 30) // 64)}) length = len(big_table_4GB) big_table_4GB = pickle.dumps(big_table_4GB) big_table_4GB = pickle.loads(big_table_4GB) assert len(big_table_4GB) == length def test_in_memory_table_slice(in_memory_pa_table): table = InMemoryTable(in_memory_pa_table).slice(1, 2) assert table.table == in_memory_pa_table.slice(1, 2) assert isinstance(table, InMemoryTable) def test_in_memory_table_filter(in_memory_pa_table): mask = pa.array([i % 2 == 0 for i in range(len(in_memory_pa_table))]) table = InMemoryTable(in_memory_pa_table).filter(mask) assert table.table == in_memory_pa_table.filter(mask) assert isinstance(table, InMemoryTable) def test_in_memory_table_flatten(in_memory_pa_table): table = InMemoryTable(in_memory_pa_table).flatten() assert table.table == in_memory_pa_table.flatten() assert isinstance(table, InMemoryTable) def test_in_memory_table_combine_chunks(in_memory_pa_table): table = InMemoryTable(in_memory_pa_table).combine_chunks() assert table.table == in_memory_pa_table.combine_chunks() assert isinstance(table, InMemoryTable) def test_in_memory_table_cast(in_memory_pa_table): assert pa.list_(pa.int64()) in in_memory_pa_table.schema.types schema = pa.schema( { k: v if v != pa.list_(pa.int64()) else pa.list_(pa.int32()) for k, v in zip(in_memory_pa_table.schema.names, in_memory_pa_table.schema.types) } ) table = InMemoryTable(in_memory_pa_table).cast(schema) assert table.table == in_memory_pa_table.cast(schema) assert isinstance(table, InMemoryTable) def test_in_memory_table_cast_reorder_struct(): table = InMemoryTable( pa.Table.from_pydict( { "top": [ { "foo": "a", "bar": "b", } ] } ) ) schema = pa.schema({"top": pa.struct({"bar": pa.string(), "foo": pa.string()})}) assert table.cast(schema).schema == schema def test_in_memory_table_cast_with_hf_features(): table = InMemoryTable(pa.Table.from_pydict({"labels": [0, 1]})) features = Features({"labels": ClassLabel(names=["neg", "pos"])}) schema = features.arrow_schema assert table.cast(schema).schema == schema assert Features.from_arrow_schema(table.cast(schema).schema) == features def test_in_memory_table_replace_schema_metadata(in_memory_pa_table): metadata = {"huggingface": "{}"} table = InMemoryTable(in_memory_pa_table).replace_schema_metadata(metadata) assert table.table.schema.metadata == in_memory_pa_table.replace_schema_metadata(metadata).schema.metadata assert isinstance(table, InMemoryTable) def test_in_memory_table_add_column(in_memory_pa_table): i = len(in_memory_pa_table.column_names) field_ = "new_field" column = pa.array(list(range(len(in_memory_pa_table)))) table = InMemoryTable(in_memory_pa_table).add_column(i, field_, column) assert table.table == in_memory_pa_table.add_column(i, field_, column) assert isinstance(table, InMemoryTable) def test_in_memory_table_append_column(in_memory_pa_table): field_ = "new_field" column = pa.array(list(range(len(in_memory_pa_table)))) table = InMemoryTable(in_memory_pa_table).append_column(field_, column) assert table.table == in_memory_pa_table.append_column(field_, column) assert isinstance(table, InMemoryTable) def test_in_memory_table_remove_column(in_memory_pa_table): table = InMemoryTable(in_memory_pa_table).remove_column(0) assert table.table == in_memory_pa_table.remove_column(0) assert isinstance(table, InMemoryTable) def test_in_memory_table_set_column(in_memory_pa_table): i = len(in_memory_pa_table.column_names) field_ = "new_field" column = pa.array(list(range(len(in_memory_pa_table)))) table = InMemoryTable(in_memory_pa_table).set_column(i, field_, column) assert table.table == in_memory_pa_table.set_column(i, field_, column) assert isinstance(table, InMemoryTable) def test_in_memory_table_rename_columns(in_memory_pa_table): assert "tokens" in in_memory_pa_table.column_names names = [name if name != "tokens" else "new_tokens" for name in in_memory_pa_table.column_names] table = InMemoryTable(in_memory_pa_table).rename_columns(names) assert table.table == in_memory_pa_table.rename_columns(names) assert isinstance(table, InMemoryTable) def test_in_memory_table_drop(in_memory_pa_table): names = [in_memory_pa_table.column_names[0]] table = InMemoryTable(in_memory_pa_table).drop(names) assert table.table == in_memory_pa_table.drop(names) assert isinstance(table, InMemoryTable) def test_memory_mapped_table_init(arrow_file, in_memory_pa_table): table = MemoryMappedTable(_memory_mapped_arrow_table_from_file(arrow_file), arrow_file) assert table.table == in_memory_pa_table assert isinstance(table, MemoryMappedTable) assert_deepcopy_without_bringing_data_in_memory(table) assert_pickle_without_bringing_data_in_memory(table) def test_memory_mapped_table_from_file(arrow_file, in_memory_pa_table): with assert_arrow_memory_doesnt_increase(): table = MemoryMappedTable.from_file(arrow_file) assert table.table == in_memory_pa_table assert isinstance(table, MemoryMappedTable) assert_deepcopy_without_bringing_data_in_memory(table) assert_pickle_without_bringing_data_in_memory(table) def test_memory_mapped_table_from_file_with_replay(arrow_file, in_memory_pa_table): replays = [("slice", (0, 1), {}), ("flatten", (), {})] with assert_arrow_memory_doesnt_increase(): table = MemoryMappedTable.from_file(arrow_file, replays=replays) assert len(table) == 1 for method, args, kwargs in replays: in_memory_pa_table = getattr(in_memory_pa_table, method)(*args, **kwargs) assert table.table == in_memory_pa_table assert_deepcopy_without_bringing_data_in_memory(table) assert_pickle_without_bringing_data_in_memory(table) def test_memory_mapped_table_deepcopy(arrow_file): table = MemoryMappedTable.from_file(arrow_file) copied_table = copy.deepcopy(table) assert table.table == copied_table.table assert table.path == copied_table.path assert_index_attributes_equal(table, copied_table) # deepcopy must return the exact same arrow objects since they are immutable assert table.table is copied_table.table assert all(batch1 is batch2 for batch1, batch2 in zip(table._batches, copied_table._batches)) def test_memory_mapped_table_pickle(arrow_file): table = MemoryMappedTable.from_file(arrow_file) pickled_table = pickle.dumps(table) unpickled_table = pickle.loads(pickled_table) assert unpickled_table.table == table.table assert unpickled_table.path == table.path assert_index_attributes_equal(table, unpickled_table) def test_memory_mapped_table_pickle_doesnt_fill_memory(arrow_file): with assert_arrow_memory_doesnt_increase(): table = MemoryMappedTable.from_file(arrow_file) assert_deepcopy_without_bringing_data_in_memory(table) assert_pickle_without_bringing_data_in_memory(table) def test_memory_mapped_table_pickle_applies_replay(arrow_file): replays = [("slice", (0, 1), {}), ("flatten", (), {})] with assert_arrow_memory_doesnt_increase(): table = MemoryMappedTable.from_file(arrow_file, replays=replays) assert isinstance(table, MemoryMappedTable) assert table.replays == replays assert_deepcopy_without_bringing_data_in_memory(table) assert_pickle_without_bringing_data_in_memory(table) def test_memory_mapped_table_slice(arrow_file, in_memory_pa_table): table = MemoryMappedTable.from_file(arrow_file).slice(1, 2) assert table.table == in_memory_pa_table.slice(1, 2) assert isinstance(table, MemoryMappedTable) assert table.replays == [("slice", (1, 2), {})] assert_deepcopy_without_bringing_data_in_memory(table) assert_pickle_without_bringing_data_in_memory(table) def test_memory_mapped_table_filter(arrow_file, in_memory_pa_table): mask = pa.array([i % 2 == 0 for i in range(len(in_memory_pa_table))]) table = MemoryMappedTable.from_file(arrow_file).filter(mask) assert table.table == in_memory_pa_table.filter(mask) assert isinstance(table, MemoryMappedTable) assert table.replays == [("filter", (mask,), {})] assert_deepcopy_without_bringing_data_in_memory(table) # filter DOES increase memory # assert_pickle_without_bringing_data_in_memory(table) assert_pickle_does_bring_data_in_memory(table) def test_memory_mapped_table_flatten(arrow_file, in_memory_pa_table): table = MemoryMappedTable.from_file(arrow_file).flatten() assert table.table == in_memory_pa_table.flatten() assert isinstance(table, MemoryMappedTable) assert table.replays == [("flatten", (), {})] assert_deepcopy_without_bringing_data_in_memory(table) assert_pickle_without_bringing_data_in_memory(table) def test_memory_mapped_table_combine_chunks(arrow_file, in_memory_pa_table): table = MemoryMappedTable.from_file(arrow_file).combine_chunks() assert table.table == in_memory_pa_table.combine_chunks() assert isinstance(table, MemoryMappedTable) assert table.replays == [("combine_chunks", (), {})] assert_deepcopy_without_bringing_data_in_memory(table) assert_pickle_without_bringing_data_in_memory(table) def test_memory_mapped_table_cast(arrow_file, in_memory_pa_table): assert pa.list_(pa.int64()) in in_memory_pa_table.schema.types schema = pa.schema( { k: v if v != pa.list_(pa.int64()) else pa.list_(pa.int32()) for k, v in zip(in_memory_pa_table.schema.names, in_memory_pa_table.schema.types) } ) table = MemoryMappedTable.from_file(arrow_file).cast(schema) assert table.table == in_memory_pa_table.cast(schema) assert isinstance(table, MemoryMappedTable) assert table.replays == [("cast", (schema,), {})] assert_deepcopy_without_bringing_data_in_memory(table) # cast DOES increase memory when converting integers precision for example # assert_pickle_without_bringing_data_in_memory(table) assert_pickle_does_bring_data_in_memory(table) def test_memory_mapped_table_replace_schema_metadata(arrow_file, in_memory_pa_table): metadata = {"huggingface": "{}"} table = MemoryMappedTable.from_file(arrow_file).replace_schema_metadata(metadata) assert table.table.schema.metadata == in_memory_pa_table.replace_schema_metadata(metadata).schema.metadata assert isinstance(table, MemoryMappedTable) assert table.replays == [("replace_schema_metadata", (metadata,), {})] assert_deepcopy_without_bringing_data_in_memory(table) assert_pickle_without_bringing_data_in_memory(table) def test_memory_mapped_table_add_column(arrow_file, in_memory_pa_table): i = len(in_memory_pa_table.column_names) field_ = "new_field" column = pa.array(list(range(len(in_memory_pa_table)))) table = MemoryMappedTable.from_file(arrow_file).add_column(i, field_, column) assert table.table == in_memory_pa_table.add_column(i, field_, column) assert isinstance(table, MemoryMappedTable) assert table.replays == [("add_column", (i, field_, column), {})] assert_deepcopy_without_bringing_data_in_memory(table) assert_pickle_without_bringing_data_in_memory(table) def test_memory_mapped_table_append_column(arrow_file, in_memory_pa_table): field_ = "new_field" column = pa.array(list(range(len(in_memory_pa_table)))) table = MemoryMappedTable.from_file(arrow_file).append_column(field_, column) assert table.table == in_memory_pa_table.append_column(field_, column) assert isinstance(table, MemoryMappedTable) assert table.replays == [("append_column", (field_, column), {})] assert_deepcopy_without_bringing_data_in_memory(table) assert_pickle_without_bringing_data_in_memory(table) def test_memory_mapped_table_remove_column(arrow_file, in_memory_pa_table): table = MemoryMappedTable.from_file(arrow_file).remove_column(0) assert table.table == in_memory_pa_table.remove_column(0) assert isinstance(table, MemoryMappedTable) assert table.replays == [("remove_column", (0,), {})] assert_deepcopy_without_bringing_data_in_memory(table) assert_pickle_without_bringing_data_in_memory(table) def test_memory_mapped_table_set_column(arrow_file, in_memory_pa_table): i = len(in_memory_pa_table.column_names) field_ = "new_field" column = pa.array(list(range(len(in_memory_pa_table)))) table = MemoryMappedTable.from_file(arrow_file).set_column(i, field_, column) assert table.table == in_memory_pa_table.set_column(i, field_, column) assert isinstance(table, MemoryMappedTable) assert table.replays == [("set_column", (i, field_, column), {})] assert_deepcopy_without_bringing_data_in_memory(table) assert_pickle_without_bringing_data_in_memory(table) def test_memory_mapped_table_rename_columns(arrow_file, in_memory_pa_table): assert "tokens" in in_memory_pa_table.column_names names = [name if name != "tokens" else "new_tokens" for name in in_memory_pa_table.column_names] table = MemoryMappedTable.from_file(arrow_file).rename_columns(names) assert table.table == in_memory_pa_table.rename_columns(names) assert isinstance(table, MemoryMappedTable) assert table.replays == [("rename_columns", (names,), {})] assert_deepcopy_without_bringing_data_in_memory(table) assert_pickle_without_bringing_data_in_memory(table) def test_memory_mapped_table_drop(arrow_file, in_memory_pa_table): names = [in_memory_pa_table.column_names[0]] table = MemoryMappedTable.from_file(arrow_file).drop(names) assert table.table == in_memory_pa_table.drop(names) assert isinstance(table, MemoryMappedTable) assert table.replays == [("drop", (names,), {})] assert_deepcopy_without_bringing_data_in_memory(table) assert_pickle_without_bringing_data_in_memory(table) @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_init( blocks_type, in_memory_pa_table, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = ( in_memory_blocks if blocks_type == "in_memory" else memory_mapped_blocks if blocks_type == "memory_mapped" else mixed_in_memory_and_memory_mapped_blocks ) table = ConcatenationTable(in_memory_pa_table, blocks) assert table.table == in_memory_pa_table assert table.blocks == blocks def test_concatenation_table_from_blocks(in_memory_pa_table, in_memory_blocks): assert len(in_memory_pa_table) > 2 in_memory_table = InMemoryTable(in_memory_pa_table) t1, t2 = in_memory_table.slice(0, 2), in_memory_table.slice(2) table = ConcatenationTable.from_blocks(in_memory_table) assert isinstance(table, ConcatenationTable) assert table.table == in_memory_pa_table assert table.blocks == [[in_memory_table]] table = ConcatenationTable.from_blocks([t1, t2]) assert isinstance(table, ConcatenationTable) assert table.table == in_memory_pa_table assert table.blocks == [[in_memory_table]] table = ConcatenationTable.from_blocks([[t1], [t2]]) assert isinstance(table, ConcatenationTable) assert table.table == in_memory_pa_table assert table.blocks == [[in_memory_table]] table = ConcatenationTable.from_blocks(in_memory_blocks) assert isinstance(table, ConcatenationTable) assert table.table == in_memory_pa_table assert table.blocks == [[in_memory_table]] @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_from_blocks_doesnt_increase_memory( blocks_type, in_memory_pa_table, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] with assert_arrow_memory_doesnt_increase(): table = ConcatenationTable.from_blocks(blocks) assert isinstance(table, ConcatenationTable) assert table.table == in_memory_pa_table if blocks_type == "in_memory": assert table.blocks == [[InMemoryTable(in_memory_pa_table)]] else: assert table.blocks == blocks @pytest.mark.parametrize("axis", [0, 1]) def test_concatenation_table_from_tables(axis, in_memory_pa_table, arrow_file): in_memory_table = InMemoryTable(in_memory_pa_table) concatenation_table = ConcatenationTable.from_blocks(in_memory_table) memory_mapped_table = MemoryMappedTable.from_file(arrow_file) tables = [in_memory_pa_table, in_memory_table, concatenation_table, memory_mapped_table] if axis == 0: expected_table = pa.concat_tables([in_memory_pa_table] * len(tables)) else: # avoids error due to duplicate column names tables[1:] = [add_suffix_to_column_names(table, i) for i, table in enumerate(tables[1:], 1)] expected_table = in_memory_pa_table for table in tables[1:]: for name, col in zip(table.column_names, table.columns): expected_table = expected_table.append_column(name, col) with assert_arrow_memory_doesnt_increase(): table = ConcatenationTable.from_tables(tables, axis=axis) assert isinstance(table, ConcatenationTable) assert table.table == expected_table # because of consolidation, we end up with 1 InMemoryTable and 1 MemoryMappedTable assert len(table.blocks) == 1 if axis == 1 else 2 assert len(table.blocks[0]) == 1 if axis == 0 else 2 assert axis == 1 or len(table.blocks[1]) == 1 assert isinstance(table.blocks[0][0], InMemoryTable) assert isinstance(table.blocks[1][0] if axis == 0 else table.blocks[0][1], MemoryMappedTable) def test_concatenation_table_from_tables_axis1_misaligned_blocks(arrow_file): table = MemoryMappedTable.from_file(arrow_file) t1 = table.slice(0, 2) t2 = table.slice(0, 3).rename_columns([col + "_1" for col in table.column_names]) concatenated = ConcatenationTable.from_tables( [ ConcatenationTable.from_blocks([[t1], [t1], [t1]]), ConcatenationTable.from_blocks([[t2], [t2]]), ], axis=1, ) assert len(concatenated) == 6 assert [len(row_blocks[0]) for row_blocks in concatenated.blocks] == [2, 1, 1, 2] concatenated = ConcatenationTable.from_tables( [ ConcatenationTable.from_blocks([[t2], [t2]]), ConcatenationTable.from_blocks([[t1], [t1], [t1]]), ], axis=1, ) assert len(concatenated) == 6 assert [len(row_blocks[0]) for row_blocks in concatenated.blocks] == [2, 1, 1, 2] @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_deepcopy( blocks_type, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] table = ConcatenationTable.from_blocks(blocks) copied_table = copy.deepcopy(table) assert table.table == copied_table.table assert table.blocks == copied_table.blocks assert_index_attributes_equal(table, copied_table) # deepcopy must return the exact same arrow objects since they are immutable assert table.table is copied_table.table assert all(batch1 is batch2 for batch1, batch2 in zip(table._batches, copied_table._batches)) @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_pickle( blocks_type, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] table = ConcatenationTable.from_blocks(blocks) pickled_table = pickle.dumps(table) unpickled_table = pickle.loads(pickled_table) assert unpickled_table.table == table.table assert unpickled_table.blocks == table.blocks assert_index_attributes_equal(table, unpickled_table) def test_concat_tables_with_features_metadata(arrow_file, in_memory_pa_table): input_features = Features.from_arrow_schema(in_memory_pa_table.schema) input_features["id"] = Value("int64", id="my_id") intput_schema = input_features.arrow_schema t0 = in_memory_pa_table.replace_schema_metadata(intput_schema.metadata) t1 = MemoryMappedTable.from_file(arrow_file) tables = [t0, t1] concatenated_table = concat_tables(tables, axis=0) output_schema = concatenated_table.schema output_features = Features.from_arrow_schema(output_schema) assert output_schema == intput_schema assert output_schema.metadata == intput_schema.metadata assert output_features == input_features assert output_features["id"].id == "my_id" @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_slice( blocks_type, in_memory_pa_table, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] table = ConcatenationTable.from_blocks(blocks).slice(1, 2) assert table.table == in_memory_pa_table.slice(1, 2) assert isinstance(table, ConcatenationTable) @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_filter( blocks_type, in_memory_pa_table, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] mask = pa.array([i % 2 == 0 for i in range(len(in_memory_pa_table))]) table = ConcatenationTable.from_blocks(blocks).filter(mask) assert table.table == in_memory_pa_table.filter(mask) assert isinstance(table, ConcatenationTable) @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_flatten( blocks_type, in_memory_pa_table, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] table = ConcatenationTable.from_blocks(blocks).flatten() assert table.table == in_memory_pa_table.flatten() assert isinstance(table, ConcatenationTable) @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_combine_chunks( blocks_type, in_memory_pa_table, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] table = ConcatenationTable.from_blocks(blocks).combine_chunks() assert table.table == in_memory_pa_table.combine_chunks() assert isinstance(table, ConcatenationTable) @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_cast( blocks_type, in_memory_pa_table, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] assert pa.list_(pa.int64()) in in_memory_pa_table.schema.types assert pa.int64() in in_memory_pa_table.schema.types schema = pa.schema( { k: v if v != pa.list_(pa.int64()) else pa.list_(pa.int32()) for k, v in zip(in_memory_pa_table.schema.names, in_memory_pa_table.schema.types) } ) table = ConcatenationTable.from_blocks(blocks).cast(schema) assert table.table == in_memory_pa_table.cast(schema) assert isinstance(table, ConcatenationTable) schema = pa.schema( { k: v if v != pa.int64() else pa.int32() for k, v in zip(in_memory_pa_table.schema.names, in_memory_pa_table.schema.types) } ) table = ConcatenationTable.from_blocks(blocks).cast(schema) assert table.table == in_memory_pa_table.cast(schema) assert isinstance(table, ConcatenationTable) @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concat_tables_cast_with_features_metadata( blocks_type, in_memory_pa_table, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] input_features = Features.from_arrow_schema(in_memory_pa_table.schema) input_features["id"] = Value("int64", id="my_id") intput_schema = input_features.arrow_schema concatenated_table = ConcatenationTable.from_blocks(blocks).cast(intput_schema) output_schema = concatenated_table.schema output_features = Features.from_arrow_schema(output_schema) assert output_schema == intput_schema assert output_schema.metadata == intput_schema.metadata assert output_features == input_features assert output_features["id"].id == "my_id" @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_replace_schema_metadata( blocks_type, in_memory_pa_table, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] metadata = {"huggingface": "{}"} table = ConcatenationTable.from_blocks(blocks).replace_schema_metadata(metadata) assert table.table.schema.metadata == in_memory_pa_table.replace_schema_metadata(metadata).schema.metadata assert isinstance(table, ConcatenationTable) @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_add_column( blocks_type, in_memory_pa_table, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] i = len(in_memory_pa_table.column_names) field_ = "new_field" column = pa.array(list(range(len(in_memory_pa_table)))) with pytest.raises(NotImplementedError): ConcatenationTable.from_blocks(blocks).add_column(i, field_, column) # assert table.table == in_memory_pa_table.add_column(i, field_, column) # unpickled_table = pickle.loads(pickle.dumps(table)) # assert unpickled_table.table == in_memory_pa_table.add_column(i, field_, column) @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_append_column( blocks_type, in_memory_pa_table, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] field_ = "new_field" column = pa.array(list(range(len(in_memory_pa_table)))) with pytest.raises(NotImplementedError): ConcatenationTable.from_blocks(blocks).append_column(field_, column) # assert table.table == in_memory_pa_table.append_column(field_, column) # unpickled_table = pickle.loads(pickle.dumps(table)) # assert unpickled_table.table == in_memory_pa_table.append_column(field_, column) @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_remove_column( blocks_type, in_memory_pa_table, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] table = ConcatenationTable.from_blocks(blocks).remove_column(0) assert table.table == in_memory_pa_table.remove_column(0) assert isinstance(table, ConcatenationTable) @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_set_column( blocks_type, in_memory_pa_table, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] i = len(in_memory_pa_table.column_names) field_ = "new_field" column = pa.array(list(range(len(in_memory_pa_table)))) with pytest.raises(NotImplementedError): ConcatenationTable.from_blocks(blocks).set_column(i, field_, column) # assert table.table == in_memory_pa_table.set_column(i, field_, column) # unpickled_table = pickle.loads(pickle.dumps(table)) # assert unpickled_table.table == in_memory_pa_table.set_column(i, field_, column) @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_rename_columns( blocks_type, in_memory_pa_table, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] assert "tokens" in in_memory_pa_table.column_names names = [name if name != "tokens" else "new_tokens" for name in in_memory_pa_table.column_names] table = ConcatenationTable.from_blocks(blocks).rename_columns(names) assert isinstance(table, ConcatenationTable) assert table.table == in_memory_pa_table.rename_columns(names) @pytest.mark.parametrize("blocks_type", ["in_memory", "memory_mapped", "mixed"]) def test_concatenation_table_drop( blocks_type, in_memory_pa_table, in_memory_blocks, memory_mapped_blocks, mixed_in_memory_and_memory_mapped_blocks ): blocks = { "in_memory": in_memory_blocks, "memory_mapped": memory_mapped_blocks, "mixed": mixed_in_memory_and_memory_mapped_blocks, }[blocks_type] names = [in_memory_pa_table.column_names[0]] table = ConcatenationTable.from_blocks(blocks).drop(names) assert table.table == in_memory_pa_table.drop(names) assert isinstance(table, ConcatenationTable) def test_concat_tables(arrow_file, in_memory_pa_table): t0 = in_memory_pa_table t1 = InMemoryTable(t0) t2 = MemoryMappedTable.from_file(arrow_file) t3 = ConcatenationTable.from_blocks(t1) tables = [t0, t1, t2, t3] concatenated_table = concat_tables(tables, axis=0) assert concatenated_table.table == pa.concat_tables([t0] * 4) assert concatenated_table.table.shape == (40, 4) assert isinstance(concatenated_table, ConcatenationTable) assert len(concatenated_table.blocks) == 3 # t0 and t1 are consolidated as a single InMemoryTable assert isinstance(concatenated_table.blocks[0][0], InMemoryTable) assert isinstance(concatenated_table.blocks[1][0], MemoryMappedTable) assert isinstance(concatenated_table.blocks[2][0], InMemoryTable) # add suffix to avoid error due to duplicate column names concatenated_table = concat_tables( [add_suffix_to_column_names(table, i) for i, table in enumerate(tables)], axis=1 ) assert concatenated_table.table.shape == (10, 16) assert len(concatenated_table.blocks[0]) == 3 # t0 and t1 are consolidated as a single InMemoryTable assert isinstance(concatenated_table.blocks[0][0], InMemoryTable) assert isinstance(concatenated_table.blocks[0][1], MemoryMappedTable) assert isinstance(concatenated_table.blocks[0][2], InMemoryTable) def _interpolation_search_ground_truth(arr: List[int], x: int) -> Union[int, IndexError]: for i in range(len(arr) - 1): if arr[i] <= x < arr[i + 1]: return i return IndexError class _ListWithGetitemCounter(list): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.unique_getitem_calls = set() def __getitem__(self, i): out = super().__getitem__(i) self.unique_getitem_calls.add(i) return out @property def getitem_unique_count(self): return len(self.unique_getitem_calls) @pytest.mark.parametrize( "arr, x", [(np.arange(0, 14, 3), x) for x in range(-1, 22)] + [(list(np.arange(-5, 5)), x) for x in range(-6, 6)] + [([0, 1_000, 1_001, 1_003], x) for x in [-1, 0, 2, 100, 999, 1_000, 1_001, 1_002, 1_003, 1_004]] + [(list(range(1_000)), x) for x in [-1, 0, 1, 10, 666, 999, 1_000, 1_0001]], ) def test_interpolation_search(arr, x): ground_truth = _interpolation_search_ground_truth(arr, x) if isinstance(ground_truth, int): arr = _ListWithGetitemCounter(arr) output = _interpolation_search(arr, x) assert ground_truth == output # 4 maximum unique getitem calls is expected for the cases of this test # but it can be bigger for large and messy arrays. assert arr.getitem_unique_count <= 4 else: with pytest.raises(ground_truth): _interpolation_search(arr, x) def test_indexed_table_mixin(): n_rows_per_chunk = 10 n_chunks = 4 pa_table = pa.Table.from_pydict({"col": [0] * n_rows_per_chunk}) pa_table = pa.concat_tables([pa_table] * n_chunks) table = Table(pa_table) assert all(table._offsets.tolist() == np.cumsum([0] + [n_rows_per_chunk] * n_chunks)) assert table.fast_slice(5) == pa_table.slice(5) assert table.fast_slice(2, 13) == pa_table.slice(2, 13) @pytest.mark.parametrize( "arrays", [ [pa.array([[1, 2, 3, 4]]), pa.array([[10, 2]])], [ pa.array([[[1, 2], [3]]], pa.list_(pa.list_(pa.int32()), 2)), pa.array([[[10, 2, 3], [2]]], pa.list_(pa.list_(pa.int32()), 2)), ], [pa.array([[[1, 2, 3]], [[2, 3], [20, 21]], [[4]]]).slice(1), pa.array([[[1, 2, 3]]])], ], ) def test_concat_arrays(arrays): assert array_concat(arrays) == pa.concat_arrays(arrays) def test_concat_arrays_nested_with_nulls(): arrays = [pa.array([{"a": 21, "b": [[1, 2], [3]]}]), pa.array([{"a": 100, "b": [[1], None]}])] concatenated_arrays = array_concat(arrays) assert concatenated_arrays == pa.array([{"a": 21, "b": [[1, 2], [3]]}, {"a": 100, "b": [[1], None]}]) def test_concat_extension_arrays(): arrays = [pa.array([[[1, 2], [3, 4]]]), pa.array([[[10, 2], [3, 4]]])] extension_type = Array2DExtensionType((2, 2), "int64") assert array_concat([extension_type.wrap_array(array) for array in arrays]) == extension_type.wrap_array( pa.concat_arrays(arrays) ) def test_cast_array_to_features(): arr = pa.array([[0, 1]]) assert cast_array_to_feature(arr, Sequence(Value("string"))).type == pa.list_(pa.string()) with pytest.raises(TypeError): cast_array_to_feature(arr, Sequence(Value("string")), allow_number_to_str=False) def test_cast_array_to_features_nested(): arr = pa.array([[{"foo": [0]}]]) assert cast_array_to_feature(arr, [{"foo": Sequence(Value("string"))}]).type == pa.list_( pa.struct({"foo": pa.list_(pa.string())}) ) def test_cast_array_to_features_to_nested_with_no_fields(): arr = pa.array([{}]) assert cast_array_to_feature(arr, {}).type == pa.struct({}) assert cast_array_to_feature(arr, {}).to_pylist() == arr.to_pylist() def test_cast_array_to_features_nested_with_null_values(): # same type arr = pa.array([{"foo": [None, [0]]}], pa.struct({"foo": pa.list_(pa.list_(pa.int64()))})) casted_array = cast_array_to_feature(arr, {"foo": [[Value("int64")]]}) assert casted_array.type == pa.struct({"foo": pa.list_(pa.list_(pa.int64()))}) assert casted_array.to_pylist() == arr.to_pylist() # different type arr = pa.array([{"foo": [None, [0]]}], pa.struct({"foo": pa.list_(pa.list_(pa.int64()))})) if datasets.config.PYARROW_VERSION.major < 10: with pytest.warns(UserWarning, match="None values are converted to empty lists.+"): casted_array = cast_array_to_feature(arr, {"foo": [[Value("int32")]]}) assert casted_array.type == pa.struct({"foo": pa.list_(pa.list_(pa.int32()))}) assert casted_array.to_pylist() == [ {"foo": [[], [0]]} ] # empty list because of https://github.com/huggingface/datasets/issues/3676 else: with warnings.catch_warnings(): warnings.simplefilter("error") casted_array = cast_array_to_feature(arr, {"foo": [[Value("int32")]]}) assert casted_array.type == pa.struct({"foo": pa.list_(pa.list_(pa.int32()))}) assert casted_array.to_pylist() == [{"foo": [None, [0]]}] def test_cast_array_to_features_to_null_type(): # same type arr = pa.array([[None, None]]) assert cast_array_to_feature(arr, Sequence(Value("null"))).type == pa.list_(pa.null()) # different type arr = pa.array([[None, 1]]) with pytest.raises(TypeError): cast_array_to_feature(arr, Sequence(Value("null"))) def test_cast_array_to_features_sequence_classlabel(): arr = pa.array([[], [1], [0, 1]], pa.list_(pa.int64())) assert cast_array_to_feature(arr, Sequence(ClassLabel(names=["foo", "bar"]))).type == pa.list_(pa.int64()) arr = pa.array([[], ["bar"], ["foo", "bar"]], pa.list_(pa.string())) assert cast_array_to_feature(arr, Sequence(ClassLabel(names=["foo", "bar"]))).type == pa.list_(pa.int64()) # Test empty arrays arr = pa.array([[], []], pa.list_(pa.int64())) assert cast_array_to_feature(arr, Sequence(ClassLabel(names=["foo", "bar"]))).type == pa.list_(pa.int64()) arr = pa.array([[], []], pa.list_(pa.string())) assert cast_array_to_feature(arr, Sequence(ClassLabel(names=["foo", "bar"]))).type == pa.list_(pa.int64()) # Test invalid class labels arr = pa.array([[2]], pa.list_(pa.int64())) with pytest.raises(ValueError): assert cast_array_to_feature(arr, Sequence(ClassLabel(names=["foo", "bar"]))) arr = pa.array([["baz"]], pa.list_(pa.string())) with pytest.raises(ValueError): assert cast_array_to_feature(arr, Sequence(ClassLabel(names=["foo", "bar"]))) def test_cast_sliced_fixed_size_array_to_features(): arr = pa.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], pa.list_(pa.int32(), 3)) casted_array = cast_array_to_feature(arr[1:], Sequence(Value("int64"), length=3)) assert casted_array.type == pa.list_(pa.int64(), 3) assert casted_array.to_pylist() == arr[1:].to_pylist() def test_embed_array_storage(image_file): array = pa.array([{"bytes": None, "path": image_file}], type=Image.pa_type) embedded_images_array = embed_array_storage(array, Image()) assert isinstance(embedded_images_array.to_pylist()[0]["path"], str) assert embedded_images_array.to_pylist()[0]["path"] == "test_image_rgb.jpg" assert isinstance(embedded_images_array.to_pylist()[0]["bytes"], bytes) def test_embed_array_storage_nested(image_file): array = pa.array([[{"bytes": None, "path": image_file}]], type=pa.list_(Image.pa_type)) embedded_images_array = embed_array_storage(array, [Image()]) assert isinstance(embedded_images_array.to_pylist()[0][0]["path"], str) assert isinstance(embedded_images_array.to_pylist()[0][0]["bytes"], bytes) array = pa.array([{"foo": {"bytes": None, "path": image_file}}], type=pa.struct({"foo": Image.pa_type})) embedded_images_array = embed_array_storage(array, {"foo": Image()}) assert isinstance(embedded_images_array.to_pylist()[0]["foo"]["path"], str) assert isinstance(embedded_images_array.to_pylist()[0]["foo"]["bytes"], bytes) def test_embed_table_storage(image_file): features = Features({"image": Image()}) table = table_cast(pa.table({"image": [image_file]}), features.arrow_schema) embedded_images_table = embed_table_storage(table) assert isinstance(embedded_images_table.to_pydict()["image"][0]["path"], str) assert isinstance(embedded_images_table.to_pydict()["image"][0]["bytes"], bytes) @pytest.mark.parametrize( "table", [ InMemoryTable(pa.table({"foo": range(10)})), InMemoryTable(pa.concat_tables([pa.table({"foo": range(0, 5)}), pa.table({"foo": range(5, 10)})])), InMemoryTable(pa.concat_tables([pa.table({"foo": [i]}) for i in range(10)])), ], ) @pytest.mark.parametrize("batch_size", [1, 2, 3, 9, 10, 11, 20]) @pytest.mark.parametrize("drop_last_batch", [False, True]) def test_table_iter(table, batch_size, drop_last_batch): num_rows = len(table) if not drop_last_batch else len(table) // batch_size * batch_size num_batches = (num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size subtables = list(table_iter(table, batch_size=batch_size, drop_last_batch=drop_last_batch)) assert len(subtables) == num_batches if drop_last_batch: assert all(len(subtable) == batch_size for subtable in subtables) else: assert all(len(subtable) == batch_size for subtable in subtables[:-1]) assert len(subtables[-1]) <= batch_size if num_rows > 0: reloaded = pa.concat_tables(subtables) assert table.slice(0, num_rows).to_pydict() == reloaded.to_pydict() @pytest.mark.parametrize( "pa_type, expected", [ (pa.int8(), False), (pa.struct({"col1": pa.int8(), "col2": pa.int64()}), False), (pa.struct({"col1": pa.list_(pa.int8()), "col2": Array2DExtensionType((1, 3), "int64")}), True), (pa.list_(pa.int8()), False), (pa.list_(Array2DExtensionType((1, 3), "int64"), 4), True), ], ) def test_is_extension_type(pa_type, expected): assert _is_extension_type(pa_type) == expected
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_tasks.py
from copy import deepcopy from unittest.case import TestCase import pytest from datasets.arrow_dataset import Dataset from datasets.features import Audio, ClassLabel, Features, Image, Sequence, Value from datasets.info import DatasetInfo from datasets.tasks import ( AudioClassification, AutomaticSpeechRecognition, ImageClassification, LanguageModeling, QuestionAnsweringExtractive, Summarization, TextClassification, task_template_from_dict, ) from datasets.utils.py_utils import asdict SAMPLE_QUESTION_ANSWERING_EXTRACTIVE = { "id": "5733be284776f41900661182", "title": "University_of_Notre_Dame", "context": 'Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend "Venite Ad Me Omnes". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.', "question": "To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?", "answers": {"text": ["Saint Bernadette Soubirous"], "answer_start": [515]}, } @pytest.mark.parametrize( "task_cls", [ AudioClassification, AutomaticSpeechRecognition, ImageClassification, LanguageModeling, QuestionAnsweringExtractive, Summarization, TextClassification, ], ) def test_reload_task_from_dict(task_cls): task = task_cls() task_dict = asdict(task) reloaded = task_template_from_dict(task_dict) assert task == reloaded class TestLanguageModeling: def test_column_mapping(self): task = LanguageModeling(text_column="input_text") assert {"input_text": "text"} == task.column_mapping def test_from_dict(self): input_schema = Features({"text": Value("string")}) template_dict = {"text_column": "input_text"} task = LanguageModeling.from_dict(template_dict) assert "language-modeling" == task.task assert input_schema == task.input_schema class TextClassificationTest(TestCase): def setUp(self): self.labels = sorted(["pos", "neg"]) def test_column_mapping(self): task = TextClassification(text_column="input_text", label_column="input_label") self.assertDictEqual({"input_text": "text", "input_label": "labels"}, task.column_mapping) def test_from_dict(self): input_schema = Features({"text": Value("string")}) # Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here label_schema = Features({"labels": ClassLabel}) template_dict = {"text_column": "input_text", "label_column": "input_labels"} task = TextClassification.from_dict(template_dict) self.assertEqual("text-classification", task.task) self.assertEqual(input_schema, task.input_schema) self.assertEqual(label_schema, task.label_schema) def test_align_with_features(self): task = TextClassification(text_column="input_text", label_column="input_label") self.assertEqual(task.label_schema["labels"], ClassLabel) task = task.align_with_features(Features({"input_label": ClassLabel(names=self.labels)})) self.assertEqual(task.label_schema["labels"], ClassLabel(names=self.labels)) class QuestionAnsweringTest(TestCase): def test_column_mapping(self): task = QuestionAnsweringExtractive( context_column="input_context", question_column="input_question", answers_column="input_answers" ) self.assertDictEqual( {"input_context": "context", "input_question": "question", "input_answers": "answers"}, task.column_mapping ) def test_from_dict(self): input_schema = Features({"question": Value("string"), "context": Value("string")}) label_schema = Features( { "answers": Sequence( { "text": Value("string"), "answer_start": Value("int32"), } ) } ) template_dict = { "context_column": "input_input_context", "question_column": "input_question", "answers_column": "input_answers", } task = QuestionAnsweringExtractive.from_dict(template_dict) self.assertEqual("question-answering-extractive", task.task) self.assertEqual(input_schema, task.input_schema) self.assertEqual(label_schema, task.label_schema) class SummarizationTest(TestCase): def test_column_mapping(self): task = Summarization(text_column="input_text", summary_column="input_summary") self.assertDictEqual({"input_text": "text", "input_summary": "summary"}, task.column_mapping) def test_from_dict(self): input_schema = Features({"text": Value("string")}) label_schema = Features({"summary": Value("string")}) template_dict = {"text_column": "input_text", "summary_column": "input_summary"} task = Summarization.from_dict(template_dict) self.assertEqual("summarization", task.task) self.assertEqual(input_schema, task.input_schema) self.assertEqual(label_schema, task.label_schema) class AutomaticSpeechRecognitionTest(TestCase): def test_column_mapping(self): task = AutomaticSpeechRecognition(audio_column="input_audio", transcription_column="input_transcription") self.assertDictEqual({"input_audio": "audio", "input_transcription": "transcription"}, task.column_mapping) def test_from_dict(self): input_schema = Features({"audio": Audio()}) label_schema = Features({"transcription": Value("string")}) template_dict = { "audio_column": "input_audio", "transcription_column": "input_transcription", } task = AutomaticSpeechRecognition.from_dict(template_dict) self.assertEqual("automatic-speech-recognition", task.task) self.assertEqual(input_schema, task.input_schema) self.assertEqual(label_schema, task.label_schema) class AudioClassificationTest(TestCase): def setUp(self): self.labels = sorted(["pos", "neg"]) def test_column_mapping(self): task = AudioClassification(audio_column="input_audio", label_column="input_label") self.assertDictEqual({"input_audio": "audio", "input_label": "labels"}, task.column_mapping) def test_from_dict(self): input_schema = Features({"audio": Audio()}) label_schema = Features({"labels": ClassLabel}) template_dict = { "audio_column": "input_image", "label_column": "input_label", } task = AudioClassification.from_dict(template_dict) self.assertEqual("audio-classification", task.task) self.assertEqual(input_schema, task.input_schema) self.assertEqual(label_schema, task.label_schema) def test_align_with_features(self): task = AudioClassification(audio_column="input_audio", label_column="input_label") self.assertEqual(task.label_schema["labels"], ClassLabel) task = task.align_with_features(Features({"input_label": ClassLabel(names=self.labels)})) self.assertEqual(task.label_schema["labels"], ClassLabel(names=self.labels)) class ImageClassificationTest(TestCase): def setUp(self): self.labels = sorted(["pos", "neg"]) def test_column_mapping(self): task = ImageClassification(image_column="input_image", label_column="input_label") self.assertDictEqual({"input_image": "image", "input_label": "labels"}, task.column_mapping) def test_from_dict(self): input_schema = Features({"image": Image()}) label_schema = Features({"labels": ClassLabel}) template_dict = { "image_column": "input_image", "label_column": "input_label", } task = ImageClassification.from_dict(template_dict) self.assertEqual("image-classification", task.task) self.assertEqual(input_schema, task.input_schema) self.assertEqual(label_schema, task.label_schema) def test_align_with_features(self): task = ImageClassification(image_column="input_image", label_column="input_label") self.assertEqual(task.label_schema["labels"], ClassLabel) task = task.align_with_features(Features({"input_label": ClassLabel(names=self.labels)})) self.assertEqual(task.label_schema["labels"], ClassLabel(names=self.labels)) class DatasetWithTaskProcessingTest(TestCase): def test_map_on_task_template(self): info = DatasetInfo(task_templates=QuestionAnsweringExtractive()) dataset = Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}, info=info) assert isinstance(dataset.info.task_templates, list) assert len(dataset.info.task_templates) == 1 def keep_task(x): return x def dont_keep_task(x): out = deepcopy(SAMPLE_QUESTION_ANSWERING_EXTRACTIVE) out["answers"]["foobar"] = 0 return out mapped_dataset = dataset.map(keep_task) assert mapped_dataset.info.task_templates == dataset.info.task_templates # reload from cache mapped_dataset = dataset.map(keep_task) assert mapped_dataset.info.task_templates == dataset.info.task_templates mapped_dataset = dataset.map(dont_keep_task) assert mapped_dataset.info.task_templates == [] # reload from cache mapped_dataset = dataset.map(dont_keep_task) assert mapped_dataset.info.task_templates == [] def test_remove_and_map_on_task_template(self): features = Features({"text": Value("string"), "label": ClassLabel(names=("pos", "neg"))}) task_templates = TextClassification(text_column="text", label_column="label") info = DatasetInfo(features=features, task_templates=task_templates) dataset = Dataset.from_dict({"text": ["A sentence."], "label": ["pos"]}, info=info) def process(example): return example modified_dataset = dataset.remove_columns("label") mapped_dataset = modified_dataset.map(process) assert mapped_dataset.info.task_templates == []
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_upstream_hub.py
import fnmatch import os import tempfile import time import unittest from io import BytesIO from pathlib import Path from unittest.mock import patch import numpy as np import pytest from huggingface_hub import DatasetCard, HfApi from datasets import ( Audio, ClassLabel, Dataset, DatasetDict, Features, Image, Value, load_dataset, load_dataset_builder, ) from datasets.config import METADATA_CONFIGS_FIELD from datasets.utils.file_utils import cached_path from datasets.utils.hub import hf_hub_url from tests.fixtures.hub import CI_HUB_ENDPOINT, CI_HUB_USER, CI_HUB_USER_TOKEN from tests.utils import for_all_test_methods, require_pil, require_sndfile, xfail_if_500_502_http_error pytestmark = pytest.mark.integration @for_all_test_methods(xfail_if_500_502_http_error) @pytest.mark.usefixtures("ci_hub_config", "ci_hfh_hf_hub_url") class TestPushToHub: _api = HfApi(endpoint=CI_HUB_ENDPOINT) _token = CI_HUB_USER_TOKEN def test_push_dataset_dict_to_hub_no_token(self, temporary_repo, set_ci_hub_access_token): ds = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) local_ds = DatasetDict({"train": ds}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: local_ds.push_to_hub(ds_name) hub_ds = load_dataset(ds_name, download_mode="force_redownload") assert local_ds.column_names == hub_ds.column_names assert list(local_ds["train"].features.keys()) == list(hub_ds["train"].features.keys()) assert local_ds["train"].features == hub_ds["train"].features # Ensure that there is a single file on the repository that has the correct name files = sorted(self._api.list_repo_files(ds_name, repo_type="dataset")) assert all( fnmatch.fnmatch(file, expected_file) for file, expected_file in zip( files, [".gitattributes", "README.md", "data/train-00000-of-00001-*.parquet"] ) ) def test_push_dataset_dict_to_hub_name_without_namespace(self, temporary_repo): ds = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) local_ds = DatasetDict({"train": ds}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: local_ds.push_to_hub(ds_name.split("/")[-1], token=self._token) hub_ds = load_dataset(ds_name, download_mode="force_redownload") assert local_ds.column_names == hub_ds.column_names assert list(local_ds["train"].features.keys()) == list(hub_ds["train"].features.keys()) assert local_ds["train"].features == hub_ds["train"].features # Ensure that there is a single file on the repository that has the correct name files = sorted(self._api.list_repo_files(ds_name, repo_type="dataset")) assert all( fnmatch.fnmatch(file, expected_file) for file, expected_file in zip( files, [".gitattributes", "README.md", "data/train-00000-of-00001-*.parquet"] ) ) def test_push_dataset_dict_to_hub_datasets_with_different_features(self, cleanup_repo): ds_train = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) ds_test = Dataset.from_dict({"x": [True, False, True], "y": ["a", "b", "c"]}) local_ds = DatasetDict({"train": ds_train, "test": ds_test}) ds_name = f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}" try: with pytest.raises(ValueError): local_ds.push_to_hub(ds_name.split("/")[-1], token=self._token) except AssertionError: cleanup_repo(ds_name) raise def test_push_dataset_dict_to_hub_private(self, temporary_repo): ds = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) local_ds = DatasetDict({"train": ds}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: local_ds.push_to_hub(ds_name, token=self._token, private=True) hub_ds = load_dataset(ds_name, download_mode="force_redownload", token=self._token) assert local_ds.column_names == hub_ds.column_names assert list(local_ds["train"].features.keys()) == list(hub_ds["train"].features.keys()) assert local_ds["train"].features == hub_ds["train"].features # Ensure that there is a single file on the repository that has the correct name files = sorted(self._api.list_repo_files(ds_name, repo_type="dataset", token=self._token)) assert all( fnmatch.fnmatch(file, expected_file) for file, expected_file in zip( files, [".gitattributes", "README.md", "data/train-00000-of-00001-*.parquet"] ) ) def test_push_dataset_dict_to_hub(self, temporary_repo): ds = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) local_ds = DatasetDict({"train": ds}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: local_ds.push_to_hub(ds_name, token=self._token) hub_ds = load_dataset(ds_name, download_mode="force_redownload") assert local_ds.column_names == hub_ds.column_names assert list(local_ds["train"].features.keys()) == list(hub_ds["train"].features.keys()) assert local_ds["train"].features == hub_ds["train"].features # Ensure that there is a single file on the repository that has the correct name files = sorted(self._api.list_repo_files(ds_name, repo_type="dataset", token=self._token)) assert all( fnmatch.fnmatch(file, expected_file) for file, expected_file in zip( files, [".gitattributes", "README.md", "data/train-00000-of-00001-*.parquet"] ) ) def test_push_dataset_dict_to_hub_multiple_files(self, temporary_repo): ds = Dataset.from_dict({"x": list(range(1000)), "y": list(range(1000))}) local_ds = DatasetDict({"train": ds}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: with patch("datasets.config.MAX_SHARD_SIZE", "16KB"): local_ds.push_to_hub(ds_name, token=self._token) hub_ds = load_dataset(ds_name, download_mode="force_redownload") assert local_ds.column_names == hub_ds.column_names assert list(local_ds["train"].features.keys()) == list(hub_ds["train"].features.keys()) assert local_ds["train"].features == hub_ds["train"].features # Ensure that there are two files on the repository that have the correct name files = sorted(self._api.list_repo_files(ds_name, repo_type="dataset", token=self._token)) assert all( fnmatch.fnmatch(file, expected_file) for file, expected_file in zip( files, [ ".gitattributes", "README.md", "data/train-00000-of-00002-*.parquet", "data/train-00001-of-00002-*.parquet", ], ) ) def test_push_dataset_dict_to_hub_multiple_files_with_max_shard_size(self, temporary_repo): ds = Dataset.from_dict({"x": list(range(1000)), "y": list(range(1000))}) local_ds = DatasetDict({"train": ds}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: local_ds.push_to_hub(ds_name, token=self._token, max_shard_size="16KB") hub_ds = load_dataset(ds_name, download_mode="force_redownload") assert local_ds.column_names == hub_ds.column_names assert list(local_ds["train"].features.keys()) == list(hub_ds["train"].features.keys()) assert local_ds["train"].features == hub_ds["train"].features # Ensure that there are two files on the repository that have the correct name files = sorted(self._api.list_repo_files(ds_name, repo_type="dataset", token=self._token)) assert all( fnmatch.fnmatch(file, expected_file) for file, expected_file in zip( files, [ ".gitattributes", "README.md", "data/train-00000-of-00002-*.parquet", "data/train-00001-of-00002-*.parquet", ], ) ) def test_push_dataset_dict_to_hub_multiple_files_with_num_shards(self, temporary_repo): ds = Dataset.from_dict({"x": list(range(1000)), "y": list(range(1000))}) local_ds = DatasetDict({"train": ds}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: local_ds.push_to_hub(ds_name, token=self._token, num_shards={"train": 2}) hub_ds = load_dataset(ds_name, download_mode="force_redownload") assert local_ds.column_names == hub_ds.column_names assert list(local_ds["train"].features.keys()) == list(hub_ds["train"].features.keys()) assert local_ds["train"].features == hub_ds["train"].features # Ensure that there are two files on the repository that have the correct name files = sorted(self._api.list_repo_files(ds_name, repo_type="dataset", token=self._token)) assert all( fnmatch.fnmatch(file, expected_file) for file, expected_file in zip( files, [ ".gitattributes", "README.md", "data/train-00000-of-00002-*.parquet", "data/train-00001-of-00002-*.parquet", ], ) ) def test_push_dataset_dict_to_hub_overwrite_files(self, temporary_repo): ds = Dataset.from_dict({"x": list(range(1000)), "y": list(range(1000))}) ds2 = Dataset.from_dict({"x": list(range(100)), "y": list(range(100))}) local_ds = DatasetDict({"train": ds, "random": ds2}) ds_name = f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}" # Push to hub two times, but the second time with a larger amount of files. # Verify that the new files contain the correct dataset. with temporary_repo(ds_name) as ds_name: local_ds.push_to_hub(ds_name, token=self._token) with tempfile.TemporaryDirectory() as tmp: # Add a file starting with "data" to ensure it doesn't get deleted. path = Path(tmp) / "datafile.txt" with open(path, "w") as f: f.write("Bogus file") self._api.upload_file( path_or_fileobj=str(path), path_in_repo="datafile.txt", repo_id=ds_name, repo_type="dataset", token=self._token, ) local_ds.push_to_hub(ds_name, token=self._token, max_shard_size=500 << 5) # Ensure that there are two files on the repository that have the correct name files = sorted(self._api.list_repo_files(ds_name, repo_type="dataset", token=self._token)) assert all( fnmatch.fnmatch(file, expected_file) for file, expected_file in zip( files, [ ".gitattributes", "README.md", "data/random-00000-of-00001-*.parquet", "data/train-00000-of-00002-*.parquet", "data/train-00001-of-00002-*.parquet", "datafile.txt", ], ) ) self._api.delete_file("datafile.txt", repo_id=ds_name, repo_type="dataset", token=self._token) hub_ds = load_dataset(ds_name, download_mode="force_redownload") assert local_ds.column_names == hub_ds.column_names assert list(local_ds["train"].features.keys()) == list(hub_ds["train"].features.keys()) assert local_ds["train"].features == hub_ds["train"].features del hub_ds # Push to hub two times, but the second time with fewer files. # Verify that the new files contain the correct dataset and that non-necessary files have been deleted. with temporary_repo(ds_name) as ds_name: local_ds.push_to_hub(ds_name, token=self._token, max_shard_size=500 << 5) with tempfile.TemporaryDirectory() as tmp: # Add a file starting with "data" to ensure it doesn't get deleted. path = Path(tmp) / "datafile.txt" with open(path, "w") as f: f.write("Bogus file") self._api.upload_file( path_or_fileobj=str(path), path_in_repo="datafile.txt", repo_id=ds_name, repo_type="dataset", token=self._token, ) local_ds.push_to_hub(ds_name, token=self._token) # Ensure that there are two files on the repository that have the correct name files = sorted(self._api.list_repo_files(ds_name, repo_type="dataset", token=self._token)) assert all( fnmatch.fnmatch(file, expected_file) for file, expected_file in zip( files, [ ".gitattributes", "README.md", "data/random-00000-of-00001-*.parquet", "data/train-00000-of-00001-*.parquet", "datafile.txt", ], ) ) # Keeping the "datafile.txt" breaks the load_dataset to think it's a text-based dataset self._api.delete_file("datafile.txt", repo_id=ds_name, repo_type="dataset", token=self._token) hub_ds = load_dataset(ds_name, download_mode="force_redownload") assert local_ds.column_names == hub_ds.column_names assert list(local_ds["train"].features.keys()) == list(hub_ds["train"].features.keys()) assert local_ds["train"].features == hub_ds["train"].features def test_push_dataset_to_hub(self, temporary_repo): local_ds = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: local_ds.push_to_hub(ds_name, split="train", token=self._token) local_ds_dict = {"train": local_ds} hub_ds_dict = load_dataset(ds_name, download_mode="force_redownload") assert list(local_ds_dict.keys()) == list(hub_ds_dict.keys()) for ds_split_name in local_ds_dict.keys(): local_ds = local_ds_dict[ds_split_name] hub_ds = hub_ds_dict[ds_split_name] assert local_ds.column_names == hub_ds.column_names assert list(local_ds.features.keys()) == list(hub_ds.features.keys()) assert local_ds.features == hub_ds.features def test_push_dataset_to_hub_custom_features(self, temporary_repo): features = Features({"x": Value("int64"), "y": ClassLabel(names=["neg", "pos"])}) ds = Dataset.from_dict({"x": [1, 2, 3], "y": [0, 0, 1]}, features=features) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: ds.push_to_hub(ds_name, token=self._token) hub_ds = load_dataset(ds_name, split="train", download_mode="force_redownload") assert ds.column_names == hub_ds.column_names assert list(ds.features.keys()) == list(hub_ds.features.keys()) assert ds.features == hub_ds.features assert ds[:] == hub_ds[:] @require_sndfile def test_push_dataset_to_hub_custom_features_audio(self, temporary_repo): audio_path = os.path.join(os.path.dirname(__file__), "features", "data", "test_audio_44100.wav") data = {"x": [audio_path, None], "y": [0, -1]} features = Features({"x": Audio(), "y": Value("int32")}) ds = Dataset.from_dict(data, features=features) for embed_external_files in [True, False]: with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: ds.push_to_hub(ds_name, embed_external_files=embed_external_files, token=self._token) hub_ds = load_dataset(ds_name, split="train", download_mode="force_redownload") assert ds.column_names == hub_ds.column_names assert list(ds.features.keys()) == list(hub_ds.features.keys()) assert ds.features == hub_ds.features np.testing.assert_equal(ds[0]["x"]["array"], hub_ds[0]["x"]["array"]) assert ds[1] == hub_ds[1] # don't test hub_ds[0] since audio decoding might be slightly different hub_ds = hub_ds.cast_column("x", Audio(decode=False)) elem = hub_ds[0]["x"] path, bytes_ = elem["path"], elem["bytes"] assert isinstance(path, str) assert os.path.basename(path) == "test_audio_44100.wav" assert bool(bytes_) == embed_external_files @require_pil def test_push_dataset_to_hub_custom_features_image(self, temporary_repo): image_path = os.path.join(os.path.dirname(__file__), "features", "data", "test_image_rgb.jpg") data = {"x": [image_path, None], "y": [0, -1]} features = Features({"x": Image(), "y": Value("int32")}) ds = Dataset.from_dict(data, features=features) for embed_external_files in [True, False]: with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: ds.push_to_hub(ds_name, embed_external_files=embed_external_files, token=self._token) hub_ds = load_dataset(ds_name, split="train", download_mode="force_redownload") assert ds.column_names == hub_ds.column_names assert list(ds.features.keys()) == list(hub_ds.features.keys()) assert ds.features == hub_ds.features assert ds[:] == hub_ds[:] hub_ds = hub_ds.cast_column("x", Image(decode=False)) elem = hub_ds[0]["x"] path, bytes_ = elem["path"], elem["bytes"] assert isinstance(path, str) assert bool(bytes_) == embed_external_files @require_pil def test_push_dataset_to_hub_custom_features_image_list(self, temporary_repo): image_path = os.path.join(os.path.dirname(__file__), "features", "data", "test_image_rgb.jpg") data = {"x": [[image_path], [image_path, image_path]], "y": [0, -1]} features = Features({"x": [Image()], "y": Value("int32")}) ds = Dataset.from_dict(data, features=features) for embed_external_files in [True, False]: with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: ds.push_to_hub(ds_name, embed_external_files=embed_external_files, token=self._token) hub_ds = load_dataset(ds_name, split="train", download_mode="force_redownload") assert ds.column_names == hub_ds.column_names assert list(ds.features.keys()) == list(hub_ds.features.keys()) assert ds.features == hub_ds.features assert ds[:] == hub_ds[:] hub_ds = hub_ds.cast_column("x", [Image(decode=False)]) elem = hub_ds[0]["x"][0] path, bytes_ = elem["path"], elem["bytes"] assert isinstance(path, str) assert bool(bytes_) == embed_external_files def test_push_dataset_dict_to_hub_custom_features(self, temporary_repo): features = Features({"x": Value("int64"), "y": ClassLabel(names=["neg", "pos"])}) ds = Dataset.from_dict({"x": [1, 2, 3], "y": [0, 0, 1]}, features=features) local_ds = DatasetDict({"test": ds}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: local_ds.push_to_hub(ds_name, token=self._token) hub_ds = load_dataset(ds_name, download_mode="force_redownload") assert local_ds.column_names == hub_ds.column_names assert list(local_ds["test"].features.keys()) == list(hub_ds["test"].features.keys()) assert local_ds["test"].features == hub_ds["test"].features def test_push_dataset_to_hub_custom_splits(self, temporary_repo): ds = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: ds.push_to_hub(ds_name, split="random", token=self._token) hub_ds = load_dataset(ds_name, download_mode="force_redownload") assert ds.column_names == hub_ds["random"].column_names assert list(ds.features.keys()) == list(hub_ds["random"].features.keys()) assert ds.features == hub_ds["random"].features def test_push_dataset_to_hub_skip_identical_files(self, temporary_repo): ds = Dataset.from_dict({"x": list(range(1000)), "y": list(range(1000))}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: with patch("datasets.arrow_dataset.HfApi.upload_file", side_effect=self._api.upload_file) as mock_hf_api: # Initial push ds.push_to_hub(ds_name, token=self._token, max_shard_size="1KB") call_count_old = mock_hf_api.call_count mock_hf_api.reset_mock() # Remove a data file files = self._api.list_repo_files(ds_name, repo_type="dataset", token=self._token) data_files = [f for f in files if f.startswith("data/")] assert len(data_files) > 1 self._api.delete_file(data_files[0], repo_id=ds_name, repo_type="dataset", token=self._token) # "Resume" push - push missing files ds.push_to_hub(ds_name, token=self._token, max_shard_size="1KB") call_count_new = mock_hf_api.call_count assert call_count_old > call_count_new hub_ds = load_dataset(ds_name, split="train", download_mode="force_redownload") assert ds.column_names == hub_ds.column_names assert list(ds.features.keys()) == list(hub_ds.features.keys()) assert ds.features == hub_ds.features def test_push_dataset_to_hub_multiple_splits_one_by_one(self, temporary_repo): ds = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: ds.push_to_hub(ds_name, split="train", token=self._token) ds.push_to_hub(ds_name, split="test", token=self._token) hub_ds = load_dataset(ds_name, download_mode="force_redownload") assert sorted(hub_ds) == ["test", "train"] assert ds.column_names == hub_ds["train"].column_names assert list(ds.features.keys()) == list(hub_ds["train"].features.keys()) assert ds.features == hub_ds["train"].features def test_push_dataset_dict_to_hub_custom_splits(self, temporary_repo): ds = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) local_ds = DatasetDict({"random": ds}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: local_ds.push_to_hub(ds_name, token=self._token) hub_ds = load_dataset(ds_name, download_mode="force_redownload") assert local_ds.column_names == hub_ds.column_names assert list(local_ds["random"].features.keys()) == list(hub_ds["random"].features.keys()) assert local_ds["random"].features == hub_ds["random"].features @unittest.skip("This test cannot pass until iterable datasets have push to hub") def test_push_streaming_dataset_dict_to_hub(self, temporary_repo): ds = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) local_ds = DatasetDict({"train": ds}) with tempfile.TemporaryDirectory() as tmp: local_ds.save_to_disk(tmp) local_ds = load_dataset(tmp, streaming=True) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: local_ds.push_to_hub(ds_name, token=self._token) hub_ds = load_dataset(ds_name, download_mode="force_redownload") assert local_ds.column_names == hub_ds.column_names assert list(local_ds["train"].features.keys()) == list(hub_ds["train"].features.keys()) assert local_ds["train"].features == hub_ds["train"].features def test_push_multiple_dataset_configs_to_hub_load_dataset_builder(self, temporary_repo): ds_default = Dataset.from_dict({"a": [0], "b": [1]}) ds_config1 = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) ds_config2 = Dataset.from_dict({"foo": [1, 2], "bar": [4, 5]}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: ds_default.push_to_hub(ds_name, token=self._token) ds_config1.push_to_hub(ds_name, "config1", token=self._token) ds_config2.push_to_hub(ds_name, "config2", token=self._token) ds_builder_default = load_dataset_builder(ds_name, download_mode="force_redownload") # default config assert len(ds_builder_default.BUILDER_CONFIGS) == 3 assert len(ds_builder_default.config.data_files["train"]) == 1 assert fnmatch.fnmatch( ds_builder_default.config.data_files["train"][0], "*/data/train-*", ) ds_builder_config1 = load_dataset_builder(ds_name, "config1", download_mode="force_redownload") assert len(ds_builder_config1.BUILDER_CONFIGS) == 3 assert len(ds_builder_config1.config.data_files["train"]) == 1 assert fnmatch.fnmatch( ds_builder_config1.config.data_files["train"][0], "*/config1/train-*", ) ds_builder_config2 = load_dataset_builder(ds_name, "config2", download_mode="force_redownload") assert len(ds_builder_config2.BUILDER_CONFIGS) == 3 assert len(ds_builder_config2.config.data_files["train"]) == 1 assert fnmatch.fnmatch( ds_builder_config2.config.data_files["train"][0], "*/config2/train-*", ) with pytest.raises(ValueError): # no config 'config3' load_dataset_builder(ds_name, "config3", download_mode="force_redownload") def test_push_multiple_dataset_configs_to_hub_load_dataset(self, temporary_repo): ds_default = Dataset.from_dict({"a": [0], "b": [1]}) ds_config1 = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) ds_config2 = Dataset.from_dict({"foo": [1, 2], "bar": [4, 5]}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: ds_default.push_to_hub(ds_name, token=self._token) ds_config1.push_to_hub(ds_name, "config1", token=self._token) ds_config2.push_to_hub(ds_name, "config2", token=self._token) files = sorted(self._api.list_repo_files(ds_name, repo_type="dataset")) expected_files = sorted( [ ".gitattributes", "README.md", "config1/train-00000-of-00001-*.parquet", "config2/train-00000-of-00001-*.parquet", "data/train-00000-of-00001-*.parquet", ] ) assert all(fnmatch.fnmatch(file, expected_file) for file, expected_file in zip(files, expected_files)) hub_ds_default = load_dataset(ds_name, download_mode="force_redownload") hub_ds_config1 = load_dataset(ds_name, "config1", download_mode="force_redownload") hub_ds_config2 = load_dataset(ds_name, "config2", download_mode="force_redownload") # only "train" split assert len(hub_ds_default) == len(hub_ds_config1) == len(hub_ds_config2) == 1 assert ds_default.column_names == hub_ds_default["train"].column_names == ["a", "b"] assert ds_config1.column_names == hub_ds_config1["train"].column_names == ["x", "y"] assert ds_config2.column_names == hub_ds_config2["train"].column_names == ["foo", "bar"] assert ds_default.features == hub_ds_default["train"].features assert ds_config1.features == hub_ds_config1["train"].features assert ds_config2.features == hub_ds_config2["train"].features assert ds_default.num_rows == hub_ds_default["train"].num_rows == 1 assert ds_config1.num_rows == hub_ds_config1["train"].num_rows == 3 assert ds_config2.num_rows == hub_ds_config2["train"].num_rows == 2 with pytest.raises(ValueError): # no config 'config3' load_dataset(ds_name, "config3", download_mode="force_redownload") def test_push_multiple_dataset_configs_to_hub_readme_metadata_content(self, temporary_repo): ds_default = Dataset.from_dict({"a": [0], "b": [2]}) ds_config1 = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) ds_config2 = Dataset.from_dict({"foo": [1, 2], "bar": [4, 5]}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: ds_default.push_to_hub(ds_name, token=self._token) ds_config1.push_to_hub(ds_name, "config1", token=self._token) ds_config2.push_to_hub(ds_name, "config2", token=self._token) # check that configs args was correctly pushed to README.md ds_readme_path = cached_path(hf_hub_url(ds_name, "README.md")) dataset_card_data = DatasetCard.load(ds_readme_path).data assert METADATA_CONFIGS_FIELD in dataset_card_data assert isinstance(dataset_card_data[METADATA_CONFIGS_FIELD], list) assert sorted(dataset_card_data[METADATA_CONFIGS_FIELD], key=lambda x: x["config_name"]) == [ { "config_name": "config1", "data_files": [ {"split": "train", "path": "config1/train-*"}, ], }, { "config_name": "config2", "data_files": [ {"split": "train", "path": "config2/train-*"}, ], }, { "config_name": "default", "data_files": [ {"split": "train", "path": "data/train-*"}, ], }, ] def test_push_multiple_dataset_dict_configs_to_hub_load_dataset_builder(self, temporary_repo): ds_default = Dataset.from_dict({"a": [0], "b": [1]}) ds_config1 = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) ds_config2 = Dataset.from_dict({"foo": [1, 2], "bar": [4, 5]}) ds_default = DatasetDict({"random": ds_default}) ds_config1 = DatasetDict({"random": ds_config1}) ds_config2 = DatasetDict({"random": ds_config2}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: ds_default.push_to_hub(ds_name, token=self._token) ds_config1.push_to_hub(ds_name, "config1", token=self._token) ds_config2.push_to_hub(ds_name, "config2", token=self._token) ds_builder_default = load_dataset_builder(ds_name, download_mode="force_redownload") # default config assert len(ds_builder_default.BUILDER_CONFIGS) == 3 assert len(ds_builder_default.config.data_files["random"]) == 1 assert fnmatch.fnmatch( ds_builder_default.config.data_files["random"][0], "*/data/random-*", ) ds_builder_config1 = load_dataset_builder(ds_name, "config1", download_mode="force_redownload") assert len(ds_builder_config1.BUILDER_CONFIGS) == 3 assert len(ds_builder_config1.config.data_files["random"]) == 1 assert fnmatch.fnmatch( ds_builder_config1.config.data_files["random"][0], "*/config1/random-*", ) ds_builder_config2 = load_dataset_builder(ds_name, "config2", download_mode="force_redownload") assert len(ds_builder_config2.BUILDER_CONFIGS) == 3 assert len(ds_builder_config2.config.data_files["random"]) == 1 assert fnmatch.fnmatch( ds_builder_config2.config.data_files["random"][0], "*/config2/random-*", ) with pytest.raises(ValueError): # no config named 'config3' load_dataset_builder(ds_name, "config3", download_mode="force_redownload") def test_push_multiple_dataset_dict_configs_to_hub_load_dataset(self, temporary_repo): ds_default = Dataset.from_dict({"a": [0], "b": [1]}) ds_config1 = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) ds_config2 = Dataset.from_dict({"foo": [1, 2], "bar": [4, 5]}) ds_default = DatasetDict({"train": ds_default, "random": ds_default}) ds_config1 = DatasetDict({"train": ds_config1, "random": ds_config1}) ds_config2 = DatasetDict({"train": ds_config2, "random": ds_config2}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: ds_default.push_to_hub(ds_name, token=self._token) ds_config1.push_to_hub(ds_name, "config1", token=self._token) ds_config2.push_to_hub(ds_name, "config2", token=self._token) files = sorted(self._api.list_repo_files(ds_name, repo_type="dataset")) expected_files = sorted( [ ".gitattributes", "README.md", "config1/random-00000-of-00001-*.parquet", "config1/train-00000-of-00001-*.parquet", "config2/random-00000-of-00001-*.parquet", "config2/train-00000-of-00001-*.parquet", "data/random-00000-of-00001-*.parquet", "data/train-00000-of-00001-*.parquet", ] ) assert all(fnmatch.fnmatch(file, expected_file) for file, expected_file in zip(files, expected_files)) hub_ds_default = load_dataset(ds_name, download_mode="force_redownload") hub_ds_config1 = load_dataset(ds_name, "config1", download_mode="force_redownload") hub_ds_config2 = load_dataset(ds_name, "config2", download_mode="force_redownload") # two splits expected_splits = ["random", "train"] assert len(hub_ds_default) == len(hub_ds_config1) == len(hub_ds_config2) == 2 assert sorted(hub_ds_default) == sorted(hub_ds_config1) == sorted(hub_ds_config2) == expected_splits for split in expected_splits: assert ds_default[split].column_names == hub_ds_default[split].column_names == ["a", "b"] assert ds_config1[split].column_names == hub_ds_config1[split].column_names == ["x", "y"] assert ds_config2[split].column_names == hub_ds_config2[split].column_names == ["foo", "bar"] assert ds_default[split].features == hub_ds_default[split].features assert ds_config1[split].features == hub_ds_config1[split].features assert ds_config2[split].features == hub_ds_config2["train"].features assert ds_default[split].num_rows == hub_ds_default[split].num_rows == 1 assert ds_config1[split].num_rows == hub_ds_config1[split].num_rows == 3 assert ds_config2[split].num_rows == hub_ds_config2[split].num_rows == 2 with pytest.raises(ValueError): # no config 'config3' load_dataset(ds_name, "config3", download_mode="force_redownload") def test_push_multiple_dataset_dict_configs_to_hub_readme_metadata_content(self, temporary_repo): ds_default = Dataset.from_dict({"a": [0], "b": [1]}) ds_config1 = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) ds_config2 = Dataset.from_dict({"foo": [1, 2], "bar": [4, 5]}) ds_default = DatasetDict({"train": ds_default, "random": ds_default}) ds_config1 = DatasetDict({"train": ds_config1, "random": ds_config1}) ds_config2 = DatasetDict({"train": ds_config2, "random": ds_config2}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: ds_default.push_to_hub(ds_name, token=self._token) ds_config1.push_to_hub(ds_name, "config1", token=self._token) ds_config2.push_to_hub(ds_name, "config2", token=self._token) # check that configs args was correctly pushed to README.md ds_readme_path = cached_path(hf_hub_url(ds_name, "README.md")) dataset_card_data = DatasetCard.load(ds_readme_path).data assert METADATA_CONFIGS_FIELD in dataset_card_data assert isinstance(dataset_card_data[METADATA_CONFIGS_FIELD], list) assert sorted(dataset_card_data[METADATA_CONFIGS_FIELD], key=lambda x: x["config_name"]) == [ { "config_name": "config1", "data_files": [ {"split": "train", "path": "config1/train-*"}, {"split": "random", "path": "config1/random-*"}, ], }, { "config_name": "config2", "data_files": [ {"split": "train", "path": "config2/train-*"}, {"split": "random", "path": "config2/random-*"}, ], }, { "config_name": "default", "data_files": [ {"split": "train", "path": "data/train-*"}, {"split": "random", "path": "data/random-*"}, ], }, ] def test_push_dataset_to_hub_with_config_no_metadata_configs(self, temporary_repo): ds = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) ds_another_config = Dataset.from_dict({"foo": [1, 2], "bar": [4, 5]}) parquet_buf = BytesIO() ds.to_parquet(parquet_buf) parquet_content = parquet_buf.getvalue() with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: self._api.create_repo(ds_name, token=self._token, repo_type="dataset") # old push_to_hub was uploading the parquet files only - without metadata configs self._api.upload_file( path_or_fileobj=parquet_content, path_in_repo="data/train-00000-of-00001.parquet", repo_id=ds_name, repo_type="dataset", token=self._token, ) ds_another_config.push_to_hub(ds_name, "another_config", token=self._token) ds_builder = load_dataset_builder(ds_name, download_mode="force_redownload") assert len(ds_builder.config.data_files) == 1 assert len(ds_builder.config.data_files["train"]) == 1 assert fnmatch.fnmatch(ds_builder.config.data_files["train"][0], "*/data/train-00000-of-00001.parquet") ds_another_config_builder = load_dataset_builder( ds_name, "another_config", download_mode="force_redownload" ) assert len(ds_another_config_builder.config.data_files) == 1 assert len(ds_another_config_builder.config.data_files["train"]) == 1 assert fnmatch.fnmatch( ds_another_config_builder.config.data_files["train"][0], "*/another_config/train-00000-of-00001-*.parquet", ) def test_push_dataset_dict_to_hub_with_config_no_metadata_configs(self, temporary_repo): ds = Dataset.from_dict({"x": [1, 2, 3], "y": [4, 5, 6]}) ds_another_config = Dataset.from_dict({"foo": [1, 2], "bar": [4, 5]}) parquet_buf = BytesIO() ds.to_parquet(parquet_buf) parquet_content = parquet_buf.getvalue() local_ds_another_config = DatasetDict({"random": ds_another_config}) with temporary_repo(f"{CI_HUB_USER}/test-{int(time.time() * 10e3)}") as ds_name: self._api.create_repo(ds_name, token=self._token, repo_type="dataset") # old push_to_hub was uploading the parquet files only - without metadata configs self._api.upload_file( path_or_fileobj=parquet_content, path_in_repo="data/random-00000-of-00001.parquet", repo_id=ds_name, repo_type="dataset", token=self._token, ) local_ds_another_config.push_to_hub(ds_name, "another_config", token=self._token) ds_builder = load_dataset_builder(ds_name, download_mode="force_redownload") assert len(ds_builder.config.data_files) == 1 assert len(ds_builder.config.data_files["random"]) == 1 assert fnmatch.fnmatch(ds_builder.config.data_files["random"][0], "*/data/random-00000-of-00001.parquet") ds_another_config_builder = load_dataset_builder( ds_name, "another_config", download_mode="force_redownload" ) assert len(ds_another_config_builder.config.data_files) == 1 assert len(ds_another_config_builder.config.data_files["random"]) == 1 assert fnmatch.fnmatch( ds_another_config_builder.config.data_files["random"][0], "*/another_config/random-00000-of-00001-*.parquet", )
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_version.py
import pytest from datasets.utils.version import Version @pytest.mark.parametrize( "other, expected_equality", [ (Version("1.0.0"), True), ("1.0.0", True), (Version("2.0.0"), False), ("2.0.0", False), ("1", False), ("a", False), (1, False), (None, False), ], ) def test_version_equality_and_hash(other, expected_equality): version = Version("1.0.0") assert (version == other) is expected_equality assert (version != other) is not expected_equality assert (hash(version) == hash(other)) is expected_equality
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/test_warnings.py
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def mock_emitted_deprecation_warnings(monkeypatch): monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings", set()) # Used by list_metrics @pytest.fixture def mock_hfh(monkeypatch): class MetricMock: def __init__(self, metric_id): self.id = metric_id class HfhMock: _metrics = [MetricMock(metric_id) for metric_id in ["accuracy", "mse", "precision", "codeparrot/apps_metric"]] def list_metrics(self): return self._metrics monkeypatch.setattr("datasets.inspect.huggingface_hub", HfhMock()) @pytest.mark.parametrize( "func, args", [(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] ) def test_metric_deprecation_warning(func, args, mock_emitted_deprecation_warnings, mock_hfh, tmp_path): if "tmp_path" in args: args = tuple(arg if arg != "tmp_path" else tmp_path for arg in args) with pytest.warns(FutureWarning, match="https://huggingface.co/docs/evaluate"): func(*args)
0
hf_public_repos/datasets
hf_public_repos/datasets/tests/utils.py
import asyncio import importlib.metadata import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as pa import pytest import requests from packaging import version from datasets import config def parse_flag_from_env(key, default=False): try: value = os.environ[key] except KeyError: # KEY isn't set, default to `default`. _value = default else: # KEY is set, convert it to True or False. try: _value = strtobool(value) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f"If set, {key} must be yes or no.") return _value _run_slow_tests = parse_flag_from_env("RUN_SLOW", default=False) _run_remote_tests = parse_flag_from_env("RUN_REMOTE", default=False) _run_local_tests = parse_flag_from_env("RUN_LOCAL", default=True) _run_packaged_tests = parse_flag_from_env("RUN_PACKAGED", default=True) # Compression require_lz4 = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4") require_py7zr = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="test requires py7zr") require_zstandard = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="test requires zstandard") # Audio require_sndfile = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec("soundfile") is None or version.parse(importlib.metadata.version("soundfile")) < version.parse("0.12.0"), reason="test requires sndfile>=0.12.1: 'pip install \"soundfile>=0.12.1\"'; ", ) # Beam require_beam = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse("0.3.2"), reason="test requires apache-beam and a compatible dill version", ) # Dill-cloudpickle compatibility require_dill_gt_0_3_2 = pytest.mark.skipif( config.DILL_VERSION <= version.parse("0.3.2"), reason="test requires dill>0.3.2 for cloudpickle compatibility", ) # Windows require_not_windows = pytest.mark.skipif( sys.platform == "win32", reason="test should not be run on Windows", ) def require_faiss(test_case): """ Decorator marking a test that requires Faiss. These tests are skipped when Faiss isn't installed. """ try: import faiss # noqa except ImportError: test_case = unittest.skip("test requires faiss")(test_case) return test_case def require_regex(test_case): """ Decorator marking a test that requires regex. These tests are skipped when Regex isn't installed. """ try: import regex # noqa except ImportError: test_case = unittest.skip("test requires regex")(test_case) return test_case def require_elasticsearch(test_case): """ Decorator marking a test that requires ElasticSearch. These tests are skipped when ElasticSearch isn't installed. """ try: import elasticsearch # noqa except ImportError: test_case = unittest.skip("test requires elasticsearch")(test_case) return test_case def require_sqlalchemy(test_case): """ Decorator marking a test that requires SQLAlchemy. These tests are skipped when SQLAlchemy isn't installed. """ try: import sqlalchemy # noqa except ImportError: test_case = unittest.skip("test requires sqlalchemy")(test_case) return test_case def require_torch(test_case): """ Decorator marking a test that requires PyTorch. These tests are skipped when PyTorch isn't installed. """ if not config.TORCH_AVAILABLE: test_case = unittest.skip("test requires PyTorch")(test_case) return test_case def require_tf(test_case): """ Decorator marking a test that requires TensorFlow. These tests are skipped when TensorFlow isn't installed. """ if not config.TF_AVAILABLE: test_case = unittest.skip("test requires TensorFlow")(test_case) return test_case def require_jax(test_case): """ Decorator marking a test that requires JAX. These tests are skipped when JAX isn't installed. """ if not config.JAX_AVAILABLE: test_case = unittest.skip("test requires JAX")(test_case) return test_case def require_pil(test_case): """ Decorator marking a test that requires Pillow. These tests are skipped when Pillow isn't installed. """ if not config.PIL_AVAILABLE: test_case = unittest.skip("test requires Pillow")(test_case) return test_case def require_transformers(test_case): """ Decorator marking a test that requires transformers. These tests are skipped when transformers isn't installed. """ try: import transformers # noqa F401 except ImportError: return unittest.skip("test requires transformers")(test_case) else: return test_case def require_tiktoken(test_case): """ Decorator marking a test that requires tiktoken. These tests are skipped when transformers isn't installed. """ try: import tiktoken # noqa F401 except ImportError: return unittest.skip("test requires tiktoken")(test_case) else: return test_case def require_spacy(test_case): """ Decorator marking a test that requires spacy. These tests are skipped when they aren't installed. """ try: import spacy # noqa F401 except ImportError: return unittest.skip("test requires spacy")(test_case) else: return test_case def require_spacy_model(model): """ Decorator marking a test that requires a spacy model. These tests are skipped when they aren't installed. """ def _require_spacy_model(test_case): try: import spacy # noqa F401 spacy.load(model) except ImportError: return unittest.skip("test requires spacy")(test_case) except OSError: return unittest.skip("test requires spacy model '{}'".format(model))(test_case) else: return test_case return _require_spacy_model def require_pyspark(test_case): """ Decorator marking a test that requires pyspark. These tests are skipped when pyspark isn't installed. """ try: import pyspark # noqa F401 except ImportError: return unittest.skip("test requires pyspark")(test_case) else: return test_case def require_joblibspark(test_case): """ Decorator marking a test that requires joblibspark. These tests are skipped when pyspark isn't installed. """ try: import joblibspark # noqa F401 except ImportError: return unittest.skip("test requires joblibspark")(test_case) else: return test_case def slow(test_case): """ Decorator marking a test as slow. Slow tests are skipped by default. Set the RUN_SLOW environment variable to a truthy value to run them. """ if not _run_slow_tests or _run_slow_tests == 0: test_case = unittest.skip("test is slow")(test_case) return test_case def local(test_case): """ Decorator marking a test as local Local tests are run by default. Set the RUN_LOCAL environment variable to a falsy value to not run them. """ if not _run_local_tests or _run_local_tests == 0: test_case = unittest.skip("test is local")(test_case) return test_case def packaged(test_case): """ Decorator marking a test as packaged Packaged tests are run by default. Set the RUN_PACKAGED environment variable to a falsy value to not run them. """ if not _run_packaged_tests or _run_packaged_tests == 0: test_case = unittest.skip("test is packaged")(test_case) return test_case def remote(test_case): """ Decorator marking a test as one that relies on GitHub or the Hugging Face Hub. Remote tests are skipped by default. Set the RUN_REMOTE environment variable to a falsy value to not run them. """ if not _run_remote_tests or _run_remote_tests == 0: test_case = unittest.skip("test requires remote")(test_case) return test_case def for_all_test_methods(*decorators): def decorate(cls): for name, fn in cls.__dict__.items(): if callable(fn) and name.startswith("test"): for decorator in decorators: fn = decorator(fn) setattr(cls, name, fn) return cls return decorate class RequestWouldHangIndefinitelyError(Exception): pass class OfflineSimulationMode(Enum): CONNECTION_FAILS = 0 CONNECTION_TIMES_OUT = 1 HF_DATASETS_OFFLINE_SET_TO_1 = 2 @contextmanager def offline(mode=OfflineSimulationMode.CONNECTION_FAILS, timeout=1e-16): """ Simulate offline mode. There are three offline simulatiom modes: CONNECTION_FAILS (default mode): a ConnectionError is raised for each network call. Connection errors are created by mocking socket.socket CONNECTION_TIMES_OUT: the connection hangs until it times out. The default timeout value is low (1e-16) to speed up the tests. Timeout errors are created by mocking requests.request HF_DATASETS_OFFLINE_SET_TO_1: the HF_DATASETS_OFFLINE environment variable is set to 1. This makes the http/ftp calls of the library instantly fail and raise an OfflineModeEmabled error. """ online_request = requests.Session().request def timeout_request(session, method, url, **kwargs): # Change the url to an invalid url so that the connection hangs invalid_url = "https://10.255.255.1" if kwargs.get("timeout") is None: raise RequestWouldHangIndefinitelyError( f"Tried a call to {url} in offline mode with no timeout set. Please set a timeout." ) kwargs["timeout"] = timeout try: return online_request(method, invalid_url, **kwargs) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier e.request.url = url max_retry_error = e.args[0] max_retry_error.args = (max_retry_error.args[0].replace("10.255.255.1", f"OfflineMock[{url}]"),) e.args = (max_retry_error,) raise def raise_connection_error(session, prepared_request, **kwargs): raise requests.ConnectionError("Offline mode is enabled.", request=prepared_request) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch("requests.Session.send", raise_connection_error): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch("requests.Session.request", timeout_request): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch("datasets.config.HF_DATASETS_OFFLINE", True): yield else: raise ValueError("Please use a value from the OfflineSimulationMode enum.") @contextmanager def set_current_working_directory_to_temp_dir(*args, **kwargs): original_working_dir = str(Path().resolve()) with tempfile.TemporaryDirectory(*args, **kwargs) as tmp_dir: try: os.chdir(tmp_dir) yield finally: os.chdir(original_working_dir) @contextmanager def assert_arrow_memory_increases(): import gc gc.collect() previous_allocated_memory = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def assert_arrow_memory_doesnt_increase(): import gc gc.collect() previous_allocated_memory = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def is_rng_equal(rng1, rng2): return deepcopy(rng1).integers(0, 100, 10).tolist() == deepcopy(rng2).integers(0, 100, 10).tolist() def xfail_if_500_502_http_error(func): import decorator from requests.exceptions import HTTPError def _wrapper(func, *args, **kwargs): try: return func(*args, **kwargs) except HTTPError as err: if str(err).startswith("500") or str(err).startswith("502"): pytest.xfail(str(err)) raise err return decorator.decorator(_wrapper, func) # --- distributed testing functions --- # # copied from transformers # originally adapted from https://stackoverflow.com/a/59041913/9201239 class _RunOutput: def __init__(self, returncode, stdout, stderr): self.returncode = returncode self.stdout = stdout self.stderr = stderr async def _read_stream(stream, callback): while True: line = await stream.readline() if line: callback(line) else: break async def _stream_subprocess(cmd, env=None, stdin=None, timeout=None, quiet=False, echo=False) -> _RunOutput: if echo: print("\nRunning: ", " ".join(cmd)) p = await asyncio.create_subprocess_exec( cmd[0], *cmd[1:], stdin=stdin, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env, ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) out = [] err = [] def tee(line, sink, pipe, label=""): line = line.decode("utf-8").rstrip() sink.append(line) if not quiet: print(label, line, file=pipe) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout, lambda line: tee(line, out, sys.stdout, label="stdout:")), _read_stream(p.stderr, lambda line: tee(line, err, sys.stderr, label="stderr:")), ], timeout=timeout, ) return _RunOutput(await p.wait(), out, err) def execute_subprocess_async(cmd, env=None, stdin=None, timeout=180, quiet=False, echo=True) -> _RunOutput: loop = asyncio.get_event_loop() result = loop.run_until_complete( _stream_subprocess(cmd, env=env, stdin=stdin, timeout=timeout, quiet=quiet, echo=echo) ) cmd_str = " ".join(cmd) if result.returncode > 0: stderr = "\n".join(result.stderr) raise RuntimeError( f"'{cmd_str}' failed with returncode {result.returncode}\n\n" f"The combined stderr from workers follows:\n{stderr}" ) # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(f"'{cmd_str}' produced no output.") return result def pytest_xdist_worker_id(): """ Returns an int value of worker's numerical id under `pytest-xdist`'s concurrent workers `pytest -n N` regime, or 0 if `-n 1` or `pytest-xdist` isn't being used. """ worker = os.environ.get("PYTEST_XDIST_WORKER", "gw0") worker = re.sub(r"^gw", "", worker, 0, re.M) return int(worker) def get_torch_dist_unique_port(): """ Returns a port number that can be fed to `torchrun`'s `--master_port` argument. Under `pytest-xdist` it adds a delta number based on a worker id so that concurrent tests don't try to use the same port at once. """ port = 29500 uniq_delta = pytest_xdist_worker_id() return port + uniq_delta
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/commands/conftest.py
import pytest DATASET_LOADING_SCRIPT_NAME = "__dummy_dataset1__" DATASET_LOADING_SCRIPT_CODE = """ import json import os import datasets REPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/" URLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"} class __DummyDataset1__(datasets.GeneratorBasedBuilder): def _info(self): features = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string")), "ner_tags": datasets.Sequence( datasets.features.ClassLabel( names=[ "O", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC", ] ) ), "langs": datasets.Sequence(datasets.Value("string")), "spans": datasets.Sequence(datasets.Value("string")), } ) return datasets.DatasetInfo(features=features) def _split_generators(self, dl_manager): dl_path = dl_manager.download(URLS) return [ datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}), datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}), ] def _generate_examples(self, filepath): with open(filepath, "r", encoding="utf-8") as f: for i, line in enumerate(f): yield i, json.loads(line) """ @pytest.fixture def dataset_loading_script_name(): return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def dataset_loading_script_code(): return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def dataset_loading_script_dir(dataset_loading_script_name, dataset_loading_script_code, tmp_path): script_name = dataset_loading_script_name script_dir = tmp_path / "datasets" / script_name script_dir.mkdir(parents=True) script_path = script_dir / f"{script_name}.py" with open(script_path, "w") as f: f.write(dataset_loading_script_code) return str(script_dir)
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/commands/test_test.py
import os from collections import namedtuple import pytest from datasets import ClassLabel, Features, Sequence, Value from datasets.commands.test import TestCommand from datasets.info import DatasetInfo, DatasetInfosDict _TestCommandArgs = namedtuple( "_TestCommandArgs", [ "dataset", "name", "cache_dir", "data_dir", "all_configs", "save_infos", "ignore_verifications", "force_redownload", "clear_cache", ], defaults=[None, None, None, False, False, False, False, False], ) def is_1percent_close(source, target): return (abs(source - target) / target) < 0.01 @pytest.mark.integration def test_test_command(dataset_loading_script_dir): args = _TestCommandArgs(dataset=dataset_loading_script_dir, all_configs=True, save_infos=True) test_command = TestCommand(*args) test_command.run() dataset_readme_path = os.path.join(dataset_loading_script_dir, "README.md") assert os.path.exists(dataset_readme_path) dataset_infos = DatasetInfosDict.from_directory(dataset_loading_script_dir) expected_dataset_infos = DatasetInfosDict( { "default": DatasetInfo( features=Features( { "tokens": Sequence(Value("string")), "ner_tags": Sequence( ClassLabel(names=["O", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]) ), "langs": Sequence(Value("string")), "spans": Sequence(Value("string")), } ), splits=[ { "name": "train", "num_bytes": 2351563, "num_examples": 10000, }, { "name": "validation", "num_bytes": 238418, "num_examples": 1000, }, ], download_size=3940680, dataset_size=2589981, ) } ) assert dataset_infos.keys() == expected_dataset_infos.keys() for key in DatasetInfo._INCLUDED_INFO_IN_YAML: result, expected = getattr(dataset_infos["default"], key), getattr(expected_dataset_infos["default"], key) if key == "num_bytes": assert is_1percent_close(result, expected) elif key == "splits": assert list(result) == list(expected) for split in result: assert result[split].name == expected[split].name assert result[split].num_examples == expected[split].num_examples assert is_1percent_close(result[split].num_bytes, expected[split].num_bytes) else: result == expected
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/distributed_scripts/run_torch_distributed.py
import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node NUM_SHARDS = 4 NUM_ITEMS_PER_SHARD = 3 class FailedTestError(RuntimeError): pass def gen(shards: List[str]): for shard in shards: for i in range(NUM_ITEMS_PER_SHARD): yield {"i": i, "shard": shard} def main(): rank = int(os.environ["RANK"]) world_size = int(os.environ["WORLD_SIZE"]) parser = ArgumentParser() parser.add_argument("--streaming", type=bool) parser.add_argument("--local_rank", type=int) parser.add_argument("--num_workers", type=int, default=0) args = parser.parse_args() streaming = args.streaming num_workers = args.num_workers gen_kwargs = {"shards": [f"shard_{shard_idx}" for shard_idx in range(NUM_SHARDS)]} ds = IterableDataset.from_generator(gen, gen_kwargs=gen_kwargs) if not streaming: ds = Dataset.from_list(list(ds)) ds = split_dataset_by_node(ds, rank=rank, world_size=world_size) dataloader = torch.utils.data.DataLoader(ds, num_workers=num_workers) full_size = NUM_SHARDS * NUM_ITEMS_PER_SHARD expected_local_size = full_size // world_size expected_local_size += int(rank < (full_size % world_size)) local_size = sum(1 for _ in dataloader) if local_size != expected_local_size: raise FailedTestError(f"local_size {local_size} != expected_local_size {expected_local_size}") if __name__ == "__main__": main()
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/features/test_array_xd.py
import os import random import tempfile import unittest import numpy as np import pandas as pd import pyarrow as pa import pytest from absl.testing import parameterized import datasets from datasets.arrow_writer import ArrowWriter from datasets.features import Array2D, Array3D, Array4D, Array5D, Value from datasets.features.features import Array3DExtensionType, PandasArrayExtensionDtype, _ArrayXD from datasets.formatting.formatting import NumpyArrowExtractor, SimpleArrowExtractor SHAPE_TEST_1 = (30, 487) SHAPE_TEST_2 = (36, 1024) SHAPE_TEST_3 = (None, 100) SPEED_TEST_SHAPE = (100, 100) SPEED_TEST_N_EXAMPLES = 100 DEFAULT_FEATURES = datasets.Features( { "text": Array2D(SHAPE_TEST_1, dtype="float32"), "image": Array2D(SHAPE_TEST_2, dtype="float32"), "dynamic": Array2D(SHAPE_TEST_3, dtype="float32"), } ) def generate_examples(features: dict, num_examples=100, seq_shapes=None): dummy_data = [] seq_shapes = seq_shapes or {} for i in range(num_examples): example = {} for col_id, (k, v) in enumerate(features.items()): if isinstance(v, _ArrayXD): if k == "dynamic": first_dim = random.randint(1, 3) data = np.random.rand(first_dim, *v.shape[1:]).astype(v.dtype) else: data = np.random.rand(*v.shape).astype(v.dtype) elif isinstance(v, datasets.Value): data = "foo" elif isinstance(v, datasets.Sequence): while isinstance(v, datasets.Sequence): v = v.feature shape = seq_shapes[k] data = np.random.rand(*shape).astype(v.dtype) example[k] = data dummy_data.append((i, example)) return dummy_data class ExtensionTypeCompatibilityTest(unittest.TestCase): def test_array2d_nonspecific_shape(self): with tempfile.TemporaryDirectory() as tmp_dir: my_features = DEFAULT_FEATURES.copy() with ArrowWriter(features=my_features, path=os.path.join(tmp_dir, "beta.arrow")) as writer: for key, record in generate_examples( features=my_features, num_examples=1, ): example = my_features.encode_example(record) writer.write(example) num_examples, num_bytes = writer.finalize() dataset = datasets.Dataset.from_file(os.path.join(tmp_dir, "beta.arrow")) dataset.set_format("numpy") row = dataset[0] first_shape = row["image"].shape second_shape = row["text"].shape self.assertTrue(first_shape is not None and second_shape is not None, "need atleast 2 different shapes") self.assertEqual(len(first_shape), len(second_shape), "both shapes are supposed to be equal length") self.assertNotEqual(first_shape, second_shape, "shapes must not be the same") del dataset def test_multiple_extensions_same_row(self): with tempfile.TemporaryDirectory() as tmp_dir: my_features = DEFAULT_FEATURES.copy() with ArrowWriter(features=my_features, path=os.path.join(tmp_dir, "beta.arrow")) as writer: for key, record in generate_examples(features=my_features, num_examples=1): example = my_features.encode_example(record) writer.write(example) num_examples, num_bytes = writer.finalize() dataset = datasets.Dataset.from_file(os.path.join(tmp_dir, "beta.arrow")) dataset.set_format("numpy") row = dataset[0] first_len = len(row["image"].shape) second_len = len(row["text"].shape) third_len = len(row["dynamic"].shape) self.assertEqual(first_len, 2, "use a sequence type if dim is < 2") self.assertEqual(second_len, 2, "use a sequence type if dim is < 2") self.assertEqual(third_len, 2, "use a sequence type if dim is < 2") del dataset def test_compatability_with_string_values(self): with tempfile.TemporaryDirectory() as tmp_dir: my_features = DEFAULT_FEATURES.copy() my_features["image_id"] = datasets.Value("string") with ArrowWriter(features=my_features, path=os.path.join(tmp_dir, "beta.arrow")) as writer: for key, record in generate_examples(features=my_features, num_examples=1): example = my_features.encode_example(record) writer.write(example) num_examples, num_bytes = writer.finalize() dataset = datasets.Dataset.from_file(os.path.join(tmp_dir, "beta.arrow")) self.assertIsInstance(dataset[0]["image_id"], str, "image id must be of type string") del dataset def test_extension_indexing(self): with tempfile.TemporaryDirectory() as tmp_dir: my_features = DEFAULT_FEATURES.copy() my_features["explicit_ext"] = Array2D((3, 3), dtype="float32") with ArrowWriter(features=my_features, path=os.path.join(tmp_dir, "beta.arrow")) as writer: for key, record in generate_examples(features=my_features, num_examples=1): example = my_features.encode_example(record) writer.write(example) num_examples, num_bytes = writer.finalize() dataset = datasets.Dataset.from_file(os.path.join(tmp_dir, "beta.arrow")) dataset.set_format("numpy") data = dataset[0]["explicit_ext"] self.assertIsInstance(data, np.ndarray, "indexed extension must return numpy.ndarray") del dataset def get_array_feature_types(): shape_1 = [3] * 5 shape_2 = [3, 4, 5, 6, 7] return [ { "testcase_name": f"{d}d", "array_feature": array_feature, "shape_1": tuple(shape_1[:d]), "shape_2": tuple(shape_2[:d]), } for d, array_feature in zip(range(2, 6), [Array2D, Array3D, Array4D, Array5D]) ] @parameterized.named_parameters(get_array_feature_types()) class ArrayXDTest(unittest.TestCase): def get_features(self, array_feature, shape_1, shape_2): return datasets.Features( { "image": array_feature(shape_1, dtype="float32"), "source": Value("string"), "matrix": array_feature(shape_2, dtype="float32"), } ) def get_dict_example_0(self, shape_1, shape_2): return { "image": np.random.rand(*shape_1).astype("float32"), "source": "foo", "matrix": np.random.rand(*shape_2).astype("float32"), } def get_dict_example_1(self, shape_1, shape_2): return { "image": np.random.rand(*shape_1).astype("float32"), "matrix": np.random.rand(*shape_2).astype("float32"), "source": "bar", } def get_dict_examples(self, shape_1, shape_2): return { "image": np.random.rand(2, *shape_1).astype("float32").tolist(), "source": ["foo", "bar"], "matrix": np.random.rand(2, *shape_2).astype("float32").tolist(), } def _check_getitem_output_type(self, dataset, shape_1, shape_2, first_matrix): matrix_column = dataset["matrix"] self.assertIsInstance(matrix_column, list) self.assertIsInstance(matrix_column[0], list) self.assertIsInstance(matrix_column[0][0], list) self.assertTupleEqual(np.array(matrix_column).shape, (2, *shape_2)) matrix_field_of_first_example = dataset[0]["matrix"] self.assertIsInstance(matrix_field_of_first_example, list) self.assertIsInstance(matrix_field_of_first_example, list) self.assertEqual(np.array(matrix_field_of_first_example).shape, shape_2) np.testing.assert_array_equal(np.array(matrix_field_of_first_example), np.array(first_matrix)) matrix_field_of_first_two_examples = dataset[:2]["matrix"] self.assertIsInstance(matrix_field_of_first_two_examples, list) self.assertIsInstance(matrix_field_of_first_two_examples[0], list) self.assertIsInstance(matrix_field_of_first_two_examples[0][0], list) self.assertTupleEqual(np.array(matrix_field_of_first_two_examples).shape, (2, *shape_2)) with dataset.formatted_as("numpy"): self.assertTupleEqual(dataset["matrix"].shape, (2, *shape_2)) self.assertEqual(dataset[0]["matrix"].shape, shape_2) self.assertTupleEqual(dataset[:2]["matrix"].shape, (2, *shape_2)) with dataset.formatted_as("pandas"): self.assertIsInstance(dataset["matrix"], pd.Series) self.assertIsInstance(dataset[0]["matrix"], pd.Series) self.assertIsInstance(dataset[:2]["matrix"], pd.Series) self.assertTupleEqual(dataset["matrix"].to_numpy().shape, (2, *shape_2)) self.assertTupleEqual(dataset[0]["matrix"].to_numpy().shape, (1, *shape_2)) self.assertTupleEqual(dataset[:2]["matrix"].to_numpy().shape, (2, *shape_2)) def test_write(self, array_feature, shape_1, shape_2): with tempfile.TemporaryDirectory() as tmp_dir: my_features = self.get_features(array_feature, shape_1, shape_2) my_examples = [ (0, self.get_dict_example_0(shape_1, shape_2)), (1, self.get_dict_example_1(shape_1, shape_2)), ] with ArrowWriter(features=my_features, path=os.path.join(tmp_dir, "beta.arrow")) as writer: for key, record in my_examples: example = my_features.encode_example(record) writer.write(example) num_examples, num_bytes = writer.finalize() dataset = datasets.Dataset.from_file(os.path.join(tmp_dir, "beta.arrow")) self._check_getitem_output_type(dataset, shape_1, shape_2, my_examples[0][1]["matrix"]) del dataset def test_write_batch(self, array_feature, shape_1, shape_2): with tempfile.TemporaryDirectory() as tmp_dir: my_features = self.get_features(array_feature, shape_1, shape_2) dict_examples = self.get_dict_examples(shape_1, shape_2) dict_examples = my_features.encode_batch(dict_examples) with ArrowWriter(features=my_features, path=os.path.join(tmp_dir, "beta.arrow")) as writer: writer.write_batch(dict_examples) num_examples, num_bytes = writer.finalize() dataset = datasets.Dataset.from_file(os.path.join(tmp_dir, "beta.arrow")) self._check_getitem_output_type(dataset, shape_1, shape_2, dict_examples["matrix"][0]) del dataset def test_from_dict(self, array_feature, shape_1, shape_2): dict_examples = self.get_dict_examples(shape_1, shape_2) dataset = datasets.Dataset.from_dict( dict_examples, features=self.get_features(array_feature, shape_1, shape_2) ) self._check_getitem_output_type(dataset, shape_1, shape_2, dict_examples["matrix"][0]) del dataset class ArrayXDDynamicTest(unittest.TestCase): def get_one_col_dataset(self, first_dim_list, fixed_shape): features = datasets.Features({"image": Array3D(shape=(None, *fixed_shape), dtype="float32")}) dict_values = {"image": [np.random.rand(fdim, *fixed_shape).astype("float32") for fdim in first_dim_list]} dataset = datasets.Dataset.from_dict(dict_values, features=features) return dataset def get_two_col_datasset(self, first_dim_list, fixed_shape): features = datasets.Features( {"image": Array3D(shape=(None, *fixed_shape), dtype="float32"), "text": Value("string")} ) dict_values = { "image": [np.random.rand(fdim, *fixed_shape).astype("float32") for fdim in first_dim_list], "text": ["text" for _ in first_dim_list], } dataset = datasets.Dataset.from_dict(dict_values, features=features) return dataset def test_to_pylist(self): fixed_shape = (2, 2) first_dim_list = [1, 3, 10] dataset = self.get_one_col_dataset(first_dim_list, fixed_shape) arr_xd = SimpleArrowExtractor().extract_column(dataset._data) self.assertIsInstance(arr_xd.type, Array3DExtensionType) pylist = arr_xd.to_pylist() for first_dim, single_arr in zip(first_dim_list, pylist): self.assertIsInstance(single_arr, list) self.assertTupleEqual(np.array(single_arr).shape, (first_dim, *fixed_shape)) def test_to_numpy(self): fixed_shape = (2, 2) # ragged first_dim_list = [1, 3, 10] dataset = self.get_one_col_dataset(first_dim_list, fixed_shape) arr_xd = SimpleArrowExtractor().extract_column(dataset._data) self.assertIsInstance(arr_xd.type, Array3DExtensionType) # replace with arr_xd = arr_xd.combine_chunks() when 12.0.0 will be the minimal required PyArrow version arr_xd = arr_xd.type.wrap_array(pa.concat_arrays([chunk.storage for chunk in arr_xd.chunks])) numpy_arr = arr_xd.to_numpy() self.assertIsInstance(numpy_arr, np.ndarray) self.assertEqual(numpy_arr.dtype, object) for first_dim, single_arr in zip(first_dim_list, numpy_arr): self.assertIsInstance(single_arr, np.ndarray) self.assertTupleEqual(single_arr.shape, (first_dim, *fixed_shape)) # non-ragged first_dim_list = [4, 4, 4] dataset = self.get_one_col_dataset(first_dim_list, fixed_shape) arr_xd = SimpleArrowExtractor().extract_column(dataset._data) self.assertIsInstance(arr_xd.type, Array3DExtensionType) # replace with arr_xd = arr_xd.combine_chunks() when 12.0.0 will be the minimal required PyArrow version arr_xd = arr_xd.type.wrap_array(pa.concat_arrays([chunk.storage for chunk in arr_xd.chunks])) numpy_arr = arr_xd.to_numpy() self.assertIsInstance(numpy_arr, np.ndarray) self.assertNotEqual(numpy_arr.dtype, object) for first_dim, single_arr in zip(first_dim_list, numpy_arr): self.assertIsInstance(single_arr, np.ndarray) self.assertTupleEqual(single_arr.shape, (first_dim, *fixed_shape)) def test_iter_dataset(self): fixed_shape = (2, 2) first_dim_list = [1, 3, 10] dataset = self.get_one_col_dataset(first_dim_list, fixed_shape) for first_dim, ds_row in zip(first_dim_list, dataset): single_arr = ds_row["image"] self.assertIsInstance(single_arr, list) self.assertTupleEqual(np.array(single_arr).shape, (first_dim, *fixed_shape)) def test_to_pandas(self): fixed_shape = (2, 2) # ragged first_dim_list = [1, 3, 10] dataset = self.get_one_col_dataset(first_dim_list, fixed_shape) df = dataset.to_pandas() self.assertEqual(type(df.image.dtype), PandasArrayExtensionDtype) numpy_arr = df.image.to_numpy() self.assertIsInstance(numpy_arr, np.ndarray) self.assertEqual(numpy_arr.dtype, object) for first_dim, single_arr in zip(first_dim_list, numpy_arr): self.assertIsInstance(single_arr, np.ndarray) self.assertTupleEqual(single_arr.shape, (first_dim, *fixed_shape)) # non-ragged first_dim_list = [4, 4, 4] dataset = self.get_one_col_dataset(first_dim_list, fixed_shape) df = dataset.to_pandas() self.assertEqual(type(df.image.dtype), PandasArrayExtensionDtype) numpy_arr = df.image.to_numpy() self.assertIsInstance(numpy_arr, np.ndarray) self.assertNotEqual(numpy_arr.dtype, object) for first_dim, single_arr in zip(first_dim_list, numpy_arr): self.assertIsInstance(single_arr, np.ndarray) self.assertTupleEqual(single_arr.shape, (first_dim, *fixed_shape)) def test_map_dataset(self): fixed_shape = (2, 2) first_dim_list = [1, 3, 10] dataset = self.get_one_col_dataset(first_dim_list, fixed_shape) dataset = dataset.map(lambda a: {"image": np.concatenate([a] * 2)}, input_columns="image") # check also if above function resulted with 2x bigger first dim for first_dim, ds_row in zip(first_dim_list, dataset): single_arr = ds_row["image"] self.assertIsInstance(single_arr, list) self.assertTupleEqual(np.array(single_arr).shape, (first_dim * 2, *fixed_shape)) @pytest.mark.parametrize("dtype, dummy_value", [("int32", 1), ("bool", True), ("float64", 1)]) def test_table_to_pandas(dtype, dummy_value): features = datasets.Features({"foo": datasets.Array2D(dtype=dtype, shape=(2, 2))}) dataset = datasets.Dataset.from_dict({"foo": [[[dummy_value] * 2] * 2]}, features=features) df = dataset._data.to_pandas() assert type(df.foo.dtype) == PandasArrayExtensionDtype arr = df.foo.to_numpy() np.testing.assert_equal(arr, np.array([[[dummy_value] * 2] * 2], dtype=np.dtype(dtype))) @pytest.mark.parametrize("dtype, dummy_value", [("int32", 1), ("bool", True), ("float64", 1)]) def test_array_xd_numpy_arrow_extractor(dtype, dummy_value): features = datasets.Features({"foo": datasets.Array2D(dtype=dtype, shape=(2, 2))}) dataset = datasets.Dataset.from_dict({"foo": [[[dummy_value] * 2] * 2]}, features=features) arr = NumpyArrowExtractor().extract_column(dataset._data) assert isinstance(arr, np.ndarray) np.testing.assert_equal(arr, np.array([[[dummy_value] * 2] * 2], dtype=np.dtype(dtype))) def test_array_xd_with_none(): # Fixed shape features = datasets.Features({"foo": datasets.Array2D(dtype="int32", shape=(2, 2))}) dummy_array = np.array([[1, 2], [3, 4]], dtype="int32") dataset = datasets.Dataset.from_dict({"foo": [dummy_array, None, dummy_array, None]}, features=features) arr = NumpyArrowExtractor().extract_column(dataset._data) assert isinstance(arr, np.ndarray) and arr.dtype == np.float64 and arr.shape == (4, 2, 2) assert np.allclose(arr[0], dummy_array) and np.allclose(arr[2], dummy_array) assert np.all(np.isnan(arr[1])) and np.all(np.isnan(arr[3])) # broadcasted np.nan - use np.all # Dynamic shape features = datasets.Features({"foo": datasets.Array2D(dtype="int32", shape=(None, 2))}) dummy_array = np.array([[1, 2], [3, 4]], dtype="int32") dataset = datasets.Dataset.from_dict({"foo": [dummy_array, None, dummy_array, None]}, features=features) arr = NumpyArrowExtractor().extract_column(dataset._data) assert isinstance(arr, np.ndarray) and arr.dtype == object and arr.shape == (4,) np.testing.assert_equal(arr[0], dummy_array) np.testing.assert_equal(arr[2], dummy_array) assert np.isnan(arr[1]) and np.isnan(arr[3]) # a single np.nan value - np.all not needed @pytest.mark.parametrize("seq_type", ["no_sequence", "sequence", "sequence_of_sequence"]) @pytest.mark.parametrize( "dtype", [ "bool", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", "float16", "float32", "float64", ], ) @pytest.mark.parametrize("shape, feature_class", [((2, 3), datasets.Array2D), ((2, 3, 4), datasets.Array3D)]) def test_array_xd_with_np(seq_type, dtype, shape, feature_class): feature = feature_class(dtype=dtype, shape=shape) data = np.zeros(shape, dtype=dtype) expected = data.tolist() if seq_type == "sequence": feature = datasets.Sequence(feature) data = [data] expected = [expected] elif seq_type == "sequence_of_sequence": feature = datasets.Sequence(datasets.Sequence(feature)) data = [[data]] expected = [[expected]] ds = datasets.Dataset.from_dict({"col": [data]}, features=datasets.Features({"col": feature})) assert ds[0]["col"] == expected @pytest.mark.parametrize("with_none", [False, True]) def test_dataset_map(with_none): ds = datasets.Dataset.from_dict({"path": ["path1", "path2"]}) def process_data(batch): batch = { "image": [ np.array( [ [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 20, 30], [40, 50, 60], [70, 80, 90]], [[100, 200, 300], [400, 500, 600], [700, 800, 900]], ] ) for _ in batch["path"] ] } if with_none: batch["image"][0] = None return batch features = datasets.Features({"image": Array3D(dtype="int32", shape=(3, 3, 3))}) processed_ds = ds.map(process_data, batched=True, remove_columns=ds.column_names, features=features) assert processed_ds.shape == (2, 1) with processed_ds.with_format("numpy") as pds: for i, example in enumerate(pds): assert "image" in example assert isinstance(example["image"], np.ndarray) assert example["image"].shape == (3, 3, 3) if with_none and i == 0: assert np.all(np.isnan(example["image"]))
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/features/test_audio.py
import os import tarfile import pyarrow as pa import pytest from datasets import Dataset, concatenate_datasets, load_dataset from datasets.features import Audio, Features, Sequence, Value from ..utils import ( require_sndfile, ) @pytest.fixture() def tar_wav_path(shared_datadir, tmp_path_factory): audio_path = str(shared_datadir / "test_audio_44100.wav") path = tmp_path_factory.mktemp("data") / "audio_data.wav.tar" with tarfile.TarFile(path, "w") as f: f.add(audio_path, arcname=os.path.basename(audio_path)) return path @pytest.fixture() def tar_mp3_path(shared_datadir, tmp_path_factory): audio_path = str(shared_datadir / "test_audio_44100.mp3") path = tmp_path_factory.mktemp("data") / "audio_data.mp3.tar" with tarfile.TarFile(path, "w") as f: f.add(audio_path, arcname=os.path.basename(audio_path)) return path def iter_archive(archive_path): with tarfile.open(archive_path) as tar: for tarinfo in tar: file_path = tarinfo.name file_obj = tar.extractfile(tarinfo) yield file_path, file_obj def test_audio_instantiation(): audio = Audio() assert audio.sampling_rate is None assert audio.mono is True assert audio.id is None assert audio.dtype == "dict" assert audio.pa_type == pa.struct({"bytes": pa.binary(), "path": pa.string()}) assert audio._type == "Audio" def test_audio_feature_type_to_arrow(): features = Features({"audio": Audio()}) assert features.arrow_schema == pa.schema({"audio": Audio().pa_type}) features = Features({"struct_containing_an_audio": {"audio": Audio()}}) assert features.arrow_schema == pa.schema({"struct_containing_an_audio": pa.struct({"audio": Audio().pa_type})}) features = Features({"sequence_of_audios": Sequence(Audio())}) assert features.arrow_schema == pa.schema({"sequence_of_audios": pa.list_(Audio().pa_type)}) @pytest.mark.parametrize( "build_example", [ lambda audio_path: audio_path, lambda audio_path: open(audio_path, "rb").read(), lambda audio_path: {"path": audio_path}, lambda audio_path: {"path": audio_path, "bytes": None}, lambda audio_path: {"path": audio_path, "bytes": open(audio_path, "rb").read()}, lambda audio_path: {"path": None, "bytes": open(audio_path, "rb").read()}, lambda audio_path: {"bytes": open(audio_path, "rb").read()}, lambda audio_path: {"array": [0.1, 0.2, 0.3], "sampling_rate": 16_000}, ], ) def test_audio_feature_encode_example(shared_datadir, build_example): audio_path = str(shared_datadir / "test_audio_44100.wav") audio = Audio() encoded_example = audio.encode_example(build_example(audio_path)) assert isinstance(encoded_example, dict) assert encoded_example.keys() == {"bytes", "path"} assert encoded_example["bytes"] is not None or encoded_example["path"] is not None decoded_example = audio.decode_example(encoded_example) assert decoded_example.keys() == {"path", "array", "sampling_rate"} @pytest.mark.parametrize( "build_example", [ lambda audio_path: {"path": audio_path, "sampling_rate": 16_000}, lambda audio_path: {"path": audio_path, "bytes": None, "sampling_rate": 16_000}, lambda audio_path: {"path": audio_path, "bytes": open(audio_path, "rb").read(), "sampling_rate": 16_000}, lambda audio_path: {"array": [0.1, 0.2, 0.3], "sampling_rate": 16_000}, ], ) def test_audio_feature_encode_example_pcm(shared_datadir, build_example): audio_path = str(shared_datadir / "test_audio_16000.pcm") audio = Audio(sampling_rate=16_000) encoded_example = audio.encode_example(build_example(audio_path)) assert isinstance(encoded_example, dict) assert encoded_example.keys() == {"bytes", "path"} assert encoded_example["bytes"] is not None or encoded_example["path"] is not None decoded_example = audio.decode_example(encoded_example) assert decoded_example.keys() == {"path", "array", "sampling_rate"} @require_sndfile def test_audio_decode_example(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.wav") audio = Audio() decoded_example = audio.decode_example(audio.encode_example(audio_path)) assert decoded_example.keys() == {"path", "array", "sampling_rate"} assert decoded_example["path"] == audio_path assert decoded_example["array"].shape == (202311,) assert decoded_example["sampling_rate"] == 44100 with pytest.raises(RuntimeError): Audio(decode=False).decode_example(audio_path) @require_sndfile def test_audio_resampling(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.wav") audio = Audio(sampling_rate=16000) decoded_example = audio.decode_example(audio.encode_example(audio_path)) assert decoded_example.keys() == {"path", "array", "sampling_rate"} assert decoded_example["path"] == audio_path assert decoded_example["array"].shape == (73401,) assert decoded_example["sampling_rate"] == 16000 @require_sndfile def test_audio_decode_example_mp3(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.mp3") audio = Audio() decoded_example = audio.decode_example(audio.encode_example(audio_path)) assert decoded_example.keys() == {"path", "array", "sampling_rate"} assert decoded_example["path"] == audio_path assert decoded_example["array"].shape == (110592,) assert decoded_example["sampling_rate"] == 44100 @require_sndfile def test_audio_decode_example_opus(shared_datadir): audio_path = str(shared_datadir / "test_audio_48000.opus") audio = Audio() decoded_example = audio.decode_example(audio.encode_example(audio_path)) assert decoded_example.keys() == {"path", "array", "sampling_rate"} assert decoded_example["path"] == audio_path assert decoded_example["array"].shape == (48000,) assert decoded_example["sampling_rate"] == 48000 @pytest.mark.parametrize("sampling_rate", [16_000, 48_000]) def test_audio_decode_example_pcm(shared_datadir, sampling_rate): audio_path = str(shared_datadir / "test_audio_16000.pcm") audio_input = {"path": audio_path, "sampling_rate": 16_000} audio = Audio(sampling_rate=sampling_rate) decoded_example = audio.decode_example(audio.encode_example(audio_input)) assert decoded_example.keys() == {"path", "array", "sampling_rate"} assert decoded_example["path"] is None assert decoded_example["array"].shape == (16208 * sampling_rate // 16_000,) assert decoded_example["sampling_rate"] == sampling_rate @require_sndfile def test_audio_resampling_mp3_different_sampling_rates(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.mp3") audio_path2 = str(shared_datadir / "test_audio_16000.mp3") audio = Audio(sampling_rate=48000) decoded_example = audio.decode_example(audio.encode_example(audio_path)) assert decoded_example.keys() == {"path", "array", "sampling_rate"} assert decoded_example["path"] == audio_path assert decoded_example["array"].shape == (120373,) assert decoded_example["sampling_rate"] == 48000 decoded_example = audio.decode_example(audio.encode_example(audio_path2)) assert decoded_example.keys() == {"path", "array", "sampling_rate"} assert decoded_example["path"] == audio_path2 assert decoded_example["array"].shape == (122688,) assert decoded_example["sampling_rate"] == 48000 @require_sndfile def test_dataset_with_audio_feature(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.wav") data = {"audio": [audio_path]} features = Features({"audio": Audio()}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"audio"} assert item["audio"].keys() == {"path", "array", "sampling_rate"} assert item["audio"]["path"] == audio_path assert item["audio"]["array"].shape == (202311,) assert item["audio"]["sampling_rate"] == 44100 batch = dset[:1] assert batch.keys() == {"audio"} assert len(batch["audio"]) == 1 assert batch["audio"][0].keys() == {"path", "array", "sampling_rate"} assert batch["audio"][0]["path"] == audio_path assert batch["audio"][0]["array"].shape == (202311,) assert batch["audio"][0]["sampling_rate"] == 44100 column = dset["audio"] assert len(column) == 1 assert column[0].keys() == {"path", "array", "sampling_rate"} assert column[0]["path"] == audio_path assert column[0]["array"].shape == (202311,) assert column[0]["sampling_rate"] == 44100 @require_sndfile def test_dataset_with_audio_feature_tar_wav(tar_wav_path): audio_filename = "test_audio_44100.wav" data = {"audio": []} for file_path, file_obj in iter_archive(tar_wav_path): data["audio"].append({"path": file_path, "bytes": file_obj.read()}) break features = Features({"audio": Audio()}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"audio"} assert item["audio"].keys() == {"path", "array", "sampling_rate"} assert item["audio"]["path"] == audio_filename assert item["audio"]["array"].shape == (202311,) assert item["audio"]["sampling_rate"] == 44100 batch = dset[:1] assert batch.keys() == {"audio"} assert len(batch["audio"]) == 1 assert batch["audio"][0].keys() == {"path", "array", "sampling_rate"} assert batch["audio"][0]["path"] == audio_filename assert batch["audio"][0]["array"].shape == (202311,) assert batch["audio"][0]["sampling_rate"] == 44100 column = dset["audio"] assert len(column) == 1 assert column[0].keys() == {"path", "array", "sampling_rate"} assert column[0]["path"] == audio_filename assert column[0]["array"].shape == (202311,) assert column[0]["sampling_rate"] == 44100 @require_sndfile def test_dataset_with_audio_feature_tar_mp3(tar_mp3_path): audio_filename = "test_audio_44100.mp3" data = {"audio": []} for file_path, file_obj in iter_archive(tar_mp3_path): data["audio"].append({"path": file_path, "bytes": file_obj.read()}) break features = Features({"audio": Audio()}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"audio"} assert item["audio"].keys() == {"path", "array", "sampling_rate"} assert item["audio"]["path"] == audio_filename assert item["audio"]["array"].shape == (110592,) assert item["audio"]["sampling_rate"] == 44100 batch = dset[:1] assert batch.keys() == {"audio"} assert len(batch["audio"]) == 1 assert batch["audio"][0].keys() == {"path", "array", "sampling_rate"} assert batch["audio"][0]["path"] == audio_filename assert batch["audio"][0]["array"].shape == (110592,) assert batch["audio"][0]["sampling_rate"] == 44100 column = dset["audio"] assert len(column) == 1 assert column[0].keys() == {"path", "array", "sampling_rate"} assert column[0]["path"] == audio_filename assert column[0]["array"].shape == (110592,) assert column[0]["sampling_rate"] == 44100 @require_sndfile def test_dataset_with_audio_feature_with_none(): data = {"audio": [None]} features = Features({"audio": Audio()}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"audio"} assert item["audio"] is None batch = dset[:1] assert len(batch) == 1 assert batch.keys() == {"audio"} assert isinstance(batch["audio"], list) and all(item is None for item in batch["audio"]) column = dset["audio"] assert len(column) == 1 assert isinstance(column, list) and all(item is None for item in column) # nested tests data = {"audio": [[None]]} features = Features({"audio": Sequence(Audio())}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"audio"} assert all(i is None for i in item["audio"]) data = {"nested": [{"audio": None}]} features = Features({"nested": {"audio": Audio()}}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"nested"} assert item["nested"].keys() == {"audio"} assert item["nested"]["audio"] is None @require_sndfile def test_resampling_at_loading_dataset_with_audio_feature(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.wav") data = {"audio": [audio_path]} features = Features({"audio": Audio(sampling_rate=16000)}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"audio"} assert item["audio"].keys() == {"path", "array", "sampling_rate"} assert item["audio"]["path"] == audio_path assert item["audio"]["array"].shape == (73401,) assert item["audio"]["sampling_rate"] == 16000 batch = dset[:1] assert batch.keys() == {"audio"} assert len(batch["audio"]) == 1 assert batch["audio"][0].keys() == {"path", "array", "sampling_rate"} assert batch["audio"][0]["path"] == audio_path assert batch["audio"][0]["array"].shape == (73401,) assert batch["audio"][0]["sampling_rate"] == 16000 column = dset["audio"] assert len(column) == 1 assert column[0].keys() == {"path", "array", "sampling_rate"} assert column[0]["path"] == audio_path assert column[0]["array"].shape == (73401,) assert column[0]["sampling_rate"] == 16000 @require_sndfile def test_resampling_at_loading_dataset_with_audio_feature_mp3(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.mp3") data = {"audio": [audio_path]} features = Features({"audio": Audio(sampling_rate=16000)}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"audio"} assert item["audio"].keys() == {"path", "array", "sampling_rate"} assert item["audio"]["path"] == audio_path assert item["audio"]["array"].shape == (40125,) assert item["audio"]["sampling_rate"] == 16000 batch = dset[:1] assert batch.keys() == {"audio"} assert len(batch["audio"]) == 1 assert batch["audio"][0].keys() == {"path", "array", "sampling_rate"} assert batch["audio"][0]["path"] == audio_path assert batch["audio"][0]["array"].shape == (40125,) assert batch["audio"][0]["sampling_rate"] == 16000 column = dset["audio"] assert len(column) == 1 assert column[0].keys() == {"path", "array", "sampling_rate"} assert column[0]["path"] == audio_path assert column[0]["array"].shape == (40125,) assert column[0]["sampling_rate"] == 16000 @require_sndfile def test_resampling_after_loading_dataset_with_audio_feature(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.wav") data = {"audio": [audio_path]} features = Features({"audio": Audio()}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item["audio"]["sampling_rate"] == 44100 dset = dset.cast_column("audio", Audio(sampling_rate=16000)) item = dset[0] assert item.keys() == {"audio"} assert item["audio"].keys() == {"path", "array", "sampling_rate"} assert item["audio"]["path"] == audio_path assert item["audio"]["array"].shape == (73401,) assert item["audio"]["sampling_rate"] == 16000 batch = dset[:1] assert batch.keys() == {"audio"} assert len(batch["audio"]) == 1 assert batch["audio"][0].keys() == {"path", "array", "sampling_rate"} assert batch["audio"][0]["path"] == audio_path assert batch["audio"][0]["array"].shape == (73401,) assert batch["audio"][0]["sampling_rate"] == 16000 column = dset["audio"] assert len(column) == 1 assert column[0].keys() == {"path", "array", "sampling_rate"} assert column[0]["path"] == audio_path assert column[0]["array"].shape == (73401,) assert column[0]["sampling_rate"] == 16000 @require_sndfile def test_resampling_after_loading_dataset_with_audio_feature_mp3(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.mp3") data = {"audio": [audio_path]} features = Features({"audio": Audio()}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item["audio"]["sampling_rate"] == 44100 dset = dset.cast_column("audio", Audio(sampling_rate=16000)) item = dset[0] assert item.keys() == {"audio"} assert item["audio"].keys() == {"path", "array", "sampling_rate"} assert item["audio"]["path"] == audio_path assert item["audio"]["array"].shape == (40125,) assert item["audio"]["sampling_rate"] == 16000 batch = dset[:1] assert batch.keys() == {"audio"} assert len(batch["audio"]) == 1 assert batch["audio"][0].keys() == {"path", "array", "sampling_rate"} assert batch["audio"][0]["path"] == audio_path assert batch["audio"][0]["array"].shape == (40125,) assert batch["audio"][0]["sampling_rate"] == 16000 column = dset["audio"] assert len(column) == 1 assert column[0].keys() == {"path", "array", "sampling_rate"} assert column[0]["path"] == audio_path assert column[0]["array"].shape == (40125,) assert column[0]["sampling_rate"] == 16000 @pytest.mark.parametrize( "build_data", [ lambda audio_path: {"audio": [audio_path]}, lambda audio_path: {"audio": [open(audio_path, "rb").read()]}, lambda audio_path: {"audio": [{"path": audio_path}]}, lambda audio_path: {"audio": [{"path": audio_path, "bytes": None}]}, lambda audio_path: {"audio": [{"path": audio_path, "bytes": open(audio_path, "rb").read()}]}, lambda audio_path: {"audio": [{"path": None, "bytes": open(audio_path, "rb").read()}]}, lambda audio_path: {"audio": [{"bytes": open(audio_path, "rb").read()}]}, ], ) def test_dataset_cast_to_audio_features(shared_datadir, build_data): audio_path = str(shared_datadir / "test_audio_44100.wav") data = build_data(audio_path) dset = Dataset.from_dict(data) item = dset.cast(Features({"audio": Audio()}))[0] assert item.keys() == {"audio"} assert item["audio"].keys() == {"path", "array", "sampling_rate"} item = dset.cast_column("audio", Audio())[0] assert item.keys() == {"audio"} assert item["audio"].keys() == {"path", "array", "sampling_rate"} def test_dataset_concatenate_audio_features(shared_datadir): # we use a different data structure between 1 and 2 to make sure they are compatible with each other audio_path = str(shared_datadir / "test_audio_44100.wav") data1 = {"audio": [audio_path]} dset1 = Dataset.from_dict(data1, features=Features({"audio": Audio()})) data2 = {"audio": [{"bytes": open(audio_path, "rb").read()}]} dset2 = Dataset.from_dict(data2, features=Features({"audio": Audio()})) concatenated_dataset = concatenate_datasets([dset1, dset2]) assert len(concatenated_dataset) == len(dset1) + len(dset2) assert concatenated_dataset[0]["audio"]["array"].shape == dset1[0]["audio"]["array"].shape assert concatenated_dataset[1]["audio"]["array"].shape == dset2[0]["audio"]["array"].shape def test_dataset_concatenate_nested_audio_features(shared_datadir): # we use a different data structure between 1 and 2 to make sure they are compatible with each other audio_path = str(shared_datadir / "test_audio_44100.wav") features = Features({"list_of_structs_of_audios": [{"audio": Audio()}]}) data1 = {"list_of_structs_of_audios": [[{"audio": audio_path}]]} dset1 = Dataset.from_dict(data1, features=features) data2 = {"list_of_structs_of_audios": [[{"audio": {"bytes": open(audio_path, "rb").read()}}]]} dset2 = Dataset.from_dict(data2, features=features) concatenated_dataset = concatenate_datasets([dset1, dset2]) assert len(concatenated_dataset) == len(dset1) + len(dset2) assert ( concatenated_dataset[0]["list_of_structs_of_audios"][0]["audio"]["array"].shape == dset1[0]["list_of_structs_of_audios"][0]["audio"]["array"].shape ) assert ( concatenated_dataset[1]["list_of_structs_of_audios"][0]["audio"]["array"].shape == dset2[0]["list_of_structs_of_audios"][0]["audio"]["array"].shape ) @require_sndfile def test_dataset_with_audio_feature_map_is_not_decoded(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.wav") data = {"audio": [audio_path], "text": ["Hello"]} features = Features({"audio": Audio(), "text": Value("string")}) dset = Dataset.from_dict(data, features=features) expected_audio = features.encode_batch(data)["audio"][0] for item in dset.cast_column("audio", Audio(decode=False)): assert item.keys() == {"audio", "text"} assert item == {"audio": expected_audio, "text": "Hello"} def process_text(example): example["text"] = example["text"] + " World!" return example processed_dset = dset.map(process_text) for item in processed_dset.cast_column("audio", Audio(decode=False)): assert item.keys() == {"audio", "text"} assert item == {"audio": expected_audio, "text": "Hello World!"} @require_sndfile def test_dataset_with_audio_feature_map_is_decoded(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.wav") data = {"audio": [audio_path], "text": ["Hello"]} features = Features({"audio": Audio(), "text": Value("string")}) dset = Dataset.from_dict(data, features=features) def process_audio_sampling_rate_by_example(example): example["double_sampling_rate"] = 2 * example["audio"]["sampling_rate"] return example decoded_dset = dset.map(process_audio_sampling_rate_by_example) for item in decoded_dset.cast_column("audio", Audio(decode=False)): assert item.keys() == {"audio", "text", "double_sampling_rate"} assert item["double_sampling_rate"] == 88200 def process_audio_sampling_rate_by_batch(batch): double_sampling_rates = [] for audio in batch["audio"]: double_sampling_rates.append(2 * audio["sampling_rate"]) batch["double_sampling_rate"] = double_sampling_rates return batch decoded_dset = dset.map(process_audio_sampling_rate_by_batch, batched=True) for item in decoded_dset.cast_column("audio", Audio(decode=False)): assert item.keys() == {"audio", "text", "double_sampling_rate"} assert item["double_sampling_rate"] == 88200 @require_sndfile def test_formatted_dataset_with_audio_feature(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.wav") data = {"audio": [audio_path, audio_path]} features = Features({"audio": Audio()}) dset = Dataset.from_dict(data, features=features) with dset.formatted_as("numpy"): item = dset[0] assert item.keys() == {"audio"} assert item["audio"].keys() == {"path", "array", "sampling_rate"} assert item["audio"]["path"] == audio_path assert item["audio"]["array"].shape == (202311,) assert item["audio"]["sampling_rate"] == 44100 batch = dset[:1] assert batch.keys() == {"audio"} assert len(batch["audio"]) == 1 assert batch["audio"][0].keys() == {"path", "array", "sampling_rate"} assert batch["audio"][0]["path"] == audio_path assert batch["audio"][0]["array"].shape == (202311,) assert batch["audio"][0]["sampling_rate"] == 44100 column = dset["audio"] assert len(column) == 2 assert column[0].keys() == {"path", "array", "sampling_rate"} assert column[0]["path"] == audio_path assert column[0]["array"].shape == (202311,) assert column[0]["sampling_rate"] == 44100 with dset.formatted_as("pandas"): item = dset[0] assert item.shape == (1, 1) assert item.columns == ["audio"] assert item["audio"][0].keys() == {"path", "array", "sampling_rate"} assert item["audio"][0]["path"] == audio_path assert item["audio"][0]["array"].shape == (202311,) assert item["audio"][0]["sampling_rate"] == 44100 batch = dset[:1] assert batch.shape == (1, 1) assert batch.columns == ["audio"] assert batch["audio"][0].keys() == {"path", "array", "sampling_rate"} assert batch["audio"][0]["path"] == audio_path assert batch["audio"][0]["array"].shape == (202311,) assert batch["audio"][0]["sampling_rate"] == 44100 column = dset["audio"] assert len(column) == 2 assert column[0].keys() == {"path", "array", "sampling_rate"} assert column[0]["path"] == audio_path assert column[0]["array"].shape == (202311,) assert column[0]["sampling_rate"] == 44100 @pytest.fixture def jsonl_audio_dataset_path(shared_datadir, tmp_path_factory): import json audio_path = str(shared_datadir / "test_audio_44100.wav") data = [{"audio": audio_path, "text": "Hello world!"}] path = str(tmp_path_factory.mktemp("data") / "audio_dataset.jsonl") with open(path, "w") as f: for item in data: f.write(json.dumps(item) + "\n") return path @require_sndfile @pytest.mark.parametrize("streaming", [False, True]) def test_load_dataset_with_audio_feature(streaming, jsonl_audio_dataset_path, shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.wav") data_files = jsonl_audio_dataset_path features = Features({"audio": Audio(), "text": Value("string")}) dset = load_dataset("json", split="train", data_files=data_files, features=features, streaming=streaming) item = dset[0] if not streaming else next(iter(dset)) assert item.keys() == {"audio", "text"} assert item["audio"].keys() == {"path", "array", "sampling_rate"} assert item["audio"]["path"] == audio_path assert item["audio"]["array"].shape == (202311,) assert item["audio"]["sampling_rate"] == 44100 @require_sndfile @pytest.mark.integration def test_dataset_with_audio_feature_loaded_from_cache(): # load first time ds = load_dataset("patrickvonplaten/librispeech_asr_dummy", "clean") # load from cache ds = load_dataset("patrickvonplaten/librispeech_asr_dummy", "clean", split="validation") assert isinstance(ds, Dataset) def test_dataset_with_audio_feature_undecoded(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.wav") data = {"audio": [audio_path]} features = Features({"audio": Audio(decode=False)}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"audio"} assert item["audio"] == {"path": audio_path, "bytes": None} batch = dset[:1] assert batch.keys() == {"audio"} assert len(batch["audio"]) == 1 assert batch["audio"][0] == {"path": audio_path, "bytes": None} column = dset["audio"] assert len(column) == 1 assert column[0] == {"path": audio_path, "bytes": None} def test_formatted_dataset_with_audio_feature_undecoded(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.wav") data = {"audio": [audio_path]} features = Features({"audio": Audio(decode=False)}) dset = Dataset.from_dict(data, features=features) with dset.formatted_as("numpy"): item = dset[0] assert item.keys() == {"audio"} assert item["audio"] == {"path": audio_path, "bytes": None} batch = dset[:1] assert batch.keys() == {"audio"} assert len(batch["audio"]) == 1 assert batch["audio"][0] == {"path": audio_path, "bytes": None} column = dset["audio"] assert len(column) == 1 assert column[0] == {"path": audio_path, "bytes": None} with dset.formatted_as("pandas"): item = dset[0] assert item.shape == (1, 1) assert item.columns == ["audio"] assert item["audio"][0] == {"path": audio_path, "bytes": None} batch = dset[:1] assert batch.shape == (1, 1) assert batch.columns == ["audio"] assert batch["audio"][0] == {"path": audio_path, "bytes": None} column = dset["audio"] assert len(column) == 1 assert column[0] == {"path": audio_path, "bytes": None} def test_dataset_with_audio_feature_map_undecoded(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.wav") data = {"audio": [audio_path]} features = Features({"audio": Audio(decode=False)}) dset = Dataset.from_dict(data, features=features) def assert_audio_example_undecoded(example): assert example["audio"] == {"path": audio_path, "bytes": None} dset.map(assert_audio_example_undecoded) def assert_audio_batch_undecoded(batch): for audio in batch["audio"]: assert audio == {"path": audio_path, "bytes": None} dset.map(assert_audio_batch_undecoded, batched=True) def test_audio_embed_storage(shared_datadir): audio_path = str(shared_datadir / "test_audio_44100.wav") example = {"bytes": None, "path": audio_path} storage = pa.array([example], type=pa.struct({"bytes": pa.binary(), "path": pa.string()})) embedded_storage = Audio().embed_storage(storage) embedded_example = embedded_storage.to_pylist()[0] assert embedded_example == {"bytes": open(audio_path, "rb").read(), "path": "test_audio_44100.wav"}
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/features/test_features.py
import datetime from unittest import TestCase from unittest.mock import patch import numpy as np import pandas as pd import pyarrow as pa import pytest from datasets import Array2D from datasets.arrow_dataset import Dataset from datasets.features import Audio, ClassLabel, Features, Image, Sequence, Value from datasets.features.features import ( _arrow_to_datasets_dtype, _cast_to_python_objects, cast_to_python_objects, encode_nested_example, generate_from_dict, string_to_arrow, ) from datasets.features.translation import Translation, TranslationVariableLanguages from datasets.info import DatasetInfo from datasets.utils.py_utils import asdict from ..utils import require_jax, require_tf, require_torch class FeaturesTest(TestCase): def test_from_arrow_schema_simple(self): data = {"a": [{"b": {"c": "text"}}] * 10, "foo": [1] * 10} original_features = Features({"a": {"b": {"c": Value("string")}}, "foo": Value("int64")}) dset = Dataset.from_dict(data, features=original_features) new_features = dset.features new_dset = Dataset.from_dict(data, features=new_features) self.assertEqual(original_features.type, new_features.type) self.assertDictEqual(dset[0], new_dset[0]) self.assertDictEqual(dset[:], new_dset[:]) def test_from_arrow_schema_with_sequence(self): data = {"a": [{"b": {"c": ["text"]}}] * 10, "foo": [1] * 10} original_features = Features({"a": {"b": Sequence({"c": Value("string")})}, "foo": Value("int64")}) dset = Dataset.from_dict(data, features=original_features) new_features = dset.features new_dset = Dataset.from_dict(data, features=new_features) self.assertEqual(original_features.type, new_features.type) self.assertDictEqual(dset[0], new_dset[0]) self.assertDictEqual(dset[:], new_dset[:]) def test_string_to_arrow_bijection_for_primitive_types(self): supported_pyarrow_datatypes = [ pa.time32("s"), pa.time64("us"), pa.timestamp("s"), pa.timestamp("ns", tz="America/New_York"), pa.date32(), pa.date64(), pa.duration("s"), pa.decimal128(10, 2), pa.decimal256(40, -3), pa.string(), pa.int32(), pa.float64(), pa.array([datetime.time(1, 1, 1)]).type, # arrow type: DataType(time64[us]) ] for dt in supported_pyarrow_datatypes: self.assertEqual(dt, string_to_arrow(_arrow_to_datasets_dtype(dt))) unsupported_pyarrow_datatypes = [pa.list_(pa.float64())] for dt in unsupported_pyarrow_datatypes: with self.assertRaises(ValueError): string_to_arrow(_arrow_to_datasets_dtype(dt)) supported_datasets_dtypes = [ "time32[s]", "timestamp[ns]", "timestamp[ns, tz=+07:30]", "duration[us]", "decimal128(30, -4)", "int32", "float64", ] for sdt in supported_datasets_dtypes: self.assertEqual(sdt, _arrow_to_datasets_dtype(string_to_arrow(sdt))) unsupported_datasets_dtypes = [ "time32[ns]", "timestamp[blob]", "timestamp[[ns]]", "timestamp[ns, tz=[ns]]", "duration[[us]]", "decimal20(30, -4)", "int", ] for sdt in unsupported_datasets_dtypes: with self.assertRaises(ValueError): string_to_arrow(sdt) def test_feature_named_type(self): """reference: issue #1110""" features = Features({"_type": Value("string")}) ds_info = DatasetInfo(features=features) reloaded_features = Features.from_dict(asdict(ds_info)["features"]) assert features == reloaded_features def test_feature_named_self_as_kwarg(self): """reference: issue #5641""" features = Features(self=Value("string")) ds_info = DatasetInfo(features=features) reloaded_features = Features.from_dict(asdict(ds_info)["features"]) assert features == reloaded_features def test_class_label_feature_with_no_labels(self): """reference: issue #4681""" features = Features({"label": ClassLabel(names=[])}) ds_info = DatasetInfo(features=features) reloaded_features = Features.from_dict(asdict(ds_info)["features"]) assert features == reloaded_features def test_reorder_fields_as(self): features = Features( { "id": Value("string"), "document": { "title": Value("string"), "url": Value("string"), "html": Value("string"), "tokens": Sequence({"token": Value("string"), "is_html": Value("bool")}), }, "question": { "text": Value("string"), "tokens": Sequence(Value("string")), }, "annotations": Sequence( { "id": Value("string"), "long_answer": { "start_token": Value("int64"), "end_token": Value("int64"), "start_byte": Value("int64"), "end_byte": Value("int64"), }, "short_answers": Sequence( { "start_token": Value("int64"), "end_token": Value("int64"), "start_byte": Value("int64"), "end_byte": Value("int64"), "text": Value("string"), } ), "yes_no_answer": ClassLabel(names=["NO", "YES"]), } ), } ) other = Features( # same but with [] instead of sequences, and with a shuffled fields order { "id": Value("string"), "document": { "tokens": Sequence({"token": Value("string"), "is_html": Value("bool")}), "title": Value("string"), "url": Value("string"), "html": Value("string"), }, "question": { "text": Value("string"), "tokens": [Value("string")], }, "annotations": { "yes_no_answer": [ClassLabel(names=["NO", "YES"])], "id": [Value("string")], "long_answer": [ { "end_byte": Value("int64"), "start_token": Value("int64"), "end_token": Value("int64"), "start_byte": Value("int64"), } ], "short_answers": [ Sequence( { "text": Value("string"), "start_token": Value("int64"), "end_token": Value("int64"), "start_byte": Value("int64"), "end_byte": Value("int64"), } ) ], }, } ) expected = Features( { "id": Value("string"), "document": { "tokens": Sequence({"token": Value("string"), "is_html": Value("bool")}), "title": Value("string"), "url": Value("string"), "html": Value("string"), }, "question": { "text": Value("string"), "tokens": Sequence(Value("string")), }, "annotations": Sequence( { "yes_no_answer": ClassLabel(names=["NO", "YES"]), "id": Value("string"), "long_answer": { "end_byte": Value("int64"), "start_token": Value("int64"), "end_token": Value("int64"), "start_byte": Value("int64"), }, "short_answers": Sequence( { "text": Value("string"), "start_token": Value("int64"), "end_token": Value("int64"), "start_byte": Value("int64"), "end_byte": Value("int64"), } ), } ), } ) reordered_features = features.reorder_fields_as(other) self.assertDictEqual(reordered_features, expected) self.assertEqual(reordered_features.type, other.type) self.assertEqual(reordered_features.type, expected.type) self.assertNotEqual(reordered_features.type, features.type) def test_flatten(self): features = Features({"foo": {"bar1": Value("int32"), "bar2": {"foobar": Value("string")}}}) _features = features.copy() flattened_features = features.flatten() assert flattened_features == {"foo.bar1": Value("int32"), "foo.bar2.foobar": Value("string")} assert features == _features, "calling flatten shouldn't alter the current features" def test_flatten_with_sequence(self): features = Features({"foo": Sequence({"bar": {"my_value": Value("int32")}})}) _features = features.copy() flattened_features = features.flatten() assert flattened_features == {"foo.bar": [{"my_value": Value("int32")}]} assert features == _features, "calling flatten shouldn't alter the current features" def test_features_dicts_are_synced(self): def assert_features_dicts_are_synced(features: Features): assert ( hasattr(features, "_column_requires_decoding") and features.keys() == features._column_requires_decoding.keys() ) features = Features({"foo": Sequence({"bar": {"my_value": Value("int32")}})}) assert_features_dicts_are_synced(features) features["barfoo"] = Image() assert_features_dicts_are_synced(features) del features["barfoo"] assert_features_dicts_are_synced(features) features.update({"foobar": Value("string")}) assert_features_dicts_are_synced(features) features.pop("foobar") assert_features_dicts_are_synced(features) features.popitem() assert_features_dicts_are_synced(features) features.setdefault("xyz", Value("bool")) assert_features_dicts_are_synced(features) features.clear() assert_features_dicts_are_synced(features) def test_classlabel_init(tmp_path_factory): names = ["negative", "positive"] names_file = str(tmp_path_factory.mktemp("features") / "labels.txt") with open(names_file, "w", encoding="utf-8") as f: f.write("\n".join(names)) classlabel = ClassLabel(names=names) assert classlabel.names == names and classlabel.num_classes == len(names) classlabel = ClassLabel(names_file=names_file) assert classlabel.names == names and classlabel.num_classes == len(names) classlabel = ClassLabel(num_classes=len(names), names=names) assert classlabel.names == names and classlabel.num_classes == len(names) classlabel = ClassLabel(num_classes=len(names)) assert classlabel.names == [str(i) for i in range(len(names))] and classlabel.num_classes == len(names) with pytest.raises(ValueError): classlabel = ClassLabel(num_classes=len(names) + 1, names=names) with pytest.raises(ValueError): classlabel = ClassLabel(names=names, names_file=names_file) with pytest.raises(ValueError): classlabel = ClassLabel() with pytest.raises(TypeError): classlabel = ClassLabel(names=np.array(names)) def test_classlabel_str2int(): names = ["negative", "positive"] classlabel = ClassLabel(names=names) for label in names: assert classlabel.str2int(label) == names.index(label) with pytest.raises(ValueError): classlabel.str2int("__bad_label_name__") with pytest.raises(ValueError): classlabel.str2int(1) with pytest.raises(ValueError): classlabel.str2int(None) def test_classlabel_int2str(): names = ["negative", "positive"] classlabel = ClassLabel(names=names) for i in range(len(names)): assert classlabel.int2str(i) == names[i] with pytest.raises(ValueError): classlabel.int2str(len(names)) with pytest.raises(ValueError): classlabel.int2str(-1) with pytest.raises(ValueError): classlabel.int2str(None) def test_classlabel_cast_storage(): names = ["negative", "positive"] classlabel = ClassLabel(names=names) # from integers arr = pa.array([0, 1, -1, -100], type=pa.int64()) result = classlabel.cast_storage(arr) assert result.type == pa.int64() assert result.to_pylist() == [0, 1, -1, -100] arr = pa.array([0, 1, -1, -100], type=pa.int32()) result = classlabel.cast_storage(arr) assert result.type == pa.int64() assert result.to_pylist() == [0, 1, -1, -100] arr = pa.array([3]) with pytest.raises(ValueError): classlabel.cast_storage(arr) # from strings arr = pa.array(["negative", "positive"]) result = classlabel.cast_storage(arr) assert result.type == pa.int64() assert result.to_pylist() == [0, 1] arr = pa.array(["__label_that_doesnt_exist__"]) with pytest.raises(ValueError): classlabel.cast_storage(arr) # from nulls arr = pa.array([None]) result = classlabel.cast_storage(arr) assert result.type == pa.int64() assert result.to_pylist() == [None] # from empty arr = pa.array([], pa.int64()) result = classlabel.cast_storage(arr) assert result.type == pa.int64() assert result.to_pylist() == [] arr = pa.array([], pa.string()) result = classlabel.cast_storage(arr) assert result.type == pa.int64() assert result.to_pylist() == [] @pytest.mark.parametrize("class_label_arg", ["names", "names_file"]) def test_class_label_to_and_from_dict(class_label_arg, tmp_path_factory): names = ["negative", "positive"] names_file = str(tmp_path_factory.mktemp("features") / "labels.txt") with open(names_file, "w", encoding="utf-8") as f: f.write("\n".join(names)) if class_label_arg == "names": class_label = ClassLabel(names=names) elif class_label_arg == "names_file": class_label = ClassLabel(names_file=names_file) generated_class_label = generate_from_dict(asdict(class_label)) assert generated_class_label == class_label @pytest.mark.parametrize("inner_type", [Value("int32"), {"subcolumn": Value("int32")}]) def test_encode_nested_example_sequence_with_none(inner_type): schema = Sequence(inner_type) obj = None result = encode_nested_example(schema, obj) assert result is None def test_encode_batch_with_example_with_empty_first_elem(): features = Features( { "x": Sequence(Sequence(ClassLabel(names=["a", "b"]))), } ) encoded_batch = features.encode_batch( { "x": [ [["a"], ["b"]], [[], ["b"]], ] } ) assert encoded_batch == {"x": [[[0], [1]], [[], [1]]]} @pytest.mark.parametrize( "feature", [ Value("int32"), ClassLabel(num_classes=2), Translation(languages=["en", "fr"]), TranslationVariableLanguages(languages=["en", "fr"]), ], ) def test_dataset_feature_with_none(feature): data = {"col": [None]} features = Features({"col": feature}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"col"} assert item["col"] is None batch = dset[:1] assert len(batch) == 1 assert batch.keys() == {"col"} assert isinstance(batch["col"], list) and all(item is None for item in batch["col"]) column = dset["col"] assert len(column) == 1 assert isinstance(column, list) and all(item is None for item in column) # nested tests data = {"col": [[None]]} features = Features({"col": Sequence(feature)}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"col"} assert all(i is None for i in item["col"]) data = {"nested": [{"col": None}]} features = Features({"nested": {"col": feature}}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"nested"} assert item["nested"].keys() == {"col"} assert item["nested"]["col"] is None def iternumpy(key1, value1, value2): if value1.dtype != value2.dtype: # check only for dtype raise AssertionError( f"dtype of '{key1}' key for casted object: {value1.dtype} and expected object: {value2.dtype} not matching" ) def dict_diff(d1: dict, d2: dict): # check if 2 dictionaries are equal np.testing.assert_equal(d1, d2) # sanity check if dict values are equal or not for (k1, v1), (k2, v2) in zip(d1.items(), d2.items()): # check if their values have same dtype or not if isinstance(v1, dict): # nested dictionary case dict_diff(v1, v2) elif isinstance(v1, np.ndarray): # checks if dtype and value of np.ndarray is equal iternumpy(k1, v1, v2) elif isinstance(v1, list): for element1, element2 in zip(v1, v2): # iterates over all elements of list if isinstance(element1, dict): dict_diff(element1, element2) elif isinstance(element1, np.ndarray): iternumpy(k1, element1, element2) class CastToPythonObjectsTest(TestCase): def test_cast_to_python_objects_list(self): obj = {"col_1": [{"vec": [1, 2, 3], "txt": "foo"}] * 3, "col_2": [[1, 2], [3, 4], [5, 6]]} expected_obj = {"col_1": [{"vec": [1, 2, 3], "txt": "foo"}] * 3, "col_2": [[1, 2], [3, 4], [5, 6]]} casted_obj = cast_to_python_objects(obj) self.assertDictEqual(casted_obj, expected_obj) def test_cast_to_python_objects_tuple(self): obj = {"col_1": [{"vec": (1, 2, 3), "txt": "foo"}] * 3, "col_2": [(1, 2), (3, 4), (5, 6)]} expected_obj = {"col_1": [{"vec": (1, 2, 3), "txt": "foo"}] * 3, "col_2": [(1, 2), (3, 4), (5, 6)]} casted_obj = cast_to_python_objects(obj) self.assertDictEqual(casted_obj, expected_obj) def test_cast_to_python_or_numpy(self): obj = {"col_1": [{"vec": np.arange(1, 4), "txt": "foo"}] * 3, "col_2": np.arange(1, 7).reshape(3, 2)} expected_obj = { "col_1": [{"vec": np.array([1, 2, 3]), "txt": "foo"}] * 3, "col_2": np.array([[1, 2], [3, 4], [5, 6]]), } casted_obj = cast_to_python_objects(obj) dict_diff(casted_obj, expected_obj) def test_cast_to_python_objects_series(self): obj = { "col_1": pd.Series([{"vec": [1, 2, 3], "txt": "foo"}] * 3), "col_2": pd.Series([[1, 2], [3, 4], [5, 6]]), } expected_obj = {"col_1": [{"vec": [1, 2, 3], "txt": "foo"}] * 3, "col_2": [[1, 2], [3, 4], [5, 6]]} casted_obj = cast_to_python_objects(obj) self.assertDictEqual(casted_obj, expected_obj) def test_cast_to_python_objects_dataframe(self): obj = pd.DataFrame({"col_1": [{"vec": [1, 2, 3], "txt": "foo"}] * 3, "col_2": [[1, 2], [3, 4], [5, 6]]}) expected_obj = {"col_1": [{"vec": [1, 2, 3], "txt": "foo"}] * 3, "col_2": [[1, 2], [3, 4], [5, 6]]} casted_obj = cast_to_python_objects(obj) self.assertDictEqual(casted_obj, expected_obj) def test_cast_to_python_objects_pandas_timestamp(self): obj = pd.Timestamp(2020, 1, 1) expected_obj = obj.to_pydatetime() casted_obj = cast_to_python_objects(obj) self.assertEqual(casted_obj, expected_obj) casted_obj = cast_to_python_objects(pd.Series([obj])) self.assertListEqual(casted_obj, [expected_obj]) casted_obj = cast_to_python_objects(pd.DataFrame({"a": [obj]})) self.assertDictEqual(casted_obj, {"a": [expected_obj]}) def test_cast_to_python_objects_pandas_timedelta(self): obj = pd.Timedelta(seconds=1) expected_obj = obj.to_pytimedelta() casted_obj = cast_to_python_objects(obj) self.assertEqual(casted_obj, expected_obj) casted_obj = cast_to_python_objects(pd.Series([obj])) self.assertListEqual(casted_obj, [expected_obj]) casted_obj = cast_to_python_objects(pd.DataFrame({"a": [obj]})) self.assertDictEqual(casted_obj, {"a": [expected_obj]}) @require_torch def test_cast_to_python_objects_torch(self): import torch obj = { "col_1": [{"vec": torch.tensor(np.arange(1, 4)), "txt": "foo"}] * 3, "col_2": torch.tensor(np.arange(1, 7).reshape(3, 2)), } expected_obj = { "col_1": [{"vec": np.array([1, 2, 3]), "txt": "foo"}] * 3, "col_2": np.array([[1, 2], [3, 4], [5, 6]]), } casted_obj = cast_to_python_objects(obj) dict_diff(casted_obj, expected_obj) @require_tf def test_cast_to_python_objects_tf(self): import tensorflow as tf obj = { "col_1": [{"vec": tf.constant(np.arange(1, 4)), "txt": "foo"}] * 3, "col_2": tf.constant(np.arange(1, 7).reshape(3, 2)), } expected_obj = { "col_1": [{"vec": np.array([1, 2, 3]), "txt": "foo"}] * 3, "col_2": np.array([[1, 2], [3, 4], [5, 6]]), } casted_obj = cast_to_python_objects(obj) dict_diff(casted_obj, expected_obj) @require_jax def test_cast_to_python_objects_jax(self): import jax.numpy as jnp obj = { "col_1": [{"vec": jnp.array(np.arange(1, 4)), "txt": "foo"}] * 3, "col_2": jnp.array(np.arange(1, 7).reshape(3, 2)), } assert obj["col_2"].dtype == jnp.int32 expected_obj = { "col_1": [{"vec": np.array([1, 2, 3], dtype=np.int32), "txt": "foo"}] * 3, "col_2": np.array([[1, 2], [3, 4], [5, 6]], dtype=np.int32), } casted_obj = cast_to_python_objects(obj) dict_diff(casted_obj, expected_obj) @patch("datasets.features.features._cast_to_python_objects", side_effect=_cast_to_python_objects) def test_dont_iterate_over_each_element_in_a_list(self, mocked_cast): obj = {"col_1": [[1, 2], [3, 4], [5, 6]]} cast_to_python_objects(obj) self.assertEqual(mocked_cast.call_count, 4) # 4 = depth of obj SIMPLE_FEATURES = [ Features(), Features({"a": Value("int32")}), Features({"a": Value("int32", id="my feature")}), Features({"a": Value("int32"), "b": Value("float64"), "c": Value("string")}), ] CUSTOM_FEATURES = [ Features({"label": ClassLabel(names=["negative", "positive"])}), Features({"array": Array2D(dtype="float32", shape=(4, 4))}), Features({"image": Image()}), Features({"audio": Audio()}), Features({"image": Image(decode=False)}), Features({"audio": Audio(decode=False)}), Features({"translation": Translation(["en", "fr"])}), Features({"translation": TranslationVariableLanguages(["en", "fr"])}), ] NESTED_FEATURES = [ Features({"foo": {}}), Features({"foo": {"bar": Value("int32")}}), Features({"foo": {"bar1": Value("int32"), "bar2": Value("float64")}}), Features({"foo": Sequence(Value("int32"))}), Features({"foo": Sequence({})}), Features({"foo": Sequence({"bar": Value("int32")})}), Features({"foo": [Value("int32")]}), Features({"foo": [{"bar": Value("int32")}]}), ] NESTED_CUSTOM_FEATURES = [ Features({"foo": {"bar": ClassLabel(names=["negative", "positive"])}}), Features({"foo": Sequence(ClassLabel(names=["negative", "positive"]))}), Features({"foo": Sequence({"bar": ClassLabel(names=["negative", "positive"])})}), Features({"foo": [ClassLabel(names=["negative", "positive"])]}), Features({"foo": [{"bar": ClassLabel(names=["negative", "positive"])}]}), ] @pytest.mark.parametrize("features", SIMPLE_FEATURES + CUSTOM_FEATURES + NESTED_FEATURES + NESTED_CUSTOM_FEATURES) def test_features_to_dict(features: Features): features_dict = features.to_dict() assert isinstance(features_dict, dict) reloaded = Features.from_dict(features_dict) assert features == reloaded @pytest.mark.parametrize("features", SIMPLE_FEATURES + CUSTOM_FEATURES + NESTED_FEATURES + NESTED_CUSTOM_FEATURES) def test_features_to_yaml_list(features: Features): features_yaml_list = features._to_yaml_list() assert isinstance(features_yaml_list, list) reloaded = Features._from_yaml_list(features_yaml_list) assert features == reloaded @pytest.mark.parametrize("features", SIMPLE_FEATURES + CUSTOM_FEATURES + NESTED_FEATURES + NESTED_CUSTOM_FEATURES) def test_features_to_arrow_schema(features: Features): arrow_schema = features.arrow_schema assert isinstance(arrow_schema, pa.Schema) reloaded = Features.from_arrow_schema(arrow_schema) assert features == reloaded
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/features/test_image.py
import os import tarfile import warnings import numpy as np import pandas as pd import pyarrow as pa import pytest from datasets import Dataset, Features, Image, Sequence, Value, concatenate_datasets, load_dataset from datasets.features.image import encode_np_array, image_to_bytes from ..utils import require_pil @pytest.fixture def tar_jpg_path(shared_datadir, tmp_path_factory): image_path = str(shared_datadir / "test_image_rgb.jpg") path = tmp_path_factory.mktemp("data") / "image_data.jpg.tar" with tarfile.TarFile(path, "w") as f: f.add(image_path, arcname=os.path.basename(image_path)) return path def iter_archive(archive_path): with tarfile.open(archive_path) as tar: for tarinfo in tar: file_path = tarinfo.name file_obj = tar.extractfile(tarinfo) yield file_path, file_obj def test_image_instantiation(): image = Image() assert image.id is None assert image.dtype == "PIL.Image.Image" assert image.pa_type == pa.struct({"bytes": pa.binary(), "path": pa.string()}) assert image._type == "Image" def test_image_feature_type_to_arrow(): features = Features({"image": Image()}) assert features.arrow_schema == pa.schema({"image": Image().pa_type}) features = Features({"struct_containing_an_image": {"image": Image()}}) assert features.arrow_schema == pa.schema({"struct_containing_an_image": pa.struct({"image": Image().pa_type})}) features = Features({"sequence_of_images": Sequence(Image())}) assert features.arrow_schema == pa.schema({"sequence_of_images": pa.list_(Image().pa_type)}) @require_pil @pytest.mark.parametrize( "build_example", [ lambda image_path: image_path, lambda image_path: open(image_path, "rb").read(), lambda image_path: {"path": image_path}, lambda image_path: {"path": image_path, "bytes": None}, lambda image_path: {"path": image_path, "bytes": open(image_path, "rb").read()}, lambda image_path: {"path": None, "bytes": open(image_path, "rb").read()}, lambda image_path: {"bytes": open(image_path, "rb").read()}, ], ) def test_image_feature_encode_example(shared_datadir, build_example): import PIL.Image image_path = str(shared_datadir / "test_image_rgb.jpg") image = Image() encoded_example = image.encode_example(build_example(image_path)) assert isinstance(encoded_example, dict) assert encoded_example.keys() == {"bytes", "path"} assert encoded_example["bytes"] is not None or encoded_example["path"] is not None decoded_example = image.decode_example(encoded_example) assert isinstance(decoded_example, PIL.Image.Image) @require_pil def test_image_decode_example(shared_datadir): import PIL.Image image_path = str(shared_datadir / "test_image_rgb.jpg") image = Image() decoded_example = image.decode_example({"path": image_path, "bytes": None}) assert isinstance(decoded_example, PIL.Image.Image) assert os.path.samefile(decoded_example.filename, image_path) assert decoded_example.size == (640, 480) assert decoded_example.mode == "RGB" with pytest.raises(RuntimeError): Image(decode=False).decode_example(image_path) @require_pil def test_dataset_with_image_feature(shared_datadir): import PIL.Image image_path = str(shared_datadir / "test_image_rgb.jpg") data = {"image": [image_path]} features = Features({"image": Image()}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"image"} assert isinstance(item["image"], PIL.Image.Image) assert os.path.samefile(item["image"].filename, image_path) assert item["image"].format == "JPEG" assert item["image"].size == (640, 480) assert item["image"].mode == "RGB" batch = dset[:1] assert len(batch) == 1 assert batch.keys() == {"image"} assert isinstance(batch["image"], list) and all(isinstance(item, PIL.Image.Image) for item in batch["image"]) assert os.path.samefile(batch["image"][0].filename, image_path) assert batch["image"][0].format == "JPEG" assert batch["image"][0].size == (640, 480) assert batch["image"][0].mode == "RGB" column = dset["image"] assert len(column) == 1 assert isinstance(column, list) and all(isinstance(item, PIL.Image.Image) for item in column) assert os.path.samefile(column[0].filename, image_path) assert column[0].format == "JPEG" assert column[0].size == (640, 480) assert column[0].mode == "RGB" @require_pil @pytest.mark.parametrize("infer_feature", [False, True]) def test_dataset_with_image_feature_from_pil_image(infer_feature, shared_datadir): import PIL.Image image_path = str(shared_datadir / "test_image_rgb.jpg") data = {"image": [PIL.Image.open(image_path)]} features = Features({"image": Image()}) if not infer_feature else None dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"image"} assert isinstance(item["image"], PIL.Image.Image) assert os.path.samefile(item["image"].filename, image_path) assert item["image"].format == "JPEG" assert item["image"].size == (640, 480) assert item["image"].mode == "RGB" batch = dset[:1] assert len(batch) == 1 assert batch.keys() == {"image"} assert isinstance(batch["image"], list) and all(isinstance(item, PIL.Image.Image) for item in batch["image"]) assert os.path.samefile(batch["image"][0].filename, image_path) assert batch["image"][0].format == "JPEG" assert batch["image"][0].size == (640, 480) assert batch["image"][0].mode == "RGB" column = dset["image"] assert len(column) == 1 assert isinstance(column, list) and all(isinstance(item, PIL.Image.Image) for item in column) assert os.path.samefile(column[0].filename, image_path) assert column[0].format == "JPEG" assert column[0].size == (640, 480) assert column[0].mode == "RGB" @require_pil def test_dataset_with_image_feature_from_np_array(): import PIL.Image image_array = np.arange(640 * 480, dtype=np.int32).reshape(480, 640) data = {"image": [image_array]} features = Features({"image": Image()}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"image"} assert isinstance(item["image"], PIL.Image.Image) np.testing.assert_array_equal(np.array(item["image"]), image_array) assert item["image"].filename == "" assert item["image"].format in ["PNG", "TIFF"] assert item["image"].size == (640, 480) batch = dset[:1] assert len(batch) == 1 assert batch.keys() == {"image"} assert isinstance(batch["image"], list) and all(isinstance(item, PIL.Image.Image) for item in batch["image"]) np.testing.assert_array_equal(np.array(batch["image"][0]), image_array) assert batch["image"][0].filename == "" assert batch["image"][0].format in ["PNG", "TIFF"] assert batch["image"][0].size == (640, 480) column = dset["image"] assert len(column) == 1 assert isinstance(column, list) and all(isinstance(item, PIL.Image.Image) for item in column) np.testing.assert_array_equal(np.array(column[0]), image_array) assert column[0].filename == "" assert column[0].format in ["PNG", "TIFF"] assert column[0].size == (640, 480) @require_pil def test_dataset_with_image_feature_tar_jpg(tar_jpg_path): import PIL.Image data = {"image": []} for file_path, file_obj in iter_archive(tar_jpg_path): data["image"].append({"path": file_path, "bytes": file_obj.read()}) break features = Features({"image": Image()}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"image"} assert isinstance(item["image"], PIL.Image.Image) assert item["image"].filename == "" assert item["image"].format == "JPEG" assert item["image"].size == (640, 480) assert item["image"].mode == "RGB" batch = dset[:1] assert len(batch) == 1 assert batch.keys() == {"image"} assert isinstance(batch["image"], list) and all(isinstance(item, PIL.Image.Image) for item in batch["image"]) assert batch["image"][0].filename == "" assert batch["image"][0].format == "JPEG" assert batch["image"][0].size == (640, 480) assert batch["image"][0].mode == "RGB" column = dset["image"] assert len(column) == 1 assert isinstance(column, list) and all(isinstance(item, PIL.Image.Image) for item in column) assert column[0].filename == "" assert column[0].format == "JPEG" assert column[0].size == (640, 480) assert column[0].mode == "RGB" @require_pil def test_dataset_with_image_feature_with_none(): data = {"image": [None]} features = Features({"image": Image()}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"image"} assert item["image"] is None batch = dset[:1] assert len(batch) == 1 assert batch.keys() == {"image"} assert isinstance(batch["image"], list) and all(item is None for item in batch["image"]) column = dset["image"] assert len(column) == 1 assert isinstance(column, list) and all(item is None for item in column) # nested tests data = {"images": [[None]]} features = Features({"images": Sequence(Image())}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"images"} assert all(i is None for i in item["images"]) data = {"nested": [{"image": None}]} features = Features({"nested": {"image": Image()}}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"nested"} assert item["nested"].keys() == {"image"} assert item["nested"]["image"] is None @require_pil @pytest.mark.parametrize( "build_data", [ lambda image_path: {"image": [image_path]}, lambda image_path: {"image": [open(image_path, "rb").read()]}, lambda image_path: {"image": [{"path": image_path}]}, lambda image_path: {"image": [{"path": image_path, "bytes": None}]}, lambda image_path: {"image": [{"path": image_path, "bytes": open(image_path, "rb").read()}]}, lambda image_path: {"image": [{"path": None, "bytes": open(image_path, "rb").read()}]}, lambda image_path: {"image": [{"bytes": open(image_path, "rb").read()}]}, ], ) def test_dataset_cast_to_image_features(shared_datadir, build_data): import PIL.Image image_path = str(shared_datadir / "test_image_rgb.jpg") data = build_data(image_path) dset = Dataset.from_dict(data) item = dset.cast(Features({"image": Image()}))[0] assert item.keys() == {"image"} assert isinstance(item["image"], PIL.Image.Image) item = dset.cast_column("image", Image())[0] assert item.keys() == {"image"} assert isinstance(item["image"], PIL.Image.Image) @require_pil def test_dataset_concatenate_image_features(shared_datadir): # we use a different data structure between 1 and 2 to make sure they are compatible with each other image_path = str(shared_datadir / "test_image_rgb.jpg") data1 = {"image": [image_path]} dset1 = Dataset.from_dict(data1, features=Features({"image": Image()})) data2 = {"image": [{"bytes": open(image_path, "rb").read()}]} dset2 = Dataset.from_dict(data2, features=Features({"image": Image()})) concatenated_dataset = concatenate_datasets([dset1, dset2]) assert len(concatenated_dataset) == len(dset1) + len(dset2) assert concatenated_dataset[0]["image"] == dset1[0]["image"] assert concatenated_dataset[1]["image"] == dset2[0]["image"] @require_pil def test_dataset_concatenate_nested_image_features(shared_datadir): # we use a different data structure between 1 and 2 to make sure they are compatible with each other image_path = str(shared_datadir / "test_image_rgb.jpg") features = Features({"list_of_structs_of_images": [{"image": Image()}]}) data1 = {"list_of_structs_of_images": [[{"image": image_path}]]} dset1 = Dataset.from_dict(data1, features=features) data2 = {"list_of_structs_of_images": [[{"image": {"bytes": open(image_path, "rb").read()}}]]} dset2 = Dataset.from_dict(data2, features=features) concatenated_dataset = concatenate_datasets([dset1, dset2]) assert len(concatenated_dataset) == len(dset1) + len(dset2) assert ( concatenated_dataset[0]["list_of_structs_of_images"][0]["image"] == dset1[0]["list_of_structs_of_images"][0]["image"] ) assert ( concatenated_dataset[1]["list_of_structs_of_images"][0]["image"] == dset2[0]["list_of_structs_of_images"][0]["image"] ) @require_pil def test_dataset_with_image_feature_map(shared_datadir): image_path = str(shared_datadir / "test_image_rgb.jpg") data = {"image": [image_path], "caption": ["cats sleeping"]} features = Features({"image": Image(), "caption": Value("string")}) dset = Dataset.from_dict(data, features=features) for item in dset.cast_column("image", Image(decode=False)): assert item.keys() == {"image", "caption"} assert item == {"image": {"path": image_path, "bytes": None}, "caption": "cats sleeping"} # no decoding def process_caption(example): example["caption"] = "Two " + example["caption"] return example processed_dset = dset.map(process_caption) for item in processed_dset.cast_column("image", Image(decode=False)): assert item.keys() == {"image", "caption"} assert item == {"image": {"path": image_path, "bytes": None}, "caption": "Two cats sleeping"} # decoding example def process_image_by_example(example): example["mode"] = example["image"].mode return example decoded_dset = dset.map(process_image_by_example) for item in decoded_dset.cast_column("image", Image(decode=False)): assert item.keys() == {"image", "caption", "mode"} assert os.path.samefile(item["image"]["path"], image_path) assert item["caption"] == "cats sleeping" assert item["mode"] == "RGB" # decoding batch def process_image_by_batch(batch): batch["mode"] = [image.mode for image in batch["image"]] return batch decoded_dset = dset.map(process_image_by_batch, batched=True) for item in decoded_dset.cast_column("image", Image(decode=False)): assert item.keys() == {"image", "caption", "mode"} assert os.path.samefile(item["image"]["path"], image_path) assert item["caption"] == "cats sleeping" assert item["mode"] == "RGB" @require_pil def test_formatted_dataset_with_image_feature_map(shared_datadir): image_path = str(shared_datadir / "test_image_rgb.jpg") pil_image = Image().decode_example({"path": image_path, "bytes": None}) data = {"image": [image_path], "caption": ["cats sleeping"]} features = Features({"image": Image(), "caption": Value("string")}) dset = Dataset.from_dict(data, features=features) for item in dset.cast_column("image", Image(decode=False)): assert item.keys() == {"image", "caption"} assert item == {"image": {"path": image_path, "bytes": None}, "caption": "cats sleeping"} def process_image_by_example(example): example["num_channels"] = example["image"].shape[-1] return example decoded_dset = dset.with_format("numpy").map(process_image_by_example) for item in decoded_dset.cast_column("image", Image(decode=False)): assert item.keys() == {"image", "caption", "num_channels"} assert item["image"] == encode_np_array(np.array(pil_image)) assert item["caption"] == "cats sleeping" assert item["num_channels"] == 3 def process_image_by_batch(batch): batch["num_channels"] = [image.shape[-1] for image in batch["image"]] return batch decoded_dset = dset.with_format("numpy").map(process_image_by_batch, batched=True) for item in decoded_dset.cast_column("image", Image(decode=False)): assert item.keys() == {"image", "caption", "num_channels"} assert item["image"] == encode_np_array(np.array(pil_image)) assert item["caption"] == "cats sleeping" assert item["num_channels"] == 3 @require_pil def test_dataset_with_image_feature_map_change_image(shared_datadir): import PIL.Image image_path = str(shared_datadir / "test_image_rgb.jpg") pil_image = Image().decode_example({"path": image_path, "bytes": None}) data = {"image": [image_path]} features = Features({"image": Image()}) dset = Dataset.from_dict(data, features=features) for item in dset.cast_column("image", Image(decode=False)): assert item.keys() == {"image"} assert item == { "image": { "bytes": None, "path": image_path, } } # return pil image def process_image_resize_by_example(example): example["image"] = example["image"].resize((100, 100)) return example decoded_dset = dset.map(process_image_resize_by_example) for item in decoded_dset.cast_column("image", Image(decode=False)): assert item.keys() == {"image"} assert item == {"image": {"bytes": image_to_bytes(pil_image.resize((100, 100))), "path": None}} def process_image_resize_by_batch(batch): batch["image"] = [image.resize((100, 100)) for image in batch["image"]] return batch decoded_dset = dset.map(process_image_resize_by_batch, batched=True) for item in decoded_dset.cast_column("image", Image(decode=False)): assert item.keys() == {"image"} assert item == {"image": {"bytes": image_to_bytes(pil_image.resize((100, 100))), "path": None}} # return np.ndarray (e.g. when using albumentations) def process_image_resize_by_example_return_np_array(example): example["image"] = np.array(example["image"].resize((100, 100))) return example decoded_dset = dset.map(process_image_resize_by_example_return_np_array) for item in decoded_dset.cast_column("image", Image(decode=False)): assert item.keys() == {"image"} assert item == { "image": { "bytes": image_to_bytes(PIL.Image.fromarray(np.array(pil_image.resize((100, 100))))), "path": None, } } def process_image_resize_by_batch_return_np_array(batch): batch["image"] = [np.array(image.resize((100, 100))) for image in batch["image"]] return batch decoded_dset = dset.map(process_image_resize_by_batch_return_np_array, batched=True) for item in decoded_dset.cast_column("image", Image(decode=False)): assert item.keys() == {"image"} assert item == { "image": { "bytes": image_to_bytes(PIL.Image.fromarray(np.array(pil_image.resize((100, 100))))), "path": None, } } @require_pil def test_formatted_dataset_with_image_feature(shared_datadir): import PIL.Image image_path = str(shared_datadir / "test_image_rgb.jpg") data = {"image": [image_path, image_path]} features = Features({"image": Image()}) dset = Dataset.from_dict(data, features=features) with dset.formatted_as("numpy"): item = dset[0] assert item.keys() == {"image"} assert isinstance(item["image"], np.ndarray) assert item["image"].shape == (480, 640, 3) batch = dset[:1] assert batch.keys() == {"image"} assert len(batch) == 1 assert isinstance(batch["image"], np.ndarray) assert batch["image"].shape == (1, 480, 640, 3) column = dset["image"] assert len(column) == 2 assert isinstance(column, np.ndarray) assert column.shape == (2, 480, 640, 3) with dset.formatted_as("pandas"): item = dset[0] assert item.shape == (1, 1) assert item.columns == ["image"] assert isinstance(item["image"][0], PIL.Image.Image) assert os.path.samefile(item["image"][0].filename, image_path) assert item["image"][0].format == "JPEG" assert item["image"][0].size == (640, 480) assert item["image"][0].mode == "RGB" batch = dset[:1] assert batch.shape == (1, 1) assert batch.columns == ["image"] assert isinstance(batch["image"], pd.Series) and all( isinstance(item, PIL.Image.Image) for item in batch["image"] ) assert os.path.samefile(batch["image"][0].filename, image_path) assert batch["image"][0].format == "JPEG" assert batch["image"][0].size == (640, 480) assert batch["image"][0].mode == "RGB" column = dset["image"] assert len(column) == 2 assert isinstance(column, pd.Series) and all(isinstance(item, PIL.Image.Image) for item in column) assert os.path.samefile(column[0].filename, image_path) assert column[0].format == "JPEG" assert column[0].size == (640, 480) assert column[0].mode == "RGB" # Currently, the JSONL reader doesn't support complex feature types so we create a temporary dataset script # to test streaming (without uploading the test dataset to the hub). DATASET_LOADING_SCRIPT_NAME = "__dummy_dataset__" DATASET_LOADING_SCRIPT_CODE = """ import os import datasets from datasets import DatasetInfo, Features, Image, Split, SplitGenerator, Value class __DummyDataset__(datasets.GeneratorBasedBuilder): def _info(self) -> DatasetInfo: return DatasetInfo(features=Features({"image": Image(), "caption": Value("string")})) def _split_generators(self, dl_manager): return [ SplitGenerator(Split.TRAIN, gen_kwargs={"filepath": os.path.join(dl_manager.manual_dir, "train.txt")}), ] def _generate_examples(self, filepath, **kwargs): with open(filepath, encoding="utf-8") as f: for i, line in enumerate(f): image_path, caption = line.split(",") yield i, {"image": image_path.strip(), "caption": caption.strip()} """ @pytest.fixture def data_dir(shared_datadir, tmp_path): data_dir = tmp_path / "dummy_dataset_data" data_dir.mkdir() image_path = str(shared_datadir / "test_image_rgb.jpg") with open(data_dir / "train.txt", "w") as f: f.write(f"{image_path},Two cats sleeping\n") return str(data_dir) @pytest.fixture def dataset_loading_script_dir(tmp_path): script_name = DATASET_LOADING_SCRIPT_NAME script_dir = tmp_path / script_name script_dir.mkdir() script_path = script_dir / f"{script_name}.py" with open(script_path, "w") as f: f.write(DATASET_LOADING_SCRIPT_CODE) return str(script_dir) @require_pil @pytest.mark.parametrize("streaming", [False, True]) def test_load_dataset_with_image_feature(shared_datadir, data_dir, dataset_loading_script_dir, streaming): import PIL.Image image_path = str(shared_datadir / "test_image_rgb.jpg") dset = load_dataset(dataset_loading_script_dir, split="train", data_dir=data_dir, streaming=streaming) item = dset[0] if not streaming else next(iter(dset)) assert item.keys() == {"image", "caption"} assert isinstance(item["image"], PIL.Image.Image) assert os.path.samefile(item["image"].filename, image_path) assert item["image"].format == "JPEG" assert item["image"].size == (640, 480) assert item["image"].mode == "RGB" @require_pil def test_dataset_with_image_feature_undecoded(shared_datadir): image_path = str(shared_datadir / "test_image_rgb.jpg") data = {"image": [image_path]} features = Features({"image": Image(decode=False)}) dset = Dataset.from_dict(data, features=features) item = dset[0] assert item.keys() == {"image"} assert item["image"] == {"path": image_path, "bytes": None} batch = dset[:1] assert batch.keys() == {"image"} assert len(batch["image"]) == 1 assert batch["image"][0] == {"path": image_path, "bytes": None} column = dset["image"] assert len(column) == 1 assert column[0] == {"path": image_path, "bytes": None} @require_pil def test_formatted_dataset_with_image_feature_undecoded(shared_datadir): image_path = str(shared_datadir / "test_image_rgb.jpg") data = {"image": [image_path]} features = Features({"image": Image(decode=False)}) dset = Dataset.from_dict(data, features=features) with dset.formatted_as("numpy"): item = dset[0] assert item.keys() == {"image"} assert item["image"] == {"path": image_path, "bytes": None} batch = dset[:1] assert batch.keys() == {"image"} assert len(batch["image"]) == 1 assert batch["image"][0] == {"path": image_path, "bytes": None} column = dset["image"] assert len(column) == 1 assert column[0] == {"path": image_path, "bytes": None} with dset.formatted_as("pandas"): item = dset[0] assert item.shape == (1, 1) assert item.columns == ["image"] assert item["image"][0] == {"path": image_path, "bytes": None} batch = dset[:1] assert batch.shape == (1, 1) assert batch.columns == ["image"] assert batch["image"][0] == {"path": image_path, "bytes": None} column = dset["image"] assert len(column) == 1 assert column[0] == {"path": image_path, "bytes": None} @require_pil def test_dataset_with_image_feature_map_undecoded(shared_datadir): image_path = str(shared_datadir / "test_image_rgb.jpg") data = {"image": [image_path]} features = Features({"image": Image(decode=False)}) dset = Dataset.from_dict(data, features=features) def assert_image_example_undecoded(example): assert example["image"] == {"path": image_path, "bytes": None} dset.map(assert_image_example_undecoded) def assert_image_batch_undecoded(batch): for image in batch["image"]: assert image == {"path": image_path, "bytes": None} dset.map(assert_image_batch_undecoded, batched=True) @require_pil def test_image_embed_storage(shared_datadir): image_path = str(shared_datadir / "test_image_rgb.jpg") example = {"bytes": None, "path": image_path} storage = pa.array([example], type=pa.struct({"bytes": pa.binary(), "path": pa.string()})) embedded_storage = Image().embed_storage(storage) embedded_example = embedded_storage.to_pylist()[0] assert embedded_example == {"bytes": open(image_path, "rb").read(), "path": "test_image_rgb.jpg"} @require_pil @pytest.mark.parametrize( "array, dtype_cast, expected_image_format", [ (np.arange(16).reshape(4, 4).astype(np.uint8), "exact_match", "PNG"), (np.arange(16).reshape(4, 4).astype(np.uint16), "exact_match", "TIFF"), (np.arange(16).reshape(4, 4).astype(np.int64), "downcast->|i4", "TIFF"), (np.arange(16).reshape(2, 2, 4).astype(np.uint8), "exact_match", "PNG"), (np.arange(16).reshape(2, 2, 4), "downcast->|u1", "PNG"), (np.arange(16).reshape(2, 2, 4).astype(np.float64), "error", None), ], ) def test_encode_np_array(array, dtype_cast, expected_image_format): if dtype_cast.startswith("downcast"): _, dest_dtype = dtype_cast.split("->") dest_dtype = np.dtype(dest_dtype) with pytest.warns(UserWarning, match=f"Downcasting array dtype.+{dest_dtype}.+"): encoded_image = Image().encode_example(array) elif dtype_cast == "error": with pytest.raises(TypeError): Image().encode_example(array) return else: # exact_match (no warnings are raised) with warnings.catch_warnings(): warnings.simplefilter("error") encoded_image = Image().encode_example(array) assert isinstance(encoded_image, dict) assert encoded_image.keys() == {"path", "bytes"} assert encoded_image["path"] is None assert encoded_image["bytes"] is not None and isinstance(encoded_image["bytes"], bytes) decoded_image = Image().decode_example(encoded_image) assert decoded_image.format == expected_image_format np.testing.assert_array_equal(np.array(decoded_image), array)
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/fixtures/files.py
import contextlib import csv import json import os import sqlite3 import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config # dataset + arrow_file @pytest.fixture(scope="session") def dataset(): n = 10 features = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string")), "labels": datasets.Sequence(datasets.ClassLabel(names=["negative", "positive"])), "answers": datasets.Sequence( { "text": datasets.Value("string"), "answer_start": datasets.Value("int32"), } ), "id": datasets.Value("int64"), } ) dataset = datasets.Dataset.from_dict( { "tokens": [["foo"] * 5] * n, "labels": [[1] * 5] * n, "answers": [{"answer_start": [97], "text": ["1976"]}] * 10, "id": list(range(n)), }, features=features, ) return dataset @pytest.fixture(scope="session") def arrow_file(tmp_path_factory, dataset): filename = str(tmp_path_factory.mktemp("data") / "file.arrow") dataset.map(cache_file_name=filename) return filename # FILE_CONTENT + files FILE_CONTENT = """\ Text data. Second line of data.""" @pytest.fixture(scope="session") def text_file(tmp_path_factory): filename = tmp_path_factory.mktemp("data") / "file.txt" data = FILE_CONTENT with open(filename, "w") as f: f.write(data) return filename @pytest.fixture(scope="session") def bz2_file(tmp_path_factory): import bz2 path = tmp_path_factory.mktemp("data") / "file.txt.bz2" data = bytes(FILE_CONTENT, "utf-8") with bz2.open(path, "wb") as f: f.write(data) return path @pytest.fixture(scope="session") def gz_file(tmp_path_factory): import gzip path = str(tmp_path_factory.mktemp("data") / "file.txt.gz") data = bytes(FILE_CONTENT, "utf-8") with gzip.open(path, "wb") as f: f.write(data) return path @pytest.fixture(scope="session") def lz4_file(tmp_path_factory): if datasets.config.LZ4_AVAILABLE: import lz4.frame path = tmp_path_factory.mktemp("data") / "file.txt.lz4" data = bytes(FILE_CONTENT, "utf-8") with lz4.frame.open(path, "wb") as f: f.write(data) return path @pytest.fixture(scope="session") def seven_zip_file(tmp_path_factory, text_file): if datasets.config.PY7ZR_AVAILABLE: import py7zr path = tmp_path_factory.mktemp("data") / "file.txt.7z" with py7zr.SevenZipFile(path, "w") as archive: archive.write(text_file, arcname=os.path.basename(text_file)) return path @pytest.fixture(scope="session") def tar_file(tmp_path_factory, text_file): import tarfile path = tmp_path_factory.mktemp("data") / "file.txt.tar" with tarfile.TarFile(path, "w") as f: f.add(text_file, arcname=os.path.basename(text_file)) return path @pytest.fixture(scope="session") def xz_file(tmp_path_factory): import lzma path = tmp_path_factory.mktemp("data") / "file.txt.xz" data = bytes(FILE_CONTENT, "utf-8") with lzma.open(path, "wb") as f: f.write(data) return path @pytest.fixture(scope="session") def zip_file(tmp_path_factory, text_file): import zipfile path = tmp_path_factory.mktemp("data") / "file.txt.zip" with zipfile.ZipFile(path, "w") as f: f.write(text_file, arcname=os.path.basename(text_file)) return path @pytest.fixture(scope="session") def zstd_file(tmp_path_factory): if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd path = tmp_path_factory.mktemp("data") / "file.txt.zst" data = bytes(FILE_CONTENT, "utf-8") with zstd.open(path, "wb") as f: f.write(data) return path # xml_file @pytest.fixture(scope="session") def xml_file(tmp_path_factory): filename = tmp_path_factory.mktemp("data") / "file.xml" data = textwrap.dedent( """\ <?xml version="1.0" encoding="UTF-8" ?> <tmx version="1.4"> <header segtype="sentence" srclang="ca" /> <body> <tu> <tuv xml:lang="ca"><seg>Contingut 1</seg></tuv> <tuv xml:lang="en"><seg>Content 1</seg></tuv> </tu> <tu> <tuv xml:lang="ca"><seg>Contingut 2</seg></tuv> <tuv xml:lang="en"><seg>Content 2</seg></tuv> </tu> <tu> <tuv xml:lang="ca"><seg>Contingut 3</seg></tuv> <tuv xml:lang="en"><seg>Content 3</seg></tuv> </tu> <tu> <tuv xml:lang="ca"><seg>Contingut 4</seg></tuv> <tuv xml:lang="en"><seg>Content 4</seg></tuv> </tu> <tu> <tuv xml:lang="ca"><seg>Contingut 5</seg></tuv> <tuv xml:lang="en"><seg>Content 5</seg></tuv> </tu> </body> </tmx>""" ) with open(filename, "w") as f: f.write(data) return filename DATA = [ {"col_1": "0", "col_2": 0, "col_3": 0.0}, {"col_1": "1", "col_2": 1, "col_3": 1.0}, {"col_1": "2", "col_2": 2, "col_3": 2.0}, {"col_1": "3", "col_2": 3, "col_3": 3.0}, ] DATA2 = [ {"col_1": "4", "col_2": 4, "col_3": 4.0}, {"col_1": "5", "col_2": 5, "col_3": 5.0}, ] DATA_DICT_OF_LISTS = { "col_1": ["0", "1", "2", "3"], "col_2": [0, 1, 2, 3], "col_3": [0.0, 1.0, 2.0, 3.0], } DATA_312 = [ {"col_3": 0.0, "col_1": "0", "col_2": 0}, {"col_3": 1.0, "col_1": "1", "col_2": 1}, ] DATA_STR = [ {"col_1": "s0", "col_2": 0, "col_3": 0.0}, {"col_1": "s1", "col_2": 1, "col_3": 1.0}, {"col_1": "s2", "col_2": 2, "col_3": 2.0}, {"col_1": "s3", "col_2": 3, "col_3": 3.0}, ] @pytest.fixture(scope="session") def dataset_dict(): return DATA_DICT_OF_LISTS @pytest.fixture(scope="session") def arrow_path(tmp_path_factory): dataset = datasets.Dataset.from_dict(DATA_DICT_OF_LISTS) path = str(tmp_path_factory.mktemp("data") / "dataset.arrow") dataset.map(cache_file_name=path) return path @pytest.fixture(scope="session") def sqlite_path(tmp_path_factory): path = str(tmp_path_factory.mktemp("data") / "dataset.sqlite") with contextlib.closing(sqlite3.connect(path)) as con: cur = con.cursor() cur.execute("CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)") for item in DATA: cur.execute("INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)", tuple(item.values())) con.commit() return path @pytest.fixture(scope="session") def csv_path(tmp_path_factory): path = str(tmp_path_factory.mktemp("data") / "dataset.csv") with open(path, "w", newline="") as f: writer = csv.DictWriter(f, fieldnames=["col_1", "col_2", "col_3"]) writer.writeheader() for item in DATA: writer.writerow(item) return path @pytest.fixture(scope="session") def csv2_path(tmp_path_factory): path = str(tmp_path_factory.mktemp("data") / "dataset2.csv") with open(path, "w", newline="") as f: writer = csv.DictWriter(f, fieldnames=["col_1", "col_2", "col_3"]) writer.writeheader() for item in DATA: writer.writerow(item) return path @pytest.fixture(scope="session") def bz2_csv_path(csv_path, tmp_path_factory): import bz2 path = tmp_path_factory.mktemp("data") / "dataset.csv.bz2" with open(csv_path, "rb") as f: data = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bz2.open(path, "wb") as f: f.write(data) return path @pytest.fixture(scope="session") def zip_csv_path(csv_path, csv2_path, tmp_path_factory): path = tmp_path_factory.mktemp("data") / "dataset.csv.zip" with zipfile.ZipFile(path, "w") as f: f.write(csv_path, arcname=os.path.basename(csv_path)) f.write(csv2_path, arcname=os.path.basename(csv2_path)) return path @pytest.fixture(scope="session") def zip_uppercase_csv_path(csv_path, csv2_path, tmp_path_factory): path = tmp_path_factory.mktemp("data") / "dataset.csv.zip" with zipfile.ZipFile(path, "w") as f: f.write(csv_path, arcname=os.path.basename(csv_path.replace(".csv", ".CSV"))) f.write(csv2_path, arcname=os.path.basename(csv2_path.replace(".csv", ".CSV"))) return path @pytest.fixture(scope="session") def zip_csv_with_dir_path(csv_path, csv2_path, tmp_path_factory): path = tmp_path_factory.mktemp("data") / "dataset_with_dir.csv.zip" with zipfile.ZipFile(path, "w") as f: f.write(csv_path, arcname=os.path.join("main_dir", os.path.basename(csv_path))) f.write(csv2_path, arcname=os.path.join("main_dir", os.path.basename(csv2_path))) return path @pytest.fixture(scope="session") def parquet_path(tmp_path_factory): path = str(tmp_path_factory.mktemp("data") / "dataset.parquet") schema = pa.schema( { "col_1": pa.string(), "col_2": pa.int64(), "col_3": pa.float64(), } ) with open(path, "wb") as f: writer = pq.ParquetWriter(f, schema=schema) pa_table = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(DATA))] for k in DATA[0]}, schema=schema) writer.write_table(pa_table) writer.close() return path @pytest.fixture(scope="session") def json_list_of_dicts_path(tmp_path_factory): path = str(tmp_path_factory.mktemp("data") / "dataset.json") data = {"data": DATA} with open(path, "w") as f: json.dump(data, f) return path @pytest.fixture(scope="session") def json_dict_of_lists_path(tmp_path_factory): path = str(tmp_path_factory.mktemp("data") / "dataset.json") data = {"data": DATA_DICT_OF_LISTS} with open(path, "w") as f: json.dump(data, f) return path @pytest.fixture(scope="session") def jsonl_path(tmp_path_factory): path = str(tmp_path_factory.mktemp("data") / "dataset.jsonl") with open(path, "w") as f: for item in DATA: f.write(json.dumps(item) + "\n") return path @pytest.fixture(scope="session") def jsonl2_path(tmp_path_factory): path = str(tmp_path_factory.mktemp("data") / "dataset2.jsonl") with open(path, "w") as f: for item in DATA: f.write(json.dumps(item) + "\n") return path @pytest.fixture(scope="session") def jsonl_312_path(tmp_path_factory): path = str(tmp_path_factory.mktemp("data") / "dataset_312.jsonl") with open(path, "w") as f: for item in DATA_312: f.write(json.dumps(item) + "\n") return path @pytest.fixture(scope="session") def jsonl_str_path(tmp_path_factory): path = str(tmp_path_factory.mktemp("data") / "dataset-str.jsonl") with open(path, "w") as f: for item in DATA_STR: f.write(json.dumps(item) + "\n") return path @pytest.fixture(scope="session") def text_gz_path(tmp_path_factory, text_path): import gzip path = str(tmp_path_factory.mktemp("data") / "dataset.txt.gz") with open(text_path, "rb") as orig_file: with gzip.open(path, "wb") as zipped_file: zipped_file.writelines(orig_file) return path @pytest.fixture(scope="session") def jsonl_gz_path(tmp_path_factory, jsonl_path): import gzip path = str(tmp_path_factory.mktemp("data") / "dataset.jsonl.gz") with open(jsonl_path, "rb") as orig_file: with gzip.open(path, "wb") as zipped_file: zipped_file.writelines(orig_file) return path @pytest.fixture(scope="session") def zip_jsonl_path(jsonl_path, jsonl2_path, tmp_path_factory): path = tmp_path_factory.mktemp("data") / "dataset.jsonl.zip" with zipfile.ZipFile(path, "w") as f: f.write(jsonl_path, arcname=os.path.basename(jsonl_path)) f.write(jsonl2_path, arcname=os.path.basename(jsonl2_path)) return path @pytest.fixture(scope="session") def zip_nested_jsonl_path(zip_jsonl_path, jsonl_path, jsonl2_path, tmp_path_factory): path = tmp_path_factory.mktemp("data") / "dataset_nested.jsonl.zip" with zipfile.ZipFile(path, "w") as f: f.write(zip_jsonl_path, arcname=os.path.join("nested", os.path.basename(zip_jsonl_path))) return path @pytest.fixture(scope="session") def zip_jsonl_with_dir_path(jsonl_path, jsonl2_path, tmp_path_factory): path = tmp_path_factory.mktemp("data") / "dataset_with_dir.jsonl.zip" with zipfile.ZipFile(path, "w") as f: f.write(jsonl_path, arcname=os.path.join("main_dir", os.path.basename(jsonl_path))) f.write(jsonl2_path, arcname=os.path.join("main_dir", os.path.basename(jsonl2_path))) return path @pytest.fixture(scope="session") def tar_jsonl_path(jsonl_path, jsonl2_path, tmp_path_factory): path = tmp_path_factory.mktemp("data") / "dataset.jsonl.tar" with tarfile.TarFile(path, "w") as f: f.add(jsonl_path, arcname=os.path.basename(jsonl_path)) f.add(jsonl2_path, arcname=os.path.basename(jsonl2_path)) return path @pytest.fixture(scope="session") def tar_nested_jsonl_path(tar_jsonl_path, jsonl_path, jsonl2_path, tmp_path_factory): path = tmp_path_factory.mktemp("data") / "dataset_nested.jsonl.tar" with tarfile.TarFile(path, "w") as f: f.add(tar_jsonl_path, arcname=os.path.join("nested", os.path.basename(tar_jsonl_path))) return path @pytest.fixture(scope="session") def text_path(tmp_path_factory): data = ["0", "1", "2", "3"] path = str(tmp_path_factory.mktemp("data") / "dataset.txt") with open(path, "w") as f: for item in data: f.write(item + "\n") return path @pytest.fixture(scope="session") def text2_path(tmp_path_factory): data = ["0", "1", "2", "3"] path = str(tmp_path_factory.mktemp("data") / "dataset2.txt") with open(path, "w") as f: for item in data: f.write(item + "\n") return path @pytest.fixture(scope="session") def text_dir_with_unsupported_extension(tmp_path_factory): data = ["0", "1", "2", "3"] path = tmp_path_factory.mktemp("data") / "dataset.abc" with open(path, "w") as f: for item in data: f.write(item + "\n") return path @pytest.fixture(scope="session") def zip_text_path(text_path, text2_path, tmp_path_factory): path = tmp_path_factory.mktemp("data") / "dataset.text.zip" with zipfile.ZipFile(path, "w") as f: f.write(text_path, arcname=os.path.basename(text_path)) f.write(text2_path, arcname=os.path.basename(text2_path)) return path @pytest.fixture(scope="session") def zip_text_with_dir_path(text_path, text2_path, tmp_path_factory): path = tmp_path_factory.mktemp("data") / "dataset_with_dir.text.zip" with zipfile.ZipFile(path, "w") as f: f.write(text_path, arcname=os.path.join("main_dir", os.path.basename(text_path))) f.write(text2_path, arcname=os.path.join("main_dir", os.path.basename(text2_path))) return path @pytest.fixture(scope="session") def zip_unsupported_ext_path(text_path, text2_path, tmp_path_factory): path = tmp_path_factory.mktemp("data") / "dataset.ext.zip" with zipfile.ZipFile(path, "w") as f: f.write(text_path, arcname=os.path.basename("unsupported.ext")) f.write(text2_path, arcname=os.path.basename("unsupported_2.ext")) return path @pytest.fixture(scope="session") def text_path_with_unicode_new_lines(tmp_path_factory): text = "\n".join(["First", "Second\u2029with Unicode new line", "Third"]) path = str(tmp_path_factory.mktemp("data") / "dataset_with_unicode_new_lines.txt") with open(path, "w", encoding="utf-8") as f: f.write(text) return path @pytest.fixture(scope="session") def image_file(): return os.path.join("tests", "features", "data", "test_image_rgb.jpg") @pytest.fixture(scope="session") def audio_file(): return os.path.join("tests", "features", "data", "test_audio_44100.wav") @pytest.fixture(scope="session") def zip_image_path(image_file, tmp_path_factory): path = tmp_path_factory.mktemp("data") / "dataset.img.zip" with zipfile.ZipFile(path, "w") as f: f.write(image_file, arcname=os.path.basename(image_file)) f.write(image_file, arcname=os.path.basename(image_file).replace(".jpg", "2.jpg")) return path @pytest.fixture(scope="session") def data_dir_with_hidden_files(tmp_path_factory): data_dir = tmp_path_factory.mktemp("data_dir") (data_dir / "subdir").mkdir() with open(data_dir / "subdir" / "train.txt", "w") as f: f.write("foo\n" * 10) with open(data_dir / "subdir" / "test.txt", "w") as f: f.write("bar\n" * 10) # hidden file with open(data_dir / "subdir" / ".test.txt", "w") as f: f.write("bar\n" * 10) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / ".subdir" / "train.txt", "w") as f: f.write("foo\n" * 10) with open(data_dir / ".subdir" / "test.txt", "w") as f: f.write("bar\n" * 10) return data_dir
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/fixtures/fsspec.py
import posixpath from pathlib import Path from unittest.mock import patch import pytest from fsspec.implementations.local import AbstractFileSystem, LocalFileSystem, stringify_path from fsspec.registry import _registry as _fsspec_registry class MockFileSystem(AbstractFileSystem): protocol = "mock" def __init__(self, *args, local_root_dir, **kwargs): super().__init__() self._fs = LocalFileSystem(*args, **kwargs) self.local_root_dir = Path(local_root_dir).resolve().as_posix() + "/" def mkdir(self, path, *args, **kwargs): path = posixpath.join(self.local_root_dir, self._strip_protocol(path)) return self._fs.mkdir(path, *args, **kwargs) def makedirs(self, path, *args, **kwargs): path = posixpath.join(self.local_root_dir, self._strip_protocol(path)) return self._fs.makedirs(path, *args, **kwargs) def rmdir(self, path): path = posixpath.join(self.local_root_dir, self._strip_protocol(path)) return self._fs.rmdir(path) def ls(self, path, detail=True, *args, **kwargs): path = posixpath.join(self.local_root_dir, self._strip_protocol(path)) out = self._fs.ls(path, detail=detail, *args, **kwargs) if detail: return [{**info, "name": info["name"][len(self.local_root_dir) :]} for info in out] else: return [name[len(self.local_root_dir) :] for name in out] def info(self, path, *args, **kwargs): path = posixpath.join(self.local_root_dir, self._strip_protocol(path)) out = dict(self._fs.info(path, *args, **kwargs)) out["name"] = out["name"][len(self.local_root_dir) :] return out def cp_file(self, path1, path2, *args, **kwargs): path1 = posixpath.join(self.local_root_dir, self._strip_protocol(path1)) path2 = posixpath.join(self.local_root_dir, self._strip_protocol(path2)) return self._fs.cp_file(path1, path2, *args, **kwargs) def rm_file(self, path, *args, **kwargs): path = posixpath.join(self.local_root_dir, self._strip_protocol(path)) return self._fs.rm_file(path, *args, **kwargs) def rm(self, path, *args, **kwargs): path = posixpath.join(self.local_root_dir, self._strip_protocol(path)) return self._fs.rm(path, *args, **kwargs) def _open(self, path, *args, **kwargs): path = posixpath.join(self.local_root_dir, self._strip_protocol(path)) return self._fs._open(path, *args, **kwargs) def created(self, path): path = posixpath.join(self.local_root_dir, self._strip_protocol(path)) return self._fs.created(path) def modified(self, path): path = posixpath.join(self.local_root_dir, self._strip_protocol(path)) return self._fs.modified(path) @classmethod def _strip_protocol(cls, path): path = stringify_path(path) if path.startswith("mock://"): path = path[7:] return path class TmpDirFileSystem(MockFileSystem): protocol = "tmp" tmp_dir = None def __init__(self, *args, **kwargs): assert self.tmp_dir is not None, "TmpDirFileSystem.tmp_dir is not set" super().__init__(*args, **kwargs, local_root_dir=self.tmp_dir, auto_mkdir=True) @classmethod def _strip_protocol(cls, path): path = stringify_path(path) if path.startswith("tmp://"): path = path[6:] return path @pytest.fixture def mock_fsspec(): _fsspec_registry["mock"] = MockFileSystem _fsspec_registry["tmp"] = TmpDirFileSystem yield del _fsspec_registry["mock"] del _fsspec_registry["tmp"] @pytest.fixture def mockfs(tmp_path_factory, mock_fsspec): local_fs_dir = tmp_path_factory.mktemp("mockfs") return MockFileSystem(local_root_dir=local_fs_dir, auto_mkdir=True) @pytest.fixture def tmpfs(tmp_path_factory, mock_fsspec): tmp_fs_dir = tmp_path_factory.mktemp("tmpfs") with patch.object(TmpDirFileSystem, "tmp_dir", tmp_fs_dir): yield TmpDirFileSystem() TmpDirFileSystem.clear_instance_cache()
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/fixtures/hub.py
import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder CI_HUB_USER = "__DUMMY_TRANSFORMERS_USER__" CI_HUB_USER_FULL_NAME = "Dummy User" CI_HUB_USER_TOKEN = "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" CI_HUB_ENDPOINT = "https://hub-ci.huggingface.co" CI_HUB_DATASETS_URL = CI_HUB_ENDPOINT + "/datasets/{repo_id}/resolve/{revision}/{path}" CI_HFH_HUGGINGFACE_CO_URL_TEMPLATE = CI_HUB_ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}" CI_HUB_TOKEN_PATH = Path("~/.huggingface/hub_ci_token").expanduser() @pytest.fixture def ci_hfh_hf_hub_url(monkeypatch): monkeypatch.setattr( "huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE", CI_HFH_HUGGINGFACE_CO_URL_TEMPLATE ) @pytest.fixture def ci_hub_config(monkeypatch): monkeypatch.setattr("datasets.config.HF_ENDPOINT", CI_HUB_ENDPOINT) monkeypatch.setattr("datasets.config.HUB_DATASETS_URL", CI_HUB_DATASETS_URL) @pytest.fixture def ci_hub_token_path(monkeypatch): monkeypatch.setattr("huggingface_hub.hf_api.HfFolder.path_token", CI_HUB_TOKEN_PATH) @pytest.fixture def set_ci_hub_access_token(ci_hub_config, ci_hub_token_path): HfFolder.save_token(CI_HUB_USER_TOKEN) yield HfFolder.delete_token() @pytest.fixture(scope="session") def hf_api(): return HfApi(endpoint=CI_HUB_ENDPOINT) @pytest.fixture(scope="session") def hf_token(): yield CI_HUB_USER_TOKEN @pytest.fixture def cleanup_repo(hf_api): def _cleanup_repo(repo_id): hf_api.delete_repo(repo_id, token=CI_HUB_USER_TOKEN, repo_type="dataset") return _cleanup_repo @pytest.fixture def temporary_repo(cleanup_repo): @contextmanager def _temporary_repo(repo_id): try: yield repo_id finally: cleanup_repo(repo_id) return _temporary_repo @pytest.fixture(scope="session") def hf_private_dataset_repo_txt_data_(hf_api: HfApi, hf_token, text_file): repo_name = f"repo_txt_data-{int(time.time() * 10e3)}" repo_id = f"{CI_HUB_USER}/{repo_name}" hf_api.create_repo(repo_id, token=hf_token, repo_type="dataset", private=True) hf_api.upload_file( token=hf_token, path_or_fileobj=str(text_file), path_in_repo="data/text_data.txt", repo_id=repo_id, repo_type="dataset", ) yield repo_id try: hf_api.delete_repo(repo_id, token=hf_token, repo_type="dataset") except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def hf_private_dataset_repo_txt_data(hf_private_dataset_repo_txt_data_, ci_hub_config, ci_hfh_hf_hub_url): return hf_private_dataset_repo_txt_data_ @pytest.fixture(scope="session") def hf_private_dataset_repo_zipped_txt_data_(hf_api: HfApi, hf_token, zip_csv_with_dir_path): repo_name = f"repo_zipped_txt_data-{int(time.time() * 10e3)}" repo_id = f"{CI_HUB_USER}/{repo_name}" hf_api.create_repo(repo_id, token=hf_token, repo_type="dataset", private=True) hf_api.upload_file( token=hf_token, path_or_fileobj=str(zip_csv_with_dir_path), path_in_repo="data.zip", repo_id=repo_id, repo_type="dataset", ) yield repo_id try: hf_api.delete_repo(repo_id, token=hf_token, repo_type="dataset") except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def hf_private_dataset_repo_zipped_txt_data( hf_private_dataset_repo_zipped_txt_data_, ci_hub_config, ci_hfh_hf_hub_url ): return hf_private_dataset_repo_zipped_txt_data_ @pytest.fixture(scope="session") def hf_private_dataset_repo_zipped_img_data_(hf_api: HfApi, hf_token, zip_image_path): repo_name = f"repo_zipped_img_data-{int(time.time() * 10e3)}" repo_id = f"{CI_HUB_USER}/{repo_name}" hf_api.create_repo(repo_id, token=hf_token, repo_type="dataset", private=True) hf_api.upload_file( token=hf_token, path_or_fileobj=str(zip_image_path), path_in_repo="data.zip", repo_id=repo_id, repo_type="dataset", ) yield repo_id try: hf_api.delete_repo(repo_id, token=hf_token, repo_type="dataset") except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def hf_private_dataset_repo_zipped_img_data( hf_private_dataset_repo_zipped_img_data_, ci_hub_config, ci_hfh_hf_hub_url ): return hf_private_dataset_repo_zipped_img_data_
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/io/test_csv.py
import csv import os import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.csv import CsvDatasetReader, CsvDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def _check_csv_dataset(dataset, expected_features): assert isinstance(dataset, Dataset) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_dataset_from_csv_keep_in_memory(keep_in_memory, csv_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "int64", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = CsvDatasetReader(csv_path, cache_dir=cache_dir, keep_in_memory=keep_in_memory).read() _check_csv_dataset(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ], ) def test_dataset_from_csv_features(features, csv_path, tmp_path): cache_dir = tmp_path / "cache" # CSV file loses col_1 string dtype information: default now is "int64" instead of "string" default_expected_features = {"col_1": "int64", "col_2": "int64", "col_3": "float64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = CsvDatasetReader(csv_path, features=features, cache_dir=cache_dir).read() _check_csv_dataset(dataset, expected_features) @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_dataset_from_csv_split(split, csv_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "int64", "col_2": "int64", "col_3": "float64"} dataset = CsvDatasetReader(csv_path, cache_dir=cache_dir, split=split).read() _check_csv_dataset(dataset, expected_features) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type", [str, list]) def test_dataset_from_csv_path_type(path_type, csv_path, tmp_path): if issubclass(path_type, str): path = csv_path elif issubclass(path_type, list): path = [csv_path] cache_dir = tmp_path / "cache" expected_features = {"col_1": "int64", "col_2": "int64", "col_3": "float64"} dataset = CsvDatasetReader(path, cache_dir=cache_dir).read() _check_csv_dataset(dataset, expected_features) def _check_csv_datasetdict(dataset_dict, expected_features, splits=("train",)): assert isinstance(dataset_dict, DatasetDict) for split in splits: dataset = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_csv_datasetdict_reader_keep_in_memory(keep_in_memory, csv_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "int64", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = CsvDatasetReader({"train": csv_path}, cache_dir=cache_dir, keep_in_memory=keep_in_memory).read() _check_csv_datasetdict(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ], ) def test_csv_datasetdict_reader_features(features, csv_path, tmp_path): cache_dir = tmp_path / "cache" # CSV file loses col_1 string dtype information: default now is "int64" instead of "string" default_expected_features = {"col_1": "int64", "col_2": "int64", "col_3": "float64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = CsvDatasetReader({"train": csv_path}, features=features, cache_dir=cache_dir).read() _check_csv_datasetdict(dataset, expected_features) @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_csv_datasetdict_reader_split(split, csv_path, tmp_path): if split: path = {split: csv_path} else: path = {"train": csv_path, "test": csv_path} cache_dir = tmp_path / "cache" expected_features = {"col_1": "int64", "col_2": "int64", "col_3": "float64"} dataset = CsvDatasetReader(path, cache_dir=cache_dir).read() _check_csv_datasetdict(dataset, expected_features, splits=list(path.keys())) assert all(dataset[split].split == split for split in path.keys()) def iter_csv_file(csv_path): with open(csv_path, encoding="utf-8") as csvfile: yield from csv.reader(csvfile) def test_dataset_to_csv(csv_path, tmp_path): cache_dir = tmp_path / "cache" output_csv = os.path.join(cache_dir, "tmp.csv") dataset = CsvDatasetReader({"train": csv_path}, cache_dir=cache_dir).read() CsvDatasetWriter(dataset["train"], output_csv, num_proc=1).write() original_csv = iter_csv_file(csv_path) expected_csv = iter_csv_file(output_csv) for row1, row2 in zip(original_csv, expected_csv): assert row1 == row2 def test_dataset_to_csv_multiproc(csv_path, tmp_path): cache_dir = tmp_path / "cache" output_csv = os.path.join(cache_dir, "tmp.csv") dataset = CsvDatasetReader({"train": csv_path}, cache_dir=cache_dir).read() CsvDatasetWriter(dataset["train"], output_csv, num_proc=2).write() original_csv = iter_csv_file(csv_path) expected_csv = iter_csv_file(output_csv) for row1, row2 in zip(original_csv, expected_csv): assert row1 == row2 def test_dataset_to_csv_invalidproc(csv_path, tmp_path): cache_dir = tmp_path / "cache" output_csv = os.path.join(cache_dir, "tmp.csv") dataset = CsvDatasetReader({"train": csv_path}, cache_dir=cache_dir).read() with pytest.raises(ValueError): CsvDatasetWriter(dataset["train"], output_csv, num_proc=0)
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/io/test_json.py
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def _check_json_dataset(dataset, expected_features): assert isinstance(dataset, Dataset) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_dataset_from_json_keep_in_memory(keep_in_memory, jsonl_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = JsonDatasetReader(jsonl_path, cache_dir=cache_dir, keep_in_memory=keep_in_memory).read() _check_json_dataset(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ], ) def test_dataset_from_json_features(features, jsonl_path, tmp_path): cache_dir = tmp_path / "cache" default_expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = JsonDatasetReader(jsonl_path, features=features, cache_dir=cache_dir).read() _check_json_dataset(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"col_3": "float64", "col_1": "string", "col_2": "int64"}, ], ) def test_dataset_from_json_with_unsorted_column_names(features, jsonl_312_path, tmp_path): cache_dir = tmp_path / "cache" default_expected_features = {"col_3": "float64", "col_1": "string", "col_2": "int64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = JsonDatasetReader(jsonl_312_path, features=features, cache_dir=cache_dir).read() assert isinstance(dataset, Dataset) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def test_dataset_from_json_with_mismatched_features(jsonl_312_path, tmp_path): # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} features = {"col_2": "int64", "col_3": "float64", "col_1": "string"} expected_features = features.copy() features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) cache_dir = tmp_path / "cache" dataset = JsonDatasetReader(jsonl_312_path, features=features, cache_dir=cache_dir).read() assert isinstance(dataset, Dataset) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_dataset_from_json_split(split, jsonl_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} dataset = JsonDatasetReader(jsonl_path, cache_dir=cache_dir, split=split).read() _check_json_dataset(dataset, expected_features) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type", [str, list]) def test_dataset_from_json_path_type(path_type, jsonl_path, tmp_path): if issubclass(path_type, str): path = jsonl_path elif issubclass(path_type, list): path = [jsonl_path] cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} dataset = JsonDatasetReader(path, cache_dir=cache_dir).read() _check_json_dataset(dataset, expected_features) def _check_json_datasetdict(dataset_dict, expected_features, splits=("train",)): assert isinstance(dataset_dict, DatasetDict) for split in splits: dataset = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_datasetdict_from_json_keep_in_memory(keep_in_memory, jsonl_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = JsonDatasetReader({"train": jsonl_path}, cache_dir=cache_dir, keep_in_memory=keep_in_memory).read() _check_json_datasetdict(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ], ) def test_datasetdict_from_json_features(features, jsonl_path, tmp_path): cache_dir = tmp_path / "cache" default_expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = JsonDatasetReader({"train": jsonl_path}, features=features, cache_dir=cache_dir).read() _check_json_datasetdict(dataset, expected_features) @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_datasetdict_from_json_splits(split, jsonl_path, tmp_path): if split: path = {split: jsonl_path} else: split = "train" path = {"train": jsonl_path, "test": jsonl_path} cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} dataset = JsonDatasetReader(path, cache_dir=cache_dir).read() _check_json_datasetdict(dataset, expected_features, splits=list(path.keys())) assert all(dataset[split].split == split for split in path.keys()) def load_json(buffer): return json.load(buffer) def load_json_lines(buffer): return [json.loads(line) for line in buffer] class TestJsonDatasetWriter: @pytest.mark.parametrize("lines, load_json_function", [(True, load_json_lines), (False, load_json)]) def test_dataset_to_json_lines(self, lines, load_json_function, dataset): with io.BytesIO() as buffer: JsonDatasetWriter(dataset, buffer, lines=lines).write() buffer.seek(0) exported_content = load_json_function(buffer) assert isinstance(exported_content, list) assert isinstance(exported_content[0], dict) assert len(exported_content) == 10 @pytest.mark.parametrize( "orient, container, keys, len_at", [ ("records", list, {"tokens", "labels", "answers", "id"}, None), ("split", dict, {"columns", "data"}, "data"), ("index", dict, set("0123456789"), None), ("columns", dict, {"tokens", "labels", "answers", "id"}, "tokens"), ("values", list, None, None), ("table", dict, {"schema", "data"}, "data"), ], ) def test_dataset_to_json_orient(self, orient, container, keys, len_at, dataset): with io.BytesIO() as buffer: JsonDatasetWriter(dataset, buffer, lines=False, orient=orient).write() buffer.seek(0) exported_content = load_json(buffer) assert isinstance(exported_content, container) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(exported_content, "keys") and not hasattr(exported_content[0], "keys") if len_at: assert len(exported_content[len_at]) == 10 else: assert len(exported_content) == 10 @pytest.mark.parametrize("lines, load_json_function", [(True, load_json_lines), (False, load_json)]) def test_dataset_to_json_lines_multiproc(self, lines, load_json_function, dataset): with io.BytesIO() as buffer: JsonDatasetWriter(dataset, buffer, lines=lines, num_proc=2).write() buffer.seek(0) exported_content = load_json_function(buffer) assert isinstance(exported_content, list) assert isinstance(exported_content[0], dict) assert len(exported_content) == 10 @pytest.mark.parametrize( "orient, container, keys, len_at", [ ("records", list, {"tokens", "labels", "answers", "id"}, None), ("split", dict, {"columns", "data"}, "data"), ("index", dict, set("0123456789"), None), ("columns", dict, {"tokens", "labels", "answers", "id"}, "tokens"), ("values", list, None, None), ("table", dict, {"schema", "data"}, "data"), ], ) def test_dataset_to_json_orient_multiproc(self, orient, container, keys, len_at, dataset): with io.BytesIO() as buffer: JsonDatasetWriter(dataset, buffer, lines=False, orient=orient, num_proc=2).write() buffer.seek(0) exported_content = load_json(buffer) assert isinstance(exported_content, container) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(exported_content, "keys") and not hasattr(exported_content[0], "keys") if len_at: assert len(exported_content[len_at]) == 10 else: assert len(exported_content) == 10 def test_dataset_to_json_orient_invalidproc(self, dataset): with pytest.raises(ValueError): with io.BytesIO() as buffer: JsonDatasetWriter(dataset, buffer, num_proc=0) @pytest.mark.parametrize("compression, extension", [("gzip", "gz"), ("bz2", "bz2"), ("xz", "xz")]) def test_dataset_to_json_compression(self, shared_datadir, tmp_path_factory, extension, compression, dataset): path = tmp_path_factory.mktemp("data") / f"test.json.{extension}" original_path = str(shared_datadir / f"test_file.json.{extension}") JsonDatasetWriter(dataset, path, compression=compression).write() with fsspec.open(path, "rb", compression="infer") as f: exported_content = f.read() with fsspec.open(original_path, "rb", compression="infer") as f: original_content = f.read() assert exported_content == original_content
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/io/test_parquet.py
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def _check_parquet_dataset(dataset, expected_features): assert isinstance(dataset, Dataset) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_dataset_from_parquet_keep_in_memory(keep_in_memory, parquet_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = ParquetDatasetReader(parquet_path, cache_dir=cache_dir, keep_in_memory=keep_in_memory).read() _check_parquet_dataset(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ], ) def test_dataset_from_parquet_features(features, parquet_path, tmp_path): cache_dir = tmp_path / "cache" default_expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = ParquetDatasetReader(parquet_path, features=features, cache_dir=cache_dir).read() _check_parquet_dataset(dataset, expected_features) @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_dataset_from_parquet_split(split, parquet_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} dataset = ParquetDatasetReader(parquet_path, cache_dir=cache_dir, split=split).read() _check_parquet_dataset(dataset, expected_features) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type", [str, list]) def test_dataset_from_parquet_path_type(path_type, parquet_path, tmp_path): if issubclass(path_type, str): path = parquet_path elif issubclass(path_type, list): path = [parquet_path] cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} dataset = ParquetDatasetReader(path, cache_dir=cache_dir).read() _check_parquet_dataset(dataset, expected_features) def _check_parquet_datasetdict(dataset_dict, expected_features, splits=("train",)): assert isinstance(dataset_dict, DatasetDict) for split in splits: dataset = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_parquet_datasetdict_reader_keep_in_memory(keep_in_memory, parquet_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = ParquetDatasetReader( {"train": parquet_path}, cache_dir=cache_dir, keep_in_memory=keep_in_memory ).read() _check_parquet_datasetdict(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ], ) def test_parquet_datasetdict_reader_features(features, parquet_path, tmp_path): cache_dir = tmp_path / "cache" default_expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = ParquetDatasetReader({"train": parquet_path}, features=features, cache_dir=cache_dir).read() _check_parquet_datasetdict(dataset, expected_features) @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_parquet_datasetdict_reader_split(split, parquet_path, tmp_path): if split: path = {split: parquet_path} else: split = "train" path = {"train": parquet_path, "test": parquet_path} cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} dataset = ParquetDatasetReader(path, cache_dir=cache_dir).read() _check_parquet_datasetdict(dataset, expected_features, splits=list(path.keys())) assert all(dataset[split].split == split for split in path.keys()) def test_parquet_write(dataset, tmp_path): writer = ParquetDatasetWriter(dataset, tmp_path / "foo.parquet") assert writer.write() > 0 pf = pq.ParquetFile(tmp_path / "foo.parquet") output_table = pf.read() assert dataset.data.table == output_table def test_dataset_to_parquet_keeps_features(shared_datadir, tmp_path): image_path = str(shared_datadir / "test_image_rgb.jpg") data = {"image": [image_path]} features = Features({"image": Image()}) dataset = Dataset.from_dict(data, features=features) writer = ParquetDatasetWriter(dataset, tmp_path / "foo.parquet") assert writer.write() > 0 reloaded_dataset = Dataset.from_parquet(str(tmp_path / "foo.parquet")) assert dataset.features == reloaded_dataset.features reloaded_iterable_dataset = ParquetDatasetReader(str(tmp_path / "foo.parquet"), streaming=True).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected", [ (Features({"foo": Value("int32")}), None), (Features({"image": Image(), "foo": Value("int32")}), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio())}), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ], ) def test_get_writer_batch_size(feature, expected): assert get_writer_batch_size(feature) == expected
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/io/test_sql.py
import contextlib import os import sqlite3 import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def _check_sql_dataset(dataset, expected_features): assert isinstance(dataset, Dataset) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_dataset_from_sql_keep_in_memory(keep_in_memory, sqlite_path, tmp_path, set_sqlalchemy_silence_uber_warning): cache_dir = tmp_path / "cache" expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = SqlDatasetReader( "dataset", "sqlite:///" + sqlite_path, cache_dir=cache_dir, keep_in_memory=keep_in_memory ).read() _check_sql_dataset(dataset, expected_features) @require_sqlalchemy @pytest.mark.parametrize( "features", [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ], ) def test_dataset_from_sql_features(features, sqlite_path, tmp_path, set_sqlalchemy_silence_uber_warning): cache_dir = tmp_path / "cache" default_expected_features = {"col_1": "string", "col_2": "int64", "col_3": "float64"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = SqlDatasetReader("dataset", "sqlite:///" + sqlite_path, features=features, cache_dir=cache_dir).read() _check_sql_dataset(dataset, expected_features) def iter_sql_file(sqlite_path): with contextlib.closing(sqlite3.connect(sqlite_path)) as con: cur = con.cursor() cur.execute("SELECT * FROM dataset") for row in cur: yield row @require_sqlalchemy def test_dataset_to_sql(sqlite_path, tmp_path, set_sqlalchemy_silence_uber_warning): cache_dir = tmp_path / "cache" output_sqlite_path = os.path.join(cache_dir, "tmp.sql") dataset = SqlDatasetReader("dataset", "sqlite:///" + sqlite_path, cache_dir=cache_dir).read() SqlDatasetWriter(dataset, "dataset", "sqlite:///" + output_sqlite_path, num_proc=1).write() original_sql = iter_sql_file(sqlite_path) expected_sql = iter_sql_file(output_sqlite_path) for row1, row2 in zip(original_sql, expected_sql): assert row1 == row2 @require_sqlalchemy def test_dataset_to_sql_multiproc(sqlite_path, tmp_path, set_sqlalchemy_silence_uber_warning): cache_dir = tmp_path / "cache" output_sqlite_path = os.path.join(cache_dir, "tmp.sql") dataset = SqlDatasetReader("dataset", "sqlite:///" + sqlite_path, cache_dir=cache_dir).read() SqlDatasetWriter(dataset, "dataset", "sqlite:///" + output_sqlite_path, num_proc=2).write() original_sql = iter_sql_file(sqlite_path) expected_sql = iter_sql_file(output_sqlite_path) for row1, row2 in zip(original_sql, expected_sql): assert row1 == row2 @require_sqlalchemy def test_dataset_to_sql_invalidproc(sqlite_path, tmp_path, set_sqlalchemy_silence_uber_warning): cache_dir = tmp_path / "cache" output_sqlite_path = os.path.join(cache_dir, "tmp.sql") dataset = SqlDatasetReader("dataset", "sqlite:///" + sqlite_path, cache_dir=cache_dir).read() with pytest.raises(ValueError): SqlDatasetWriter(dataset, "dataset", "sqlite:///" + output_sqlite_path, num_proc=0).write()
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/io/test_text.py
import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.text import TextDatasetReader from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def _check_text_dataset(dataset, expected_features): assert isinstance(dataset, Dataset) assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_dataset_from_text_keep_in_memory(keep_in_memory, text_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"text": "string"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = TextDatasetReader(text_path, cache_dir=cache_dir, keep_in_memory=keep_in_memory).read() _check_text_dataset(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"text": "string"}, {"text": "int32"}, {"text": "float32"}, ], ) def test_dataset_from_text_features(features, text_path, tmp_path): cache_dir = tmp_path / "cache" default_expected_features = {"text": "string"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = TextDatasetReader(text_path, features=features, cache_dir=cache_dir).read() _check_text_dataset(dataset, expected_features) @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_dataset_from_text_split(split, text_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"text": "string"} dataset = TextDatasetReader(text_path, cache_dir=cache_dir, split=split).read() _check_text_dataset(dataset, expected_features) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type", [str, list]) def test_dataset_from_text_path_type(path_type, text_path, tmp_path): if issubclass(path_type, str): path = text_path elif issubclass(path_type, list): path = [text_path] cache_dir = tmp_path / "cache" expected_features = {"text": "string"} dataset = TextDatasetReader(path, cache_dir=cache_dir).read() _check_text_dataset(dataset, expected_features) def _check_text_datasetdict(dataset_dict, expected_features, splits=("train",)): assert isinstance(dataset_dict, DatasetDict) for split in splits: dataset = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory", [False, True]) def test_datasetdict_from_text_keep_in_memory(keep_in_memory, text_path, tmp_path): cache_dir = tmp_path / "cache" expected_features = {"text": "string"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): dataset = TextDatasetReader({"train": text_path}, cache_dir=cache_dir, keep_in_memory=keep_in_memory).read() _check_text_datasetdict(dataset, expected_features) @pytest.mark.parametrize( "features", [ None, {"text": "string"}, {"text": "int32"}, {"text": "float32"}, ], ) def test_datasetdict_from_text_features(features, text_path, tmp_path): cache_dir = tmp_path / "cache" # CSV file loses col_1 string dtype information: default now is "int64" instead of "string" default_expected_features = {"text": "string"} expected_features = features.copy() if features else default_expected_features features = ( Features({feature: Value(dtype) for feature, dtype in features.items()}) if features is not None else None ) dataset = TextDatasetReader({"train": text_path}, features=features, cache_dir=cache_dir).read() _check_text_datasetdict(dataset, expected_features) @pytest.mark.parametrize("split", [None, NamedSplit("train"), "train", "test"]) def test_datasetdict_from_text_split(split, text_path, tmp_path): if split: path = {split: text_path} else: split = "train" path = {"train": text_path, "test": text_path} cache_dir = tmp_path / "cache" expected_features = {"text": "string"} dataset = TextDatasetReader(path, cache_dir=cache_dir).read() _check_text_datasetdict(dataset, expected_features, splits=list(path.keys())) assert all(dataset[split].split == split for split in path.keys())
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/packaged_modules/test_audiofolder.py
import shutil import textwrap import librosa import numpy as np import pytest import soundfile as sf from datasets import Audio, ClassLabel, Features, Value from datasets.data_files import DataFilesDict, get_data_patterns from datasets.download.streaming_download_manager import StreamingDownloadManager from datasets.packaged_modules.audiofolder.audiofolder import AudioFolder from ..utils import require_sndfile @pytest.fixture def cache_dir(tmp_path): return str(tmp_path / "audiofolder_cache_dir") @pytest.fixture def data_files_with_labels_no_metadata(tmp_path, audio_file): data_dir = tmp_path / "data_files_with_labels_no_metadata" data_dir.mkdir(parents=True, exist_ok=True) subdir_class_0 = data_dir / "fr" subdir_class_0.mkdir(parents=True, exist_ok=True) subdir_class_1 = data_dir / "uk" subdir_class_1.mkdir(parents=True, exist_ok=True) audio_filename = subdir_class_0 / "audio_fr.wav" shutil.copyfile(audio_file, audio_filename) audio_filename2 = subdir_class_1 / "audio_uk.wav" shutil.copyfile(audio_file, audio_filename2) data_files_with_labels_no_metadata = DataFilesDict.from_patterns( get_data_patterns(str(data_dir)), data_dir.as_posix() ) return data_files_with_labels_no_metadata @pytest.fixture def audio_files_with_labels_and_duplicated_label_key_in_metadata(tmp_path, audio_file): data_dir = tmp_path / "audio_files_with_labels_and_label_key_in_metadata" data_dir.mkdir(parents=True, exist_ok=True) subdir_class_0 = data_dir / "fr" subdir_class_0.mkdir(parents=True, exist_ok=True) subdir_class_1 = data_dir / "uk" subdir_class_1.mkdir(parents=True, exist_ok=True) audio_filename = subdir_class_0 / "audio_fr.wav" shutil.copyfile(audio_file, audio_filename) audio_filename2 = subdir_class_1 / "audio_uk.wav" shutil.copyfile(audio_file, audio_filename2) audio_metadata_filename = tmp_path / data_dir / "metadata.jsonl" audio_metadata = textwrap.dedent( """\ {"file_name": "fr/audio_fr.wav", "text": "Audio in French", "label": "Fr"} {"file_name": "uk/audio_uk.wav", "text": "Audio in Ukrainian", "label": "Uk"} """ ) with open(audio_metadata_filename, "w", encoding="utf-8") as f: f.write(audio_metadata) return str(audio_filename), str(audio_filename2), str(audio_metadata_filename) @pytest.fixture def audio_file_with_metadata(tmp_path, audio_file): audio_filename = tmp_path / "audio_file.wav" shutil.copyfile(audio_file, audio_filename) audio_metadata_filename = tmp_path / "metadata.jsonl" audio_metadata = textwrap.dedent( """\ {"file_name": "audio_file.wav", "text": "Audio transcription"} """ ) with open(audio_metadata_filename, "w", encoding="utf-8") as f: f.write(audio_metadata) return str(audio_filename), str(audio_metadata_filename) @pytest.fixture def audio_files_with_metadata_that_misses_one_audio(tmp_path, audio_file): audio_filename = tmp_path / "audio_file.wav" shutil.copyfile(audio_file, audio_filename) audio_filename2 = tmp_path / "audio_file2.wav" shutil.copyfile(audio_file, audio_filename2) audio_metadata_filename = tmp_path / "metadata.jsonl" audio_metadata = textwrap.dedent( """\ {"file_name": "audio_file.wav", "text": "Audio transcription"} """ ) with open(audio_metadata_filename, "w", encoding="utf-8") as f: f.write(audio_metadata) return str(audio_filename), str(audio_filename2), str(audio_metadata_filename) @pytest.fixture def data_files_with_one_split_and_metadata(tmp_path, audio_file): data_dir = tmp_path / "audiofolder_data_dir_with_metadata" data_dir.mkdir(parents=True, exist_ok=True) subdir = data_dir / "subdir" subdir.mkdir(parents=True, exist_ok=True) audio_filename = data_dir / "audio_file.wav" shutil.copyfile(audio_file, audio_filename) audio_filename2 = data_dir / "audio_file2.wav" shutil.copyfile(audio_file, audio_filename2) audio_filename3 = subdir / "audio_file3.wav" # in subdir shutil.copyfile(audio_file, audio_filename3) audio_metadata_filename = data_dir / "metadata.jsonl" audio_metadata = textwrap.dedent( """\ {"file_name": "audio_file.wav", "text": "First audio transcription"} {"file_name": "audio_file2.wav", "text": "Second audio transcription"} {"file_name": "subdir/audio_file3.wav", "text": "Third audio transcription (in subdir)"} """ ) with open(audio_metadata_filename, "w", encoding="utf-8") as f: f.write(audio_metadata) data_files_with_one_split_and_metadata = DataFilesDict.from_patterns( get_data_patterns(str(data_dir)), data_dir.as_posix() ) assert len(data_files_with_one_split_and_metadata) == 1 assert len(data_files_with_one_split_and_metadata["train"]) == 4 return data_files_with_one_split_and_metadata @pytest.fixture(params=["jsonl", "csv"]) def data_files_with_two_splits_and_metadata(request, tmp_path, audio_file): data_dir = tmp_path / "audiofolder_data_dir_with_metadata" data_dir.mkdir(parents=True, exist_ok=True) train_dir = data_dir / "train" train_dir.mkdir(parents=True, exist_ok=True) test_dir = data_dir / "test" test_dir.mkdir(parents=True, exist_ok=True) audio_filename = train_dir / "audio_file.wav" # train audio shutil.copyfile(audio_file, audio_filename) audio_filename2 = train_dir / "audio_file2.wav" # train audio shutil.copyfile(audio_file, audio_filename2) audio_filename3 = test_dir / "audio_file3.wav" # test audio shutil.copyfile(audio_file, audio_filename3) train_audio_metadata_filename = train_dir / f"metadata.{request.param}" audio_metadata = ( textwrap.dedent( """\ {"file_name": "audio_file.wav", "text": "First train audio transcription"} {"file_name": "audio_file2.wav", "text": "Second train audio transcription"} """ ) if request.param == "jsonl" else textwrap.dedent( """\ file_name,text audio_file.wav,First train audio transcription audio_file2.wav,Second train audio transcription """ ) ) with open(train_audio_metadata_filename, "w", encoding="utf-8") as f: f.write(audio_metadata) test_audio_metadata_filename = test_dir / f"metadata.{request.param}" audio_metadata = ( textwrap.dedent( """\ {"file_name": "audio_file3.wav", "text": "Test audio transcription"} """ ) if request.param == "jsonl" else textwrap.dedent( """\ file_name,text audio_file3.wav,Test audio transcription """ ) ) with open(test_audio_metadata_filename, "w", encoding="utf-8") as f: f.write(audio_metadata) data_files_with_two_splits_and_metadata = DataFilesDict.from_patterns( get_data_patterns(str(data_dir)), data_dir.as_posix() ) assert len(data_files_with_two_splits_and_metadata) == 2 assert len(data_files_with_two_splits_and_metadata["train"]) == 3 assert len(data_files_with_two_splits_and_metadata["test"]) == 2 return data_files_with_two_splits_and_metadata @pytest.fixture def data_files_with_zip_archives(tmp_path, audio_file): data_dir = tmp_path / "audiofolder_data_dir_with_zip_archives" data_dir.mkdir(parents=True, exist_ok=True) archive_dir = data_dir / "archive" archive_dir.mkdir(parents=True, exist_ok=True) subdir = archive_dir / "subdir" subdir.mkdir(parents=True, exist_ok=True) audio_filename = archive_dir / "audio_file.wav" shutil.copyfile(audio_file, audio_filename) audio_filename2 = subdir / "audio_file2.wav" # in subdir # make sure they're two different audios # Indeed we won't be able to compare the audio filenames, since the archive is not extracted in streaming mode array, sampling_rate = librosa.load(str(audio_filename), sr=16000) # original sampling rate is 44100 sf.write(str(audio_filename2), array, samplerate=16000) audio_metadata_filename = archive_dir / "metadata.jsonl" audio_metadata = textwrap.dedent( """\ {"file_name": "audio_file.wav", "text": "First audio transcription"} {"file_name": "subdir/audio_file2.wav", "text": "Second audio transcription (in subdir)"} """ ) with open(audio_metadata_filename, "w", encoding="utf-8") as f: f.write(audio_metadata) shutil.make_archive(str(archive_dir), "zip", archive_dir) shutil.rmtree(str(archive_dir)) data_files_with_zip_archives = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) assert len(data_files_with_zip_archives) == 1 assert len(data_files_with_zip_archives["train"]) == 1 return data_files_with_zip_archives @require_sndfile # check that labels are inferred correctly from dir names def test_generate_examples_with_labels(data_files_with_labels_no_metadata, cache_dir): # there are no metadata.jsonl files in this test case audiofolder = AudioFolder(data_files=data_files_with_labels_no_metadata, cache_dir=cache_dir, drop_labels=False) audiofolder.download_and_prepare() assert audiofolder.info.features == Features({"audio": Audio(), "label": ClassLabel(names=["fr", "uk"])}) dataset = list(audiofolder.as_dataset()["train"]) label_feature = audiofolder.info.features["label"] assert dataset[0]["label"] == label_feature._str2int["fr"] assert dataset[1]["label"] == label_feature._str2int["uk"] @require_sndfile @pytest.mark.parametrize("drop_metadata", [None, True, False]) @pytest.mark.parametrize("drop_labels", [None, True, False]) def test_generate_examples_duplicated_label_key( audio_files_with_labels_and_duplicated_label_key_in_metadata, drop_metadata, drop_labels, cache_dir, caplog ): fr_audio_file, uk_audio_file, audio_metadata_file = audio_files_with_labels_and_duplicated_label_key_in_metadata audiofolder = AudioFolder( drop_metadata=drop_metadata, drop_labels=drop_labels, data_files=[fr_audio_file, uk_audio_file, audio_metadata_file], cache_dir=cache_dir, ) if drop_labels is False: # infer labels from directories even if metadata files are found audiofolder.download_and_prepare() warning_in_logs = any("ignoring metadata columns" in record.msg.lower() for record in caplog.records) assert warning_in_logs if drop_metadata is not True else not warning_in_logs dataset = audiofolder.as_dataset()["train"] assert audiofolder.info.features["label"] == ClassLabel(names=["fr", "uk"]) assert all(example["label"] in audiofolder.info.features["label"]._str2int.values() for example in dataset) else: audiofolder.download_and_prepare() dataset = audiofolder.as_dataset()["train"] if drop_metadata is not True: # labels are from metadata assert audiofolder.info.features["label"] == Value("string") assert all(example["label"] in ["Fr", "Uk"] for example in dataset) else: # drop both labels and metadata assert audiofolder.info.features == Features({"audio": Audio()}) assert all(example.keys() == {"audio"} for example in dataset) @require_sndfile @pytest.mark.parametrize("drop_metadata", [None, True, False]) @pytest.mark.parametrize("drop_labels", [None, True, False]) def test_generate_examples_drop_labels(data_files_with_labels_no_metadata, drop_metadata, drop_labels): audiofolder = AudioFolder( drop_metadata=drop_metadata, drop_labels=drop_labels, data_files=data_files_with_labels_no_metadata ) gen_kwargs = audiofolder._split_generators(StreamingDownloadManager())[0].gen_kwargs # removing the labels explicitly requires drop_labels=True assert gen_kwargs["add_labels"] is not bool(drop_labels) assert gen_kwargs["add_metadata"] is False # metadata files is not present in this case generator = audiofolder._generate_examples(**gen_kwargs) if not drop_labels: assert all( example.keys() == {"audio", "label"} and all(val is not None for val in example.values()) for _, example in generator ) else: assert all( example.keys() == {"audio"} and all(val is not None for val in example.values()) for _, example in generator ) @require_sndfile @pytest.mark.parametrize("drop_metadata", [None, True, False]) @pytest.mark.parametrize("drop_labels", [None, True, False]) def test_generate_examples_drop_metadata(audio_file_with_metadata, drop_metadata, drop_labels): audio_file, audio_metadata_file = audio_file_with_metadata audiofolder = AudioFolder( drop_metadata=drop_metadata, drop_labels=drop_labels, data_files={"train": [audio_file, audio_metadata_file]} ) gen_kwargs = audiofolder._split_generators(StreamingDownloadManager())[0].gen_kwargs # since the dataset has metadata, removing the metadata explicitly requires drop_metadata=True assert gen_kwargs["add_metadata"] is not bool(drop_metadata) # since the dataset has metadata, adding the labels explicitly requires drop_labels=False assert gen_kwargs["add_labels"] is (drop_labels is False) generator = audiofolder._generate_examples(**gen_kwargs) expected_columns = {"audio"} if gen_kwargs["add_metadata"]: expected_columns.add("text") if gen_kwargs["add_labels"]: expected_columns.add("label") result = [example for _, example in generator] assert len(result) == 1 example = result[0] assert example.keys() == expected_columns for column in expected_columns: assert example[column] is not None @require_sndfile @pytest.mark.parametrize("drop_metadata", [None, True, False]) def test_generate_examples_with_metadata_in_wrong_location(audio_file, audio_file_with_metadata, drop_metadata): _, audio_metadata_file = audio_file_with_metadata audiofolder = AudioFolder(drop_metadata=drop_metadata, data_files={"train": [audio_file, audio_metadata_file]}) gen_kwargs = audiofolder._split_generators(StreamingDownloadManager())[0].gen_kwargs generator = audiofolder._generate_examples(**gen_kwargs) if not drop_metadata: with pytest.raises(ValueError): list(generator) else: assert all( example.keys() == {"audio"} and all(val is not None for val in example.values()) for _, example in generator ) @require_sndfile @pytest.mark.parametrize("drop_metadata", [None, True, False]) def test_generate_examples_with_metadata_that_misses_one_audio( audio_files_with_metadata_that_misses_one_audio, drop_metadata ): audio_file, audio_file2, audio_metadata_file = audio_files_with_metadata_that_misses_one_audio if not drop_metadata: features = Features({"audio": Audio(), "text": Value("string")}) else: features = Features({"audio": Audio()}) audiofolder = AudioFolder( drop_metadata=drop_metadata, features=features, data_files={"train": [audio_file, audio_file2, audio_metadata_file]}, ) gen_kwargs = audiofolder._split_generators(StreamingDownloadManager())[0].gen_kwargs generator = audiofolder._generate_examples(**gen_kwargs) if not drop_metadata: with pytest.raises(ValueError): _ = list(generator) else: assert all( example.keys() == {"audio"} and all(val is not None for val in example.values()) for _, example in generator ) @require_sndfile @pytest.mark.parametrize("streaming", [False, True]) def test_data_files_with_metadata_and_single_split(streaming, cache_dir, data_files_with_one_split_and_metadata): data_files = data_files_with_one_split_and_metadata audiofolder = AudioFolder(data_files=data_files, cache_dir=cache_dir) audiofolder.download_and_prepare() datasets = audiofolder.as_streaming_dataset() if streaming else audiofolder.as_dataset() for split, data_files in data_files.items(): expected_num_of_audios = len(data_files) - 1 # don't count the metadata file assert split in datasets dataset = list(datasets[split]) assert len(dataset) == expected_num_of_audios # make sure each sample has its own audio and metadata assert len({example["audio"]["path"] for example in dataset}) == expected_num_of_audios assert len({example["text"] for example in dataset}) == expected_num_of_audios assert all(example["text"] is not None for example in dataset) @require_sndfile @pytest.mark.parametrize("streaming", [False, True]) def test_data_files_with_metadata_and_multiple_splits(streaming, cache_dir, data_files_with_two_splits_and_metadata): data_files = data_files_with_two_splits_and_metadata audiofolder = AudioFolder(data_files=data_files, cache_dir=cache_dir) audiofolder.download_and_prepare() datasets = audiofolder.as_streaming_dataset() if streaming else audiofolder.as_dataset() for split, data_files in data_files.items(): expected_num_of_audios = len(data_files) - 1 # don't count the metadata file assert split in datasets dataset = list(datasets[split]) assert len(dataset) == expected_num_of_audios # make sure each sample has its own audio and metadata assert len({example["audio"]["path"] for example in dataset}) == expected_num_of_audios assert len({example["text"] for example in dataset}) == expected_num_of_audios assert all(example["text"] is not None for example in dataset) @require_sndfile @pytest.mark.parametrize("streaming", [False, True]) def test_data_files_with_metadata_and_archives(streaming, cache_dir, data_files_with_zip_archives): audiofolder = AudioFolder(data_files=data_files_with_zip_archives, cache_dir=cache_dir) audiofolder.download_and_prepare() datasets = audiofolder.as_streaming_dataset() if streaming else audiofolder.as_dataset() for split, data_files in data_files_with_zip_archives.items(): num_of_archives = len(data_files) # the metadata file is inside the archive expected_num_of_audios = 2 * num_of_archives assert split in datasets dataset = list(datasets[split]) assert len(dataset) == expected_num_of_audios # make sure each sample has its own audio (all arrays are different) and metadata assert ( sum(np.array_equal(dataset[0]["audio"]["array"], example["audio"]["array"]) for example in dataset[1:]) == 0 ) assert len({example["text"] for example in dataset}) == expected_num_of_audios assert all(example["text"] is not None for example in dataset) @require_sndfile def test_data_files_with_wrong_metadata_file_name(cache_dir, tmp_path, audio_file): data_dir = tmp_path / "data_dir_with_bad_metadata" data_dir.mkdir(parents=True, exist_ok=True) shutil.copyfile(audio_file, data_dir / "audio_file.wav") audio_metadata_filename = data_dir / "bad_metadata.jsonl" # bad file audio_metadata = textwrap.dedent( """\ {"file_name": "audio_file.wav", "text": "Audio transcription"} """ ) with open(audio_metadata_filename, "w", encoding="utf-8") as f: f.write(audio_metadata) data_files_with_bad_metadata = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) audiofolder = AudioFolder(data_files=data_files_with_bad_metadata, cache_dir=cache_dir) audiofolder.download_and_prepare() dataset = audiofolder.as_dataset(split="train") # check that there are no metadata, since the metadata file name doesn't have the right name assert "text" not in dataset.column_names @require_sndfile def test_data_files_with_wrong_audio_file_name_column_in_metadata_file(cache_dir, tmp_path, audio_file): data_dir = tmp_path / "data_dir_with_bad_metadata" data_dir.mkdir(parents=True, exist_ok=True) shutil.copyfile(audio_file, data_dir / "audio_file.wav") audio_metadata_filename = data_dir / "metadata.jsonl" audio_metadata = textwrap.dedent( # with bad column "bad_file_name" instead of "file_name" """\ {"bad_file_name_column": "audio_file.wav", "text": "Audio transcription"} """ ) with open(audio_metadata_filename, "w", encoding="utf-8") as f: f.write(audio_metadata) data_files_with_bad_metadata = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) audiofolder = AudioFolder(data_files=data_files_with_bad_metadata, cache_dir=cache_dir) with pytest.raises(ValueError) as exc_info: audiofolder.download_and_prepare() assert "`file_name` must be present" in str(exc_info.value) @require_sndfile def test_data_files_with_with_metadata_in_different_formats(cache_dir, tmp_path, audio_file): data_dir = tmp_path / "data_dir_with_metadata_in_different_format" data_dir.mkdir(parents=True, exist_ok=True) shutil.copyfile(audio_file, data_dir / "audio_file.wav") audio_metadata_filename_jsonl = data_dir / "metadata.jsonl" audio_metadata_jsonl = textwrap.dedent( """\ {"file_name": "audio_file.wav", "text": "Audio transcription"} """ ) with open(audio_metadata_filename_jsonl, "w", encoding="utf-8") as f: f.write(audio_metadata_jsonl) audio_metadata_filename_csv = data_dir / "metadata.csv" audio_metadata_csv = textwrap.dedent( """\ file_name,text audio_file.wav,Audio transcription """ ) with open(audio_metadata_filename_csv, "w", encoding="utf-8") as f: f.write(audio_metadata_csv) data_files_with_bad_metadata = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) audiofolder = AudioFolder(data_files=data_files_with_bad_metadata, cache_dir=cache_dir) with pytest.raises(ValueError) as exc_info: audiofolder.download_and_prepare() assert "metadata files with different extensions" in str(exc_info.value)
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/packaged_modules/test_csv.py
import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def csv_file(tmp_path): filename = tmp_path / "file.csv" data = textwrap.dedent( """\ header1,header2 1,2 10,20 """ ) with open(filename, "w") as f: f.write(data) return str(filename) @pytest.fixture def malformed_csv_file(tmp_path): filename = tmp_path / "malformed_file.csv" data = textwrap.dedent( """\ header1,header2 1,2 10,20, """ ) with open(filename, "w") as f: f.write(data) return str(filename) @pytest.fixture def csv_file_with_image(tmp_path, image_file): filename = tmp_path / "csv_with_image.csv" data = textwrap.dedent( f"""\ image {image_file} """ ) with open(filename, "w") as f: f.write(data) return str(filename) @pytest.fixture def csv_file_with_label(tmp_path): filename = tmp_path / "csv_with_label.csv" data = textwrap.dedent( """\ label good bad good """ ) with open(filename, "w") as f: f.write(data) return str(filename) @pytest.fixture def csv_file_with_int_list(tmp_path): filename = tmp_path / "csv_with_int_list.csv" data = textwrap.dedent( """\ int_list 1 2 3 4 5 6 7 8 9 """ ) with open(filename, "w") as f: f.write(data) return str(filename) def test_csv_generate_tables_raises_error_with_malformed_csv(csv_file, malformed_csv_file, caplog): csv = Csv() generator = csv._generate_tables([[csv_file, malformed_csv_file]]) with pytest.raises(ValueError, match="Error tokenizing data"): for _ in generator: pass assert any( record.levelname == "ERROR" and "Failed to read file" in record.message and os.path.basename(malformed_csv_file) in record.message for record in caplog.records ) @require_pil def test_csv_cast_image(csv_file_with_image): with open(csv_file_with_image, encoding="utf-8") as f: image_file = f.read().splitlines()[1] csv = Csv(encoding="utf-8", features=Features({"image": Image()})) generator = csv._generate_tables([[csv_file_with_image]]) pa_table = pa.concat_tables([table for _, table in generator]) assert pa_table.schema.field("image").type == Image()() generated_content = pa_table.to_pydict()["image"] assert generated_content == [{"path": image_file, "bytes": None}] def test_csv_cast_label(csv_file_with_label): with open(csv_file_with_label, encoding="utf-8") as f: labels = f.read().splitlines()[1:] csv = Csv(encoding="utf-8", features=Features({"label": ClassLabel(names=["good", "bad"])})) generator = csv._generate_tables([[csv_file_with_label]]) pa_table = pa.concat_tables([table for _, table in generator]) assert pa_table.schema.field("label").type == ClassLabel(names=["good", "bad"])() generated_content = pa_table.to_pydict()["label"] assert generated_content == [ClassLabel(names=["good", "bad"]).str2int(label) for label in labels] def test_csv_convert_int_list(csv_file_with_int_list): csv = Csv(encoding="utf-8", sep=",", converters={"int_list": lambda x: [int(i) for i in x.split()]}) generator = csv._generate_tables([[csv_file_with_int_list]]) pa_table = pa.concat_tables([table for _, table in generator]) assert pa.types.is_list(pa_table.schema.field("int_list").type) generated_content = pa_table.to_pydict()["int_list"] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/packaged_modules/test_folder_based_builder.py
import importlib import shutil import textwrap import pytest from datasets import ClassLabel, DownloadManager, Features, Value from datasets.data_files import DataFilesDict, get_data_patterns from datasets.download.streaming_download_manager import StreamingDownloadManager from datasets.packaged_modules.folder_based_builder.folder_based_builder import ( FolderBasedBuilder, FolderBasedBuilderConfig, ) from datasets.tasks import TextClassification remote_files = [ "https://huggingface.co/datasets/polinaeterna/texts/resolve/main/hallo.txt", "https://huggingface.co/datasets/polinaeterna/texts/resolve/main/hello.txt", "https://huggingface.co/datasets/polinaeterna/texts/resolve/main/class1/bonjour.txt", "https://huggingface.co/datasets/polinaeterna/texts/resolve/main/class1/bonjour2.txt", ] class DummyFolderBasedBuilder(FolderBasedBuilder): BASE_FEATURE = dict BASE_COLUMN_NAME = "base" BUILDER_CONFIG_CLASS = FolderBasedBuilderConfig EXTENSIONS = [".txt"] CLASSIFICATION_TASK = TextClassification(text_column="base", label_column="label") @pytest.fixture def cache_dir(tmp_path): return str(tmp_path / "autofolder_cache_dir") @pytest.fixture def auto_text_file(text_file): return str(text_file) @pytest.fixture def data_files_with_labels_no_metadata(tmp_path, auto_text_file): data_dir = tmp_path / "data_files_with_labels_no_metadata" data_dir.mkdir(parents=True, exist_ok=True) subdir_class_0 = data_dir / "class0" subdir_class_0.mkdir(parents=True, exist_ok=True) subdir_class_1 = data_dir / "class1" subdir_class_1.mkdir(parents=True, exist_ok=True) filename = subdir_class_0 / "file0.txt" shutil.copyfile(auto_text_file, filename) filename2 = subdir_class_1 / "file1.txt" shutil.copyfile(auto_text_file, filename2) data_files_with_labels_no_metadata = DataFilesDict.from_patterns( get_data_patterns(str(data_dir)), data_dir.as_posix() ) return data_files_with_labels_no_metadata @pytest.fixture def data_files_with_different_levels_no_metadata(tmp_path, auto_text_file): data_dir = tmp_path / "data_files_with_different_levels" data_dir.mkdir(parents=True, exist_ok=True) subdir_class_0 = data_dir / "class0" subdir_class_0.mkdir(parents=True, exist_ok=True) subdir_class_1 = data_dir / "subdir" / "class1" subdir_class_1.mkdir(parents=True, exist_ok=True) filename = subdir_class_0 / "file0.txt" shutil.copyfile(auto_text_file, filename) filename2 = subdir_class_1 / "file1.txt" shutil.copyfile(auto_text_file, filename2) data_files_with_different_levels = DataFilesDict.from_patterns( get_data_patterns(str(data_dir)), data_dir.as_posix() ) return data_files_with_different_levels @pytest.fixture def data_files_with_one_label_no_metadata(tmp_path, auto_text_file): # only one label found = all files in a single dir/in a root dir data_dir = tmp_path / "data_files_with_one_label" data_dir.mkdir(parents=True, exist_ok=True) filename = data_dir / "file0.txt" shutil.copyfile(auto_text_file, filename) filename2 = data_dir / "file1.txt" shutil.copyfile(auto_text_file, filename2) data_files_with_one_label = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) return data_files_with_one_label @pytest.fixture def files_with_labels_and_duplicated_label_key_in_metadata(tmp_path, auto_text_file): data_dir = tmp_path / "files_with_labels_and_label_key_in_metadata" data_dir.mkdir(parents=True, exist_ok=True) subdir_class_0 = data_dir / "class0" subdir_class_0.mkdir(parents=True, exist_ok=True) subdir_class_1 = data_dir / "class1" subdir_class_1.mkdir(parents=True, exist_ok=True) filename = subdir_class_0 / "file_class0.txt" shutil.copyfile(auto_text_file, filename) filename2 = subdir_class_1 / "file_class1.txt" shutil.copyfile(auto_text_file, filename2) metadata_filename = tmp_path / data_dir / "metadata.jsonl" metadata = textwrap.dedent( """\ {"file_name": "class0/file_class0.txt", "additional_feature": "First dummy file", "label": "CLASS_0"} {"file_name": "class1/file_class1.txt", "additional_feature": "Second dummy file", "label": "CLASS_1"} """ ) with open(metadata_filename, "w", encoding="utf-8") as f: f.write(metadata) return str(filename), str(filename2), str(metadata_filename) @pytest.fixture def file_with_metadata(tmp_path, text_file): filename = tmp_path / "file.txt" shutil.copyfile(text_file, filename) metadata_filename = tmp_path / "metadata.jsonl" metadata = textwrap.dedent( """\ {"file_name": "file.txt", "additional_feature": "Dummy file"} """ ) with open(metadata_filename, "w", encoding="utf-8") as f: f.write(metadata) return str(filename), str(metadata_filename) @pytest.fixture() def files_with_metadata_that_misses_one_sample(tmp_path, auto_text_file): filename = tmp_path / "file.txt" shutil.copyfile(auto_text_file, filename) filename2 = tmp_path / "file2.txt" shutil.copyfile(auto_text_file, filename2) metadata_filename = tmp_path / "metadata.jsonl" metadata = textwrap.dedent( """\ {"file_name": "file.txt", "additional_feature": "Dummy file"} """ ) with open(metadata_filename, "w", encoding="utf-8") as f: f.write(metadata) return str(filename), str(filename2), str(metadata_filename) @pytest.fixture def data_files_with_one_split_and_metadata(tmp_path, auto_text_file): data_dir = tmp_path / "autofolder_data_dir_with_metadata_one_split" data_dir.mkdir(parents=True, exist_ok=True) subdir = data_dir / "subdir" subdir.mkdir(parents=True, exist_ok=True) filename = data_dir / "file.txt" shutil.copyfile(auto_text_file, filename) filename2 = data_dir / "file2.txt" shutil.copyfile(auto_text_file, filename2) filename3 = subdir / "file3.txt" # in subdir shutil.copyfile(auto_text_file, filename3) metadata_filename = data_dir / "metadata.jsonl" metadata = textwrap.dedent( """\ {"file_name": "file.txt", "additional_feature": "Dummy file"} {"file_name": "file2.txt", "additional_feature": "Second dummy file"} {"file_name": "./subdir/file3.txt", "additional_feature": "Third dummy file"} """ ) with open(metadata_filename, "w", encoding="utf-8") as f: f.write(metadata) data_files_with_one_split_and_metadata = DataFilesDict.from_patterns( get_data_patterns(str(data_dir)), data_dir.as_posix() ) assert len(data_files_with_one_split_and_metadata) == 1 assert len(data_files_with_one_split_and_metadata["train"]) == 4 return data_files_with_one_split_and_metadata @pytest.fixture def data_files_with_two_splits_and_metadata(tmp_path, auto_text_file): data_dir = tmp_path / "autofolder_data_dir_with_metadata_two_splits" data_dir.mkdir(parents=True, exist_ok=True) train_dir = data_dir / "train" train_dir.mkdir(parents=True, exist_ok=True) test_dir = data_dir / "test" test_dir.mkdir(parents=True, exist_ok=True) filename = train_dir / "file.txt" # train shutil.copyfile(auto_text_file, filename) filename2 = train_dir / "file2.txt" # train shutil.copyfile(auto_text_file, filename2) filename3 = test_dir / "file3.txt" # test shutil.copyfile(auto_text_file, filename3) train_metadata_filename = train_dir / "metadata.jsonl" train_metadata = textwrap.dedent( """\ {"file_name": "file.txt", "additional_feature": "Train dummy file"} {"file_name": "file2.txt", "additional_feature": "Second train dummy file"} """ ) with open(train_metadata_filename, "w", encoding="utf-8") as f: f.write(train_metadata) test_metadata_filename = test_dir / "metadata.jsonl" test_metadata = textwrap.dedent( """\ {"file_name": "file3.txt", "additional_feature": "Test dummy file"} """ ) with open(test_metadata_filename, "w", encoding="utf-8") as f: f.write(test_metadata) data_files_with_two_splits_and_metadata = DataFilesDict.from_patterns( get_data_patterns(str(data_dir)), data_dir.as_posix() ) assert len(data_files_with_two_splits_and_metadata) == 2 assert len(data_files_with_two_splits_and_metadata["train"]) == 3 assert len(data_files_with_two_splits_and_metadata["test"]) == 2 return data_files_with_two_splits_and_metadata @pytest.fixture def data_files_with_zip_archives(tmp_path, auto_text_file): data_dir = tmp_path / "autofolder_data_dir_with_zip_archives" data_dir.mkdir(parents=True, exist_ok=True) archive_dir = data_dir / "archive" archive_dir.mkdir(parents=True, exist_ok=True) subdir = archive_dir / "subdir" subdir.mkdir(parents=True, exist_ok=True) filename = archive_dir / "file.txt" shutil.copyfile(auto_text_file, filename) filename2 = subdir / "file2.txt" # in subdir shutil.copyfile(auto_text_file, filename2) metadata_filename = archive_dir / "metadata.jsonl" metadata = textwrap.dedent( """\ {"file_name": "file.txt", "additional_feature": "Dummy file"} {"file_name": "subdir/file2.txt", "additional_feature": "Second dummy file"} """ ) with open(metadata_filename, "w", encoding="utf-8") as f: f.write(metadata) shutil.make_archive(archive_dir, "zip", archive_dir) shutil.rmtree(str(archive_dir)) data_files_with_zip_archives = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) assert len(data_files_with_zip_archives) == 1 assert len(data_files_with_zip_archives["train"]) == 1 return data_files_with_zip_archives def test_inferring_labels_from_data_dirs(data_files_with_labels_no_metadata, cache_dir): autofolder = DummyFolderBasedBuilder( data_files=data_files_with_labels_no_metadata, cache_dir=cache_dir, drop_labels=False ) gen_kwargs = autofolder._split_generators(StreamingDownloadManager())[0].gen_kwargs assert autofolder.info.features == Features({"base": {}, "label": ClassLabel(names=["class0", "class1"])}) generator = autofolder._generate_examples(**gen_kwargs) assert all(example["label"] in {"class0", "class1"} for _, example in generator) def test_default_folder_builder_not_usable(data_files_with_labels_no_metadata, cache_dir): # builder would try to access non-existing attributes of a default `BuilderConfig` class # as a custom one is not provided with pytest.raises(AttributeError): _ = FolderBasedBuilder( data_files=data_files_with_labels_no_metadata, cache_dir=cache_dir, ) # test that AutoFolder is extended for streaming when it's child class is instantiated: # see line 115 in src/datasets/streaming.py def test_streaming_patched(): _ = DummyFolderBasedBuilder() module = importlib.import_module(FolderBasedBuilder.__module__) assert hasattr(module, "_patched_for_streaming") assert module._patched_for_streaming @pytest.mark.parametrize("drop_metadata", [None, True, False]) @pytest.mark.parametrize("drop_labels", [None, True, False]) def test_generate_examples_duplicated_label_key( files_with_labels_and_duplicated_label_key_in_metadata, drop_metadata, drop_labels, cache_dir, caplog ): class0_file, class1_file, metadata_file = files_with_labels_and_duplicated_label_key_in_metadata autofolder = DummyFolderBasedBuilder( data_files=[class0_file, class1_file, metadata_file], cache_dir=cache_dir, drop_metadata=drop_metadata, drop_labels=drop_labels, ) gen_kwargs = autofolder._split_generators(StreamingDownloadManager())[0].gen_kwargs generator = autofolder._generate_examples(**gen_kwargs) if drop_labels is False: # infer labels from directories even if metadata files are found warning_in_logs = any("ignoring metadata columns" in record.msg.lower() for record in caplog.records) assert warning_in_logs if drop_metadata is not True else not warning_in_logs assert autofolder.info.features["label"] == ClassLabel(names=["class0", "class1"]) assert all(example["label"] in ["class0", "class1"] for _, example in generator) else: if drop_metadata is not True: # labels are from metadata assert autofolder.info.features["label"] == Value("string") assert all(example["label"] in ["CLASS_0", "CLASS_1"] for _, example in generator) else: # drop both labels and metadata assert autofolder.info.features == Features({"base": {}}) assert all(example.keys() == {"base"} for _, example in generator) @pytest.mark.parametrize("drop_metadata", [None, True, False]) @pytest.mark.parametrize("drop_labels", [None, True, False]) def test_generate_examples_drop_labels( data_files_with_labels_no_metadata, auto_text_file, drop_metadata, drop_labels, cache_dir ): autofolder = DummyFolderBasedBuilder( data_files=data_files_with_labels_no_metadata, drop_metadata=drop_metadata, drop_labels=drop_labels, cache_dir=cache_dir, ) gen_kwargs = autofolder._split_generators(StreamingDownloadManager())[0].gen_kwargs # removing labels explicitly requires drop_labels=True assert gen_kwargs["add_labels"] is not bool(drop_labels) assert gen_kwargs["add_metadata"] is False generator = autofolder._generate_examples(**gen_kwargs) if not drop_labels: assert all( example.keys() == {"base", "label"} and all(val is not None for val in example.values()) for _, example in generator ) else: assert all( example.keys() == {"base"} and all(val is not None for val in example.values()) for _, example in generator ) @pytest.mark.parametrize("drop_metadata", [None, True, False]) @pytest.mark.parametrize("drop_labels", [None, True, False]) def test_generate_examples_drop_metadata(file_with_metadata, drop_metadata, drop_labels, cache_dir): file, metadata_file = file_with_metadata autofolder = DummyFolderBasedBuilder( data_files=[file, metadata_file], drop_metadata=drop_metadata, drop_labels=drop_labels, cache_dir=cache_dir, ) gen_kwargs = autofolder._split_generators(StreamingDownloadManager())[0].gen_kwargs # since the dataset has metadata, removing the metadata explicitly requires drop_metadata=True assert gen_kwargs["add_metadata"] is not bool(drop_metadata) # since the dataset has metadata, adding the labels explicitly requires drop_labels=False assert gen_kwargs["add_labels"] is (drop_labels is False) generator = autofolder._generate_examples(**gen_kwargs) expected_columns = {"base"} if gen_kwargs["add_metadata"]: expected_columns.add("additional_feature") if gen_kwargs["add_labels"]: expected_columns.add("label") result = [example for _, example in generator] assert len(result) == 1 example = result[0] assert example.keys() == expected_columns for column in expected_columns: assert example[column] is not None @pytest.mark.parametrize("remote", [True, False]) @pytest.mark.parametrize("drop_labels", [None, True, False]) def test_data_files_with_different_levels_no_metadata( data_files_with_different_levels_no_metadata, drop_labels, remote, cache_dir ): data_files = remote_files if remote else data_files_with_different_levels_no_metadata autofolder = DummyFolderBasedBuilder( data_files=data_files, cache_dir=cache_dir, drop_labels=drop_labels, ) gen_kwargs = autofolder._split_generators(StreamingDownloadManager())[0].gen_kwargs generator = autofolder._generate_examples(**gen_kwargs) if drop_labels is not False: # with None (default) we should drop labels if files are on different levels in dir structure assert "label" not in autofolder.info.features assert all(example.keys() == {"base"} for _, example in generator) else: assert "label" in autofolder.info.features assert isinstance(autofolder.info.features["label"], ClassLabel) assert all(example.keys() == {"base", "label"} for _, example in generator) @pytest.mark.parametrize("remote", [False, True]) @pytest.mark.parametrize("drop_labels", [None, True, False]) def test_data_files_with_one_label_no_metadata(data_files_with_one_label_no_metadata, drop_labels, remote, cache_dir): data_files = remote_files[:2] if remote else data_files_with_one_label_no_metadata autofolder = DummyFolderBasedBuilder( data_files=data_files, cache_dir=cache_dir, drop_labels=drop_labels, ) gen_kwargs = autofolder._split_generators(StreamingDownloadManager())[0].gen_kwargs generator = autofolder._generate_examples(**gen_kwargs) if drop_labels is not False: # with None (default) we should drop labels if only one label is found (=if there is a single dir) assert "label" not in autofolder.info.features assert all(example.keys() == {"base"} for _, example in generator) else: assert "label" in autofolder.info.features assert isinstance(autofolder.info.features["label"], ClassLabel) assert all(example.keys() == {"base", "label"} for _, example in generator) @pytest.mark.parametrize("drop_metadata", [None, True, False]) def test_data_files_with_metadata_that_misses_one_sample( files_with_metadata_that_misses_one_sample, drop_metadata, cache_dir ): file, file2, metadata_file = files_with_metadata_that_misses_one_sample if not drop_metadata: features = Features({"base": None, "additional_feature": Value("string")}) else: features = Features({"base": None}) autofolder = DummyFolderBasedBuilder( data_files=[file, file2, metadata_file], drop_metadata=drop_metadata, features=features, cache_dir=cache_dir, ) gen_kwargs = autofolder._split_generators(StreamingDownloadManager())[0].gen_kwargs generator = autofolder._generate_examples(**gen_kwargs) if not drop_metadata: with pytest.raises(ValueError): list(generator) else: assert all( example.keys() == {"base"} and all(val is not None for val in example.values()) for _, example in generator ) @pytest.mark.parametrize("streaming", [False, True]) @pytest.mark.parametrize("n_splits", [1, 2]) def test_data_files_with_metadata_and_splits( streaming, cache_dir, n_splits, data_files_with_one_split_and_metadata, data_files_with_two_splits_and_metadata ): data_files = data_files_with_one_split_and_metadata if n_splits == 1 else data_files_with_two_splits_and_metadata autofolder = DummyFolderBasedBuilder( data_files=data_files, cache_dir=cache_dir, ) download_manager = StreamingDownloadManager() if streaming else DownloadManager() generated_splits = autofolder._split_generators(download_manager) for (split, files), generated_split in zip(data_files.items(), generated_splits): assert split == generated_split.name expected_num_of_examples = len(files) - 1 generated_examples = list(autofolder._generate_examples(**generated_split.gen_kwargs)) assert len(generated_examples) == expected_num_of_examples assert len({example["base"] for _, example in generated_examples}) == expected_num_of_examples assert len({example["additional_feature"] for _, example in generated_examples}) == expected_num_of_examples assert all(example["additional_feature"] is not None for _, example in generated_examples) @pytest.mark.parametrize("streaming", [False, True]) def test_data_files_with_metadata_and_archives(streaming, cache_dir, data_files_with_zip_archives): autofolder = DummyFolderBasedBuilder(data_files=data_files_with_zip_archives, cache_dir=cache_dir) download_manager = StreamingDownloadManager() if streaming else DownloadManager() generated_splits = autofolder._split_generators(download_manager) for (split, files), generated_split in zip(data_files_with_zip_archives.items(), generated_splits): assert split == generated_split.name num_of_archives = len(files) expected_num_of_examples = 2 * num_of_archives generated_examples = list(autofolder._generate_examples(**generated_split.gen_kwargs)) assert len(generated_examples) == expected_num_of_examples assert len({example["base"] for _, example in generated_examples}) == expected_num_of_examples assert len({example["additional_feature"] for _, example in generated_examples}) == expected_num_of_examples assert all(example["additional_feature"] is not None for _, example in generated_examples) def test_data_files_with_wrong_metadata_file_name(cache_dir, tmp_path, auto_text_file): data_dir = tmp_path / "data_dir_with_bad_metadata" data_dir.mkdir(parents=True, exist_ok=True) shutil.copyfile(auto_text_file, data_dir / "file.txt") metadata_filename = data_dir / "bad_metadata.jsonl" # bad file metadata = textwrap.dedent( """\ {"file_name": "file.txt", "additional_feature": "Dummy file"} """ ) with open(metadata_filename, "w", encoding="utf-8") as f: f.write(metadata) data_files_with_bad_metadata = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) autofolder = DummyFolderBasedBuilder(data_files=data_files_with_bad_metadata, cache_dir=cache_dir) gen_kwargs = autofolder._split_generators(StreamingDownloadManager())[0].gen_kwargs generator = autofolder._generate_examples(**gen_kwargs) assert all("additional_feature" not in example for _, example in generator) def test_data_files_with_wrong_file_name_column_in_metadata_file(cache_dir, tmp_path, auto_text_file): data_dir = tmp_path / "data_dir_with_bad_metadata" data_dir.mkdir(parents=True, exist_ok=True) shutil.copyfile(auto_text_file, data_dir / "file.txt") metadata_filename = data_dir / "metadata.jsonl" metadata = textwrap.dedent( # with bad column "bad_file_name" instead of "file_name" """\ {"bad_file_name": "file.txt", "additional_feature": "Dummy file"} """ ) with open(metadata_filename, "w", encoding="utf-8") as f: f.write(metadata) data_files_with_bad_metadata = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) autofolder = DummyFolderBasedBuilder(data_files=data_files_with_bad_metadata, cache_dir=cache_dir) with pytest.raises(ValueError) as exc_info: _ = autofolder._split_generators(StreamingDownloadManager())[0].gen_kwargs assert "`file_name` must be present" in str(exc_info.value)
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/packaged_modules/test_imagefolder.py
import shutil import textwrap import numpy as np import pytest from datasets import ClassLabel, Features, Image, Value from datasets.data_files import DataFilesDict, get_data_patterns from datasets.download.streaming_download_manager import StreamingDownloadManager from datasets.packaged_modules.imagefolder.imagefolder import ImageFolder from ..utils import require_pil @pytest.fixture def cache_dir(tmp_path): return str(tmp_path / "imagefolder_cache_dir") @pytest.fixture def data_files_with_labels_no_metadata(tmp_path, image_file): data_dir = tmp_path / "data_files_with_labels_no_metadata" data_dir.mkdir(parents=True, exist_ok=True) subdir_class_0 = data_dir / "cat" subdir_class_0.mkdir(parents=True, exist_ok=True) subdir_class_1 = data_dir / "dog" subdir_class_1.mkdir(parents=True, exist_ok=True) image_filename = subdir_class_0 / "image_cat.jpg" shutil.copyfile(image_file, image_filename) image_filename2 = subdir_class_1 / "image_dog.jpg" shutil.copyfile(image_file, image_filename2) data_files_with_labels_no_metadata = DataFilesDict.from_patterns( get_data_patterns(str(data_dir)), data_dir.as_posix() ) return data_files_with_labels_no_metadata @pytest.fixture def image_files_with_labels_and_duplicated_label_key_in_metadata(tmp_path, image_file): data_dir = tmp_path / "image_files_with_labels_and_label_key_in_metadata" data_dir.mkdir(parents=True, exist_ok=True) subdir_class_0 = data_dir / "cat" subdir_class_0.mkdir(parents=True, exist_ok=True) subdir_class_1 = data_dir / "dog" subdir_class_1.mkdir(parents=True, exist_ok=True) image_filename = subdir_class_0 / "image_cat.jpg" shutil.copyfile(image_file, image_filename) image_filename2 = subdir_class_1 / "image_dog.jpg" shutil.copyfile(image_file, image_filename2) image_metadata_filename = tmp_path / data_dir / "metadata.jsonl" image_metadata = textwrap.dedent( """\ {"file_name": "cat/image_cat.jpg", "caption": "Nice image of a cat", "label": "Cat"} {"file_name": "dog/image_dog.jpg", "caption": "Nice image of a dog", "label": "Dog"} """ ) with open(image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) return str(image_filename), str(image_filename2), str(image_metadata_filename) @pytest.fixture def image_file_with_metadata(tmp_path, image_file): image_filename = tmp_path / "image_rgb.jpg" shutil.copyfile(image_file, image_filename) image_metadata_filename = tmp_path / "metadata.jsonl" image_metadata = textwrap.dedent( """\ {"file_name": "image_rgb.jpg", "caption": "Nice image"} """ ) with open(image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) return str(image_filename), str(image_metadata_filename) @pytest.fixture def image_files_with_metadata_that_misses_one_image(tmp_path, image_file): image_filename = tmp_path / "image_rgb.jpg" shutil.copyfile(image_file, image_filename) image_filename2 = tmp_path / "image_rgb2.jpg" shutil.copyfile(image_file, image_filename2) image_metadata_filename = tmp_path / "metadata.jsonl" image_metadata = textwrap.dedent( """\ {"file_name": "image_rgb.jpg", "caption": "Nice image"} """ ) with open(image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) return str(image_filename), str(image_filename2), str(image_metadata_filename) @pytest.fixture(params=["jsonl", "csv"]) def data_files_with_one_split_and_metadata(request, tmp_path, image_file): data_dir = tmp_path / "imagefolder_data_dir_with_metadata_one_split" data_dir.mkdir(parents=True, exist_ok=True) subdir = data_dir / "subdir" subdir.mkdir(parents=True, exist_ok=True) image_filename = data_dir / "image_rgb.jpg" shutil.copyfile(image_file, image_filename) image_filename2 = data_dir / "image_rgb2.jpg" shutil.copyfile(image_file, image_filename2) image_filename3 = subdir / "image_rgb3.jpg" # in subdir shutil.copyfile(image_file, image_filename3) image_metadata_filename = data_dir / f"metadata.{request.param}" image_metadata = ( textwrap.dedent( """\ {"file_name": "image_rgb.jpg", "caption": "Nice image"} {"file_name": "image_rgb2.jpg", "caption": "Nice second image"} {"file_name": "subdir/image_rgb3.jpg", "caption": "Nice third image"} """ ) if request.param == "jsonl" else textwrap.dedent( """\ file_name,caption image_rgb.jpg,Nice image image_rgb2.jpg,Nice second image subdir/image_rgb3.jpg,Nice third image """ ) ) with open(image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) data_files_with_one_split_and_metadata = DataFilesDict.from_patterns( get_data_patterns(str(data_dir)), data_dir.as_posix() ) assert len(data_files_with_one_split_and_metadata) == 1 assert len(data_files_with_one_split_and_metadata["train"]) == 4 return data_files_with_one_split_and_metadata @pytest.fixture(params=["jsonl", "csv"]) def data_files_with_two_splits_and_metadata(request, tmp_path, image_file): data_dir = tmp_path / "imagefolder_data_dir_with_metadata_two_splits" data_dir.mkdir(parents=True, exist_ok=True) train_dir = data_dir / "train" train_dir.mkdir(parents=True, exist_ok=True) test_dir = data_dir / "test" test_dir.mkdir(parents=True, exist_ok=True) image_filename = train_dir / "image_rgb.jpg" # train image shutil.copyfile(image_file, image_filename) image_filename2 = train_dir / "image_rgb2.jpg" # train image shutil.copyfile(image_file, image_filename2) image_filename3 = test_dir / "image_rgb3.jpg" # test image shutil.copyfile(image_file, image_filename3) train_image_metadata_filename = train_dir / f"metadata.{request.param}" image_metadata = ( textwrap.dedent( """\ {"file_name": "image_rgb.jpg", "caption": "Nice train image"} {"file_name": "image_rgb2.jpg", "caption": "Nice second train image"} """ ) if request.param == "jsonl" else textwrap.dedent( """\ file_name,caption image_rgb.jpg,Nice train image image_rgb2.jpg,Nice second train image """ ) ) with open(train_image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) test_image_metadata_filename = test_dir / f"metadata.{request.param}" image_metadata = ( textwrap.dedent( """\ {"file_name": "image_rgb3.jpg", "caption": "Nice test image"} """ ) if request.param == "jsonl" else textwrap.dedent( """\ file_name,caption image_rgb3.jpg,Nice test image """ ) ) with open(test_image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) data_files_with_two_splits_and_metadata = DataFilesDict.from_patterns( get_data_patterns(str(data_dir)), data_dir.as_posix() ) assert len(data_files_with_two_splits_and_metadata) == 2 assert len(data_files_with_two_splits_and_metadata["train"]) == 3 assert len(data_files_with_two_splits_and_metadata["test"]) == 2 return data_files_with_two_splits_and_metadata @pytest.fixture def data_files_with_zip_archives(tmp_path, image_file): from PIL import Image, ImageOps data_dir = tmp_path / "imagefolder_data_dir_with_zip_archives" data_dir.mkdir(parents=True, exist_ok=True) archive_dir = data_dir / "archive" archive_dir.mkdir(parents=True, exist_ok=True) subdir = archive_dir / "subdir" subdir.mkdir(parents=True, exist_ok=True) image_filename = archive_dir / "image_rgb.jpg" shutil.copyfile(image_file, image_filename) image_filename2 = subdir / "image_rgb2.jpg" # in subdir # make sure they're two different images # Indeed we won't be able to compare the image.filename, since the archive is not extracted in streaming mode ImageOps.flip(Image.open(image_file)).save(image_filename2) image_metadata_filename = archive_dir / "metadata.jsonl" image_metadata = textwrap.dedent( """\ {"file_name": "image_rgb.jpg", "caption": "Nice image"} {"file_name": "subdir/image_rgb2.jpg", "caption": "Nice second image"} """ ) with open(image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) shutil.make_archive(archive_dir, "zip", archive_dir) shutil.rmtree(str(archive_dir)) data_files_with_zip_archives = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) assert len(data_files_with_zip_archives) == 1 assert len(data_files_with_zip_archives["train"]) == 1 return data_files_with_zip_archives @require_pil # check that labels are inferred correctly from dir names def test_generate_examples_with_labels(data_files_with_labels_no_metadata, cache_dir): # there are no metadata.jsonl files in this test case imagefolder = ImageFolder(data_files=data_files_with_labels_no_metadata, cache_dir=cache_dir, drop_labels=False) imagefolder.download_and_prepare() assert imagefolder.info.features == Features({"image": Image(), "label": ClassLabel(names=["cat", "dog"])}) dataset = list(imagefolder.as_dataset()["train"]) label_feature = imagefolder.info.features["label"] assert dataset[0]["label"] == label_feature._str2int["cat"] assert dataset[1]["label"] == label_feature._str2int["dog"] @require_pil @pytest.mark.parametrize("drop_metadata", [None, True, False]) @pytest.mark.parametrize("drop_labels", [None, True, False]) def test_generate_examples_duplicated_label_key( image_files_with_labels_and_duplicated_label_key_in_metadata, drop_metadata, drop_labels, cache_dir, caplog ): cat_image_file, dog_image_file, image_metadata_file = image_files_with_labels_and_duplicated_label_key_in_metadata imagefolder = ImageFolder( drop_metadata=drop_metadata, drop_labels=drop_labels, data_files=[cat_image_file, dog_image_file, image_metadata_file], cache_dir=cache_dir, ) if drop_labels is False: # infer labels from directories even if metadata files are found imagefolder.download_and_prepare() warning_in_logs = any("ignoring metadata columns" in record.msg.lower() for record in caplog.records) assert warning_in_logs if drop_metadata is not True else not warning_in_logs dataset = imagefolder.as_dataset()["train"] assert imagefolder.info.features["label"] == ClassLabel(names=["cat", "dog"]) assert all(example["label"] in imagefolder.info.features["label"]._str2int.values() for example in dataset) else: imagefolder.download_and_prepare() dataset = imagefolder.as_dataset()["train"] if drop_metadata is not True: # labels are from metadata assert imagefolder.info.features["label"] == Value("string") assert all(example["label"] in ["Cat", "Dog"] for example in dataset) else: # drop both labels and metadata assert imagefolder.info.features == Features({"image": Image()}) assert all(example.keys() == {"image"} for example in dataset) @require_pil @pytest.mark.parametrize("drop_metadata", [None, True, False]) @pytest.mark.parametrize("drop_labels", [None, True, False]) def test_generate_examples_drop_labels(data_files_with_labels_no_metadata, drop_metadata, drop_labels): imagefolder = ImageFolder( drop_metadata=drop_metadata, drop_labels=drop_labels, data_files=data_files_with_labels_no_metadata ) gen_kwargs = imagefolder._split_generators(StreamingDownloadManager())[0].gen_kwargs # removing the labels explicitly requires drop_labels=True assert gen_kwargs["add_labels"] is not bool(drop_labels) assert gen_kwargs["add_metadata"] is False generator = imagefolder._generate_examples(**gen_kwargs) if not drop_labels: assert all( example.keys() == {"image", "label"} and all(val is not None for val in example.values()) for _, example in generator ) else: assert all( example.keys() == {"image"} and all(val is not None for val in example.values()) for _, example in generator ) @require_pil @pytest.mark.parametrize("drop_metadata", [None, True, False]) @pytest.mark.parametrize("drop_labels", [None, True, False]) def test_generate_examples_drop_metadata(image_file_with_metadata, drop_metadata, drop_labels): image_file, image_metadata_file = image_file_with_metadata imagefolder = ImageFolder( drop_metadata=drop_metadata, drop_labels=drop_labels, data_files={"train": [image_file, image_metadata_file]} ) gen_kwargs = imagefolder._split_generators(StreamingDownloadManager())[0].gen_kwargs # since the dataset has metadata, removing the metadata explicitly requires drop_metadata=True assert gen_kwargs["add_metadata"] is not bool(drop_metadata) # since the dataset has metadata, adding the labels explicitly requires drop_labels=False assert gen_kwargs["add_labels"] is (drop_labels is False) generator = imagefolder._generate_examples(**gen_kwargs) expected_columns = {"image"} if gen_kwargs["add_metadata"]: expected_columns.add("caption") if gen_kwargs["add_labels"]: expected_columns.add("label") result = [example for _, example in generator] assert len(result) == 1 example = result[0] assert example.keys() == expected_columns for column in expected_columns: assert example[column] is not None @require_pil @pytest.mark.parametrize("drop_metadata", [None, True, False]) def test_generate_examples_with_metadata_in_wrong_location(image_file, image_file_with_metadata, drop_metadata): _, image_metadata_file = image_file_with_metadata imagefolder = ImageFolder(drop_metadata=drop_metadata, data_files={"train": [image_file, image_metadata_file]}) gen_kwargs = imagefolder._split_generators(StreamingDownloadManager())[0].gen_kwargs generator = imagefolder._generate_examples(**gen_kwargs) if not drop_metadata: with pytest.raises(ValueError): list(generator) else: assert all( example.keys() == {"image"} and all(val is not None for val in example.values()) for _, example in generator ) @require_pil @pytest.mark.parametrize("drop_metadata", [None, True, False]) def test_generate_examples_with_metadata_that_misses_one_image( image_files_with_metadata_that_misses_one_image, drop_metadata ): image_file, image_file2, image_metadata_file = image_files_with_metadata_that_misses_one_image if not drop_metadata: features = Features({"image": Image(), "caption": Value("string")}) else: features = Features({"image": Image()}) imagefolder = ImageFolder( drop_metadata=drop_metadata, features=features, data_files={"train": [image_file, image_file2, image_metadata_file]}, ) gen_kwargs = imagefolder._split_generators(StreamingDownloadManager())[0].gen_kwargs generator = imagefolder._generate_examples(**gen_kwargs) if not drop_metadata: with pytest.raises(ValueError): list(generator) else: assert all( example.keys() == {"image"} and all(val is not None for val in example.values()) for _, example in generator ) @require_pil @pytest.mark.parametrize("streaming", [False, True]) def test_data_files_with_metadata_and_single_split(streaming, cache_dir, data_files_with_one_split_and_metadata): data_files = data_files_with_one_split_and_metadata imagefolder = ImageFolder(data_files=data_files, cache_dir=cache_dir) imagefolder.download_and_prepare() datasets = imagefolder.as_streaming_dataset() if streaming else imagefolder.as_dataset() for split, data_files in data_files.items(): expected_num_of_images = len(data_files) - 1 # don't count the metadata file assert split in datasets dataset = list(datasets[split]) assert len(dataset) == expected_num_of_images # make sure each sample has its own image and metadata assert len({example["image"].filename for example in dataset}) == expected_num_of_images assert len({example["caption"] for example in dataset}) == expected_num_of_images assert all(example["caption"] is not None for example in dataset) @require_pil @pytest.mark.parametrize("streaming", [False, True]) def test_data_files_with_metadata_and_multiple_splits(streaming, cache_dir, data_files_with_two_splits_and_metadata): data_files = data_files_with_two_splits_and_metadata imagefolder = ImageFolder(data_files=data_files, cache_dir=cache_dir) imagefolder.download_and_prepare() datasets = imagefolder.as_streaming_dataset() if streaming else imagefolder.as_dataset() for split, data_files in data_files.items(): expected_num_of_images = len(data_files) - 1 # don't count the metadata file assert split in datasets dataset = list(datasets[split]) assert len(dataset) == expected_num_of_images # make sure each sample has its own image and metadata assert len({example["image"].filename for example in dataset}) == expected_num_of_images assert len({example["caption"] for example in dataset}) == expected_num_of_images assert all(example["caption"] is not None for example in dataset) @require_pil @pytest.mark.parametrize("streaming", [False, True]) def test_data_files_with_metadata_and_archives(streaming, cache_dir, data_files_with_zip_archives): imagefolder = ImageFolder(data_files=data_files_with_zip_archives, cache_dir=cache_dir) imagefolder.download_and_prepare() datasets = imagefolder.as_streaming_dataset() if streaming else imagefolder.as_dataset() for split, data_files in data_files_with_zip_archives.items(): num_of_archives = len(data_files) # the metadata file is inside the archive expected_num_of_images = 2 * num_of_archives assert split in datasets dataset = list(datasets[split]) assert len(dataset) == expected_num_of_images # make sure each sample has its own image and metadata assert len({np.array(example["image"])[0, 0, 0] for example in dataset}) == expected_num_of_images assert len({example["caption"] for example in dataset}) == expected_num_of_images assert all(example["caption"] is not None for example in dataset) @require_pil def test_data_files_with_wrong_metadata_file_name(cache_dir, tmp_path, image_file): data_dir = tmp_path / "data_dir_with_bad_metadata" data_dir.mkdir(parents=True, exist_ok=True) shutil.copyfile(image_file, data_dir / "image_rgb.jpg") image_metadata_filename = data_dir / "bad_metadata.jsonl" # bad file image_metadata = textwrap.dedent( """\ {"file_name": "image_rgb.jpg", "caption": "Nice image"} """ ) with open(image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) data_files_with_bad_metadata = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) imagefolder = ImageFolder(data_files=data_files_with_bad_metadata, cache_dir=cache_dir) imagefolder.download_and_prepare() dataset = imagefolder.as_dataset(split="train") # check that there are no metadata, since the metadata file name doesn't have the right name assert "caption" not in dataset.column_names @require_pil def test_data_files_with_wrong_image_file_name_column_in_metadata_file(cache_dir, tmp_path, image_file): data_dir = tmp_path / "data_dir_with_bad_metadata" data_dir.mkdir(parents=True, exist_ok=True) shutil.copyfile(image_file, data_dir / "image_rgb.jpg") image_metadata_filename = data_dir / "metadata.jsonl" image_metadata = textwrap.dedent( # with bad column "bad_file_name" instead of "file_name" """\ {"bad_file_name": "image_rgb.jpg", "caption": "Nice image"} """ ) with open(image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) data_files_with_bad_metadata = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) imagefolder = ImageFolder(data_files=data_files_with_bad_metadata, cache_dir=cache_dir) with pytest.raises(ValueError) as exc_info: imagefolder.download_and_prepare() assert "`file_name` must be present" in str(exc_info.value) @require_pil def test_data_files_with_with_metadata_in_different_formats(cache_dir, tmp_path, image_file): data_dir = tmp_path / "data_dir_with_metadata_in_different_format" data_dir.mkdir(parents=True, exist_ok=True) shutil.copyfile(image_file, data_dir / "image_rgb.jpg") image_metadata_filename_jsonl = data_dir / "metadata.jsonl" image_metadata_jsonl = textwrap.dedent( """\ {"file_name": "image_rgb.jpg", "caption": "Nice image"} """ ) with open(image_metadata_filename_jsonl, "w", encoding="utf-8") as f: f.write(image_metadata_jsonl) image_metadata_filename_csv = data_dir / "metadata.csv" image_metadata_csv = textwrap.dedent( """\ file_name,caption image_rgb.jpg,Nice image """ ) with open(image_metadata_filename_csv, "w", encoding="utf-8") as f: f.write(image_metadata_csv) data_files_with_bad_metadata = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) imagefolder = ImageFolder(data_files=data_files_with_bad_metadata, cache_dir=cache_dir) with pytest.raises(ValueError) as exc_info: imagefolder.download_and_prepare() assert "metadata files with different extensions" in str(exc_info.value)
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/packaged_modules/test_json.py
import textwrap import pyarrow as pa import pytest from datasets import Features, Value from datasets.packaged_modules.json.json import Json @pytest.fixture def jsonl_file(tmp_path): filename = tmp_path / "file.jsonl" data = textwrap.dedent( """\ {"col_1": -1} {"col_1": 1, "col_2": 2} {"col_1": 10, "col_2": 20} """ ) with open(filename, "w") as f: f.write(data) return str(filename) @pytest.fixture def jsonl_file_utf16_encoded(tmp_path): filename = tmp_path / "file_utf16_encoded.jsonl" data = textwrap.dedent( """\ {"col_1": -1} {"col_1": 1, "col_2": 2} {"col_1": 10, "col_2": 20} """ ) with open(filename, "w", encoding="utf-16") as f: f.write(data) return str(filename) @pytest.fixture def json_file_with_list_of_dicts(tmp_path): filename = tmp_path / "file_with_list_of_dicts.json" data = textwrap.dedent( """\ [ {"col_1": -1}, {"col_1": 1, "col_2": 2}, {"col_1": 10, "col_2": 20} ] """ ) with open(filename, "w") as f: f.write(data) return str(filename) @pytest.fixture def json_file_with_list_of_dicts_field(tmp_path): filename = tmp_path / "file_with_list_of_dicts_field.json" data = textwrap.dedent( """\ { "field1": 1, "field2": "aabb", "field3": [ {"col_1": -1}, {"col_1": 1, "col_2": 2}, {"col_1": 10, "col_2": 20} ] } """ ) with open(filename, "w") as f: f.write(data) return str(filename) @pytest.mark.parametrize( "file_fixture, config_kwargs", [ ("jsonl_file", {}), ("jsonl_file_utf16_encoded", {"encoding": "utf-16"}), ("json_file_with_list_of_dicts", {}), ("json_file_with_list_of_dicts_field", {"field": "field3"}), ], ) def test_json_generate_tables(file_fixture, config_kwargs, request): json = Json(**config_kwargs) generator = json._generate_tables([[request.getfixturevalue(file_fixture)]]) pa_table = pa.concat_tables([table for _, table in generator]) assert pa_table.to_pydict() == {"col_1": [-1, 1, 10], "col_2": [None, 2, 20]} @pytest.mark.parametrize( "file_fixture, config_kwargs", [ ( "jsonl_file", {"features": Features({"col_1": Value("int64"), "col_2": Value("int64"), "missing_col": Value("string")})}, ), ( "json_file_with_list_of_dicts", {"features": Features({"col_1": Value("int64"), "col_2": Value("int64"), "missing_col": Value("string")})}, ), ( "json_file_with_list_of_dicts_field", { "field": "field3", "features": Features( {"col_1": Value("int64"), "col_2": Value("int64"), "missing_col": Value("string")} ), }, ), ], ) def test_json_generate_tables_with_missing_features(file_fixture, config_kwargs, request): json = Json(**config_kwargs) generator = json._generate_tables([[request.getfixturevalue(file_fixture)]]) pa_table = pa.concat_tables([table for _, table in generator]) assert pa_table.to_pydict() == {"col_1": [-1, 1, 10], "col_2": [None, 2, 20], "missing_col": [None, None, None]}
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/packaged_modules/test_spark.py
from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def _get_expected_row_ids_and_row_dicts_for_partition_order(df, partition_order): expected_row_ids_and_row_dicts = [] for part_id in partition_order: partition = df.where(f"SPARK_PARTITION_ID() = {part_id}").collect() for row_idx, row in enumerate(partition): expected_row_ids_and_row_dicts.append((f"{part_id}_{row_idx}", row.asDict())) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def test_repartition_df_if_needed(): spark = pyspark.sql.SparkSession.builder.master("local[*]").appName("pyspark").getOrCreate() df = spark.range(100).repartition(1) spark_builder = Spark(df) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=16) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 50 @require_not_windows @require_dill_gt_0_3_2 def test_generate_iterable_examples(): spark = pyspark.sql.SparkSession.builder.master("local[*]").appName("pyspark").getOrCreate() df = spark.range(10).repartition(2) partition_order = [1, 0] generate_fn = _generate_iterable_examples(df, partition_order) # Reverse the partitions. expected_row_ids_and_row_dicts = _get_expected_row_ids_and_row_dicts_for_partition_order(df, partition_order) for i, (row_id, row_dict) in enumerate(generate_fn()): expected_row_id, expected_row_dict = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def test_spark_examples_iterable(): spark = pyspark.sql.SparkSession.builder.master("local[*]").appName("pyspark").getOrCreate() df = spark.range(10).repartition(1) it = SparkExamplesIterable(df) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(it): assert row_id == f"0_{i}" assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def test_spark_examples_iterable_shuffle(): spark = pyspark.sql.SparkSession.builder.master("local[*]").appName("pyspark").getOrCreate() df = spark.range(30).repartition(3) # Mock the generator so that shuffle reverses the partition indices. with patch("numpy.random.Generator") as generator_mock: generator_mock.shuffle.side_effect = lambda x: x.reverse() expected_row_ids_and_row_dicts = _get_expected_row_ids_and_row_dicts_for_partition_order(df, [2, 1, 0]) shuffled_it = SparkExamplesIterable(df).shuffle_data_sources(generator_mock) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(shuffled_it): expected_row_id, expected_row_dict = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def test_spark_examples_iterable_shard(): spark = pyspark.sql.SparkSession.builder.master("local[*]").appName("pyspark").getOrCreate() df = spark.range(20).repartition(4) # Partitions 0 and 2 shard_it_1 = SparkExamplesIterable(df).shard_data_sources(worker_id=0, num_workers=2) assert shard_it_1.n_shards == 2 expected_row_ids_and_row_dicts_1 = _get_expected_row_ids_and_row_dicts_for_partition_order(df, [0, 2]) for i, (row_id, row_dict) in enumerate(shard_it_1): expected_row_id, expected_row_dict = expected_row_ids_and_row_dicts_1[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 shard_it_2 = SparkExamplesIterable(df).shard_data_sources(worker_id=1, num_workers=2) assert shard_it_2.n_shards == 2 expected_row_ids_and_row_dicts_2 = _get_expected_row_ids_and_row_dicts_for_partition_order(df, [1, 3]) for i, (row_id, row_dict) in enumerate(shard_it_2): expected_row_id, expected_row_dict = expected_row_ids_and_row_dicts_2[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def test_repartition_df_if_needed_max_num_df_rows(): spark = pyspark.sql.SparkSession.builder.master("local[*]").appName("pyspark").getOrCreate() df = spark.range(100).repartition(1) spark_builder = Spark(df) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 100
0
hf_public_repos/datasets/tests
hf_public_repos/datasets/tests/packaged_modules/test_text.py
import textwrap import pyarrow as pa import pytest from datasets import Features, Image from datasets.packaged_modules.text.text import Text from ..utils import require_pil @pytest.fixture def text_file(tmp_path): filename = tmp_path / "text.txt" data = textwrap.dedent( """\ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Second paragraph: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. """ ) with open(filename, "w", encoding="utf-8") as f: f.write(data) return str(filename) @pytest.fixture def text_file_with_image(tmp_path, image_file): filename = tmp_path / "text_with_image.txt" with open(filename, "w", encoding="utf-8") as f: f.write(image_file) return str(filename) @pytest.mark.parametrize("keep_linebreaks", [True, False]) def test_text_linebreaks(text_file, keep_linebreaks): with open(text_file, encoding="utf-8") as f: expected_content = f.read().splitlines(keepends=keep_linebreaks) text = Text(keep_linebreaks=keep_linebreaks, encoding="utf-8") generator = text._generate_tables([[text_file]]) generated_content = pa.concat_tables([table for _, table in generator]).to_pydict()["text"] assert generated_content == expected_content @require_pil def test_text_cast_image(text_file_with_image): with open(text_file_with_image, encoding="utf-8") as f: image_file = f.read().splitlines()[0] text = Text(encoding="utf-8", features=Features({"image": Image()})) generator = text._generate_tables([[text_file_with_image]]) pa_table = pa.concat_tables([table for _, table in generator]) assert pa_table.schema.field("image").type == Image()() generated_content = pa_table.to_pydict()["image"] assert generated_content == [{"path": image_file, "bytes": None}] @pytest.mark.parametrize("sample_by", ["line", "paragraph", "document"]) def test_text_sample_by(sample_by, text_file): with open(text_file, encoding="utf-8") as f: expected_content = f.read() if sample_by == "line": expected_content = expected_content.splitlines() elif sample_by == "paragraph": expected_content = expected_content.split("\n\n") elif sample_by == "document": expected_content = [expected_content] text = Text(sample_by=sample_by, encoding="utf-8", chunksize=100) generator = text._generate_tables([[text_file]]) generated_content = pa.concat_tables([table for _, table in generator]).to_pydict()["text"] assert generated_content == expected_content
0
hf_public_repos/datasets
hf_public_repos/datasets/utils/release.py
# Copyright 2021 The HuggingFace Team. All rights reserved. # # 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. import argparse import re import packaging.version REPLACE_PATTERNS = { "init": (re.compile(r'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'), "setup": (re.compile(r'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), r'\1version="VERSION",'), } REPLACE_FILES = { "init": "src/datasets/__init__.py", "setup": "setup.py", } def update_version_in_file(fname, version, pattern): """Update the version in one file using a specific pattern.""" with open(fname, "r", encoding="utf-8", newline="\n") as f: code = f.read() re_pattern, replace = REPLACE_PATTERNS[pattern] replace = replace.replace("VERSION", version) code = re_pattern.sub(replace, code) with open(fname, "w", encoding="utf-8", newline="\n") as f: f.write(code) def global_version_update(version): """Update the version in all needed files.""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(fname, version, pattern) def get_version(): """Reads the current version in the __init__.""" with open(REPLACE_FILES["init"], "r") as f: code = f.read() default_version = REPLACE_PATTERNS["init"][0].search(code).groups()[0] return packaging.version.parse(default_version) def pre_release_work(patch=False): """Do all the necessary pre-release steps.""" # First let's get the default version: base version if we are in dev, bump minor otherwise. default_version = get_version() if patch and default_version.is_devrelease: raise ValueError("Can't create a patch version from the dev branch, checkout a released version!") if default_version.is_devrelease: default_version = default_version.base_version elif patch: default_version = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}" else: default_version = f"{default_version.major}.{default_version.minor + 1}.0" # Now let's ask nicely if that's the right one. version = input(f"Which version are you releasing? [{default_version}]") if len(version) == 0: version = default_version print(f"Updating version to {version}.") global_version_update(version) def post_release_work(): """Do all the necesarry post-release steps.""" # First let's get the current version current_version = get_version() dev_version = f"{current_version.major}.{current_version.minor + 1}.0.dev0" current_version = current_version.base_version # Check with the user we got that right. version = input(f"Which version are we developing now? [{dev_version}]") if len(version) == 0: version = dev_version print(f"Updating version to {version}.") global_version_update(version) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--post_release", action="store_true", help="Whether or not this is post release.") parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.") args = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("Nothing to do after a patch :-)") else: post_release_work()
0
hf_public_repos
hf_public_repos/tokenizers/CITATION.cff
# This CITATION.cff file was generated with cffinit. # Visit https://bit.ly/cffinit to generate yours today! cff-version: 1.2.0 title: HuggingFace's Tokenizers message: >- Fast State-of-the-Art Tokenizers optimized for Research and Production. type: software authors: - given-names: Anthony family-names: Moi email: m.anthony.moi@gmail.com affiliation: HuggingFace - given-names: Nicolas family-names: Patry affiliation: HuggingFace repository-code: 'https://github.com/huggingface/tokenizers' url: 'https://github.com/huggingface/tokenizers' repository: 'https://huggingface.co' abstract: >- Fast State-of-the-Art Tokenizers optimized for Research and Production. keywords: - Rust - Tokenizer - NLP license: Apache-2.0 commit: 37372b6 version: 0.13.3 date-released: '2023-04-05'
0
hf_public_repos
hf_public_repos/tokenizers/LICENSE
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 [yyyy] [name of copyright owner] 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.
0
hf_public_repos
hf_public_repos/tokenizers/README.md
<p align="center"> <br> <img src="https://huggingface.co/landing/assets/tokenizers/tokenizers-logo.png" width="600"/> <br> <p> <p align="center"> <img alt="Build" src="https://github.com/huggingface/tokenizers/workflows/Rust/badge.svg"> <a href="https://github.com/huggingface/tokenizers/blob/main/LICENSE"> <img alt="GitHub" src="https://img.shields.io/github/license/huggingface/tokenizers.svg?color=blue&cachedrop"> </a> <a href="https://pepy.tech/project/tokenizers"> <img src="https://pepy.tech/badge/tokenizers/week" /> </a> </p> Provides an implementation of today's most used tokenizers, with a focus on performance and versatility. ## Main features: - Train new vocabularies and tokenize, using today's most used tokenizers. - Extremely fast (both training and tokenization), thanks to the Rust implementation. Takes less than 20 seconds to tokenize a GB of text on a server's CPU. - Easy to use, but also extremely versatile. - Designed for research and production. - Normalization comes with alignments tracking. It's always possible to get the part of the original sentence that corresponds to a given token. - Does all the pre-processing: Truncate, Pad, add the special tokens your model needs. ## Bindings We provide bindings to the following languages (more to come!): - [Rust](https://github.com/huggingface/tokenizers/tree/main/tokenizers) (Original implementation) - [Python](https://github.com/huggingface/tokenizers/tree/main/bindings/python) - [Node.js](https://github.com/huggingface/tokenizers/tree/main/bindings/node) - [Ruby](https://github.com/ankane/tokenizers-ruby) (Contributed by @ankane, external repo) ## Quick example using Python: Choose your model between Byte-Pair Encoding, WordPiece or Unigram and instantiate a tokenizer: ```python from tokenizers import Tokenizer from tokenizers.models import BPE tokenizer = Tokenizer(BPE()) ``` You can customize how pre-tokenization (e.g., splitting into words) is done: ```python from tokenizers.pre_tokenizers import Whitespace tokenizer.pre_tokenizer = Whitespace() ``` Then training your tokenizer on a set of files just takes two lines of codes: ```python from tokenizers.trainers import BpeTrainer trainer = BpeTrainer(special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"]) tokenizer.train(files=["wiki.train.raw", "wiki.valid.raw", "wiki.test.raw"], trainer=trainer) ``` Once your tokenizer is trained, encode any text with just one line: ```python output = tokenizer.encode("Hello, y'all! How are you 😁 ?") print(output.tokens) # ["Hello", ",", "y", "'", "all", "!", "How", "are", "you", "[UNK]", "?"] ``` Check the [python documentation](https://huggingface.co/docs/tokenizers/index) or the [python quicktour](https://huggingface.co/docs/tokenizers/python/latest/quicktour.html) to learn more!
0
hf_public_repos
hf_public_repos/tokenizers/RELEASE.md
## How to release # Before the release Simple checklist on how to make releases for `tokenizers`. - Freeze `master` branch. - Run all tests (Check CI has properly run) - If any significant work, check benchmarks: - `cd tokenizers && cargo bench` (needs to be run on latest release tag to measure difference if it's your first time) - Run all `transformers` tests. (`transformers` is a big user of `tokenizers` we need to make sure we don't break it, testing is one way to make sure nothing unforeseen has been done.) - Run all fast tests at the VERY least (not just the tokenization tests). (`RUN_PIPELINE_TESTS=1 CUDA_VISIBLE_DEVICES=-1 pytest -sv tests/`) - When all *fast* tests work, then we can also (it's recommended) run the whole `transformers` test suite. - Rebase this [PR](https://github.com/huggingface/transformers/pull/16708). This will create new docker images ready to run the tests suites with `tokenizers` from the main branch. - Wait for actions to finish - Rebase this [PR](https://github.com/huggingface/transformers/pull/16712) This will run the actual full test suite. - Check the results. - **If any breaking change has been done**, make sure the version can safely be increased for transformers users (`tokenizers` version need to make sure users don't upgrade before `transformers` has). [link](https://github.com/huggingface/transformers/blob/main/setup.py#L154) For instance `tokenizers>=0.10,<0.11` so we can safely upgrade to `0.11` without impacting current users - Then start a new PR containing all desired code changes from the following steps. - You will `Create release` after the code modifications are on `master`. # Rust - `tokenizers` (rust, python & node) versions don't have to be in sync but it's very common to release for all versions at once for new features. - Edit `Cargo.toml` to reflect new version - Edit `CHANGELOG.md`: - Add relevant PRs that were added (python PRs do not belong for instance). - Add links at the end of the files. - Go to [Releases](https://github.com/huggingface/tokenizers/releases) - Create new Release: - Mark it as pre-release - Use new version name with a new tag (create on publish) `vX.X.X`. - Copy paste the new part of the `CHANGELOG.md` - ⚠️ Click on `Publish release`. This will start the whole process of building a uploading the new version on `crates.io`, there's no going back after this - Go to the [Actions](https://github.com/huggingface/tokenizers/actions) tab and check everything works smoothly. - If anything fails, you need to fix the CI/CD to make it work again. Since your package was not uploaded to the repository properly, you can try again. # Python - Edit `bindings/python/setup.py` to reflect new version. - Edit `bindings/python/py_src/tokenizers/__init__.py` to reflect new version. - Edit `CHANGELOG.md`: - Add relevant PRs that were added (node PRs do not belong for instance). - Add links at the end of the files. - Go to [Releases](https://github.com/huggingface/tokenizers/releases) - Create new Release: - Mark it as pre-release - Use new version name with a new tag (create on publish) `python-vX.X.X`. - Copy paste the new part of the `CHANGELOG.md` - ⚠️ Click on `Publish release`. This will start the whole process of building a uploading the new version on `pypi`, there's no going back after this - Go to the [Actions](https://github.com/huggingface/tokenizers/actions) tab and check everything works smoothly. - If anything fails, you need to fix the CI/CD to make it work again. Since your package was not uploaded to the repository properly, you can try again. - This CI/CD has 3 distinct builds, `Pypi`(normal), `conda` and `extra`. `Extra` is REALLY slow (~4h), this is normal since it has to rebuild many things, but enables the wheel to be available for old Linuxes # Node - Edit `bindings/node/package.json` to reflect new version. - Edit `CHANGELOG.md`: - Add relevant PRs that were added (python PRs do not belong for instance). - Add links at the end of the files. - Go to [Releases](https://github.com/huggingface/tokenizers/releases) - Create new Release: - Mark it as pre-release - Use new version name with a new tag (create on publish) `node-vX.X.X`. - Copy paste the new part of the `CHANGELOG.md` - ⚠️ Click on `Publish release`. This will start the whole process of building a uploading the new version on `npm`, there's no going back after this - Go to the [Actions](https://github.com/huggingface/tokenizers/actions) tab and check everything works smoothly. - If anything fails, you need to fix the CI/CD to make it work again. Since your package was not uploaded to the repository properly, you can try again. # Testing the CI/CD for release If you want to make modifications to the CI/CD of the release GH actions, you need to : - **Comment the part that uploads the artifacts** to `crates.io`, `PyPi` or `npm`. - Change the trigger mecanism so it can trigger every time you push to your branch. - Keep pushing your changes until the artifacts are properly created.
0
hf_public_repos/tokenizers/bindings
hf_public_repos/tokenizers/bindings/node/.eslintignore
node_modules dist coverage
0
hf_public_repos/tokenizers/bindings
hf_public_repos/tokenizers/bindings/node/.eslintrc.json
{ "root": true, "env": { "es6": true, "node": true }, "extends": [ "eslint:recommended", "plugin:prettier/recommended" ], "globals": { "Atomics": "readonly", "SharedArrayBuffer": "readonly" }, "parser": "@typescript-eslint/parser", "parserOptions": { "ecmaVersion": 2019, "sourceType": "module" }, "plugins": ["@typescript-eslint", "jest", "prettier", "simple-import-sort"], "rules": { "@typescript-eslint/no-use-before-define": ["error", { "functions": false }], "simple-import-sort/sort": "error" }, "overrides": [ { "files": "**/*.ts", "plugins": ["jsdoc"], "extends": [ "plugin:@typescript-eslint/recommended", "plugin:jest/recommended", "plugin:jest/style", "prettier/@typescript-eslint" ], "rules": { "jsdoc/no-types": "error" } } ] }
0
hf_public_repos/tokenizers/bindings
hf_public_repos/tokenizers/bindings/node/.prettierrc.json
{ "$schema": "http://json.schemastore.org/prettierrc", "printWidth": 90 }
0
hf_public_repos/tokenizers/bindings
hf_public_repos/tokenizers/bindings/node/CHANGELOG.md
## [0.13.2] - Python only chnages. ## [0.13.1] - [#1072] Fixing Roberta type ids. ## [0.13.0] - [#1008] `Decoder` is now a composable trait, but without being backward incompatible - [#1047, #1051, #1052] `Processor` is now a composable trait, but without being backward incompatible ## [0.12.1] - [#938] **Reverted breaking change**. https://github.com/huggingface/transformers/issues/16520 ## [0.12.0] YANKED Bump minor version because of a breaking change. Using `0.12` to match other bindings. - [#938] [REVERTED IN 0.12.1] **Breaking change**. Decoder trait is modified to be composable. This is only breaking if you are using decoders on their own. tokenizers should be error free. - [#939] Making the regex in `ByteLevel` pre_tokenizer optional (necessary for BigScience) - [#952] Fixed the vocabulary size of UnigramTrainer output (to respect added tokens) - [#954] Fixed not being able to save vocabularies with holes in vocab (ConvBert). Yell warnings instead, but stop panicking. - [#961] Added link for Ruby port of `tokenizers` # [0.8.0](https://github.com/huggingface/tokenizers/compare/node-v0.7.0...node-v0.8.0) (2021-09-02) ### BREACKING CHANGES - Many improvements on the Trainer ([#519](https://github.com/huggingface/tokenizers/pull/519)). The files must now be provided first when calling `tokenizer.train(files, trainer)`. ### Features - Adding the `TemplateProcessing` - Add `WordLevel` and `Unigram` models ([#490](https://github.com/huggingface/tokenizers/pull/490)) - Add `nmtNormalizer` and `precompiledNormalizer` normalizers ([#490](https://github.com/huggingface/tokenizers/pull/490)) - Add `templateProcessing` post-processor ([#490](https://github.com/huggingface/tokenizers/pull/490)) - Add `digitsPreTokenizer` pre-tokenizer ([#490](https://github.com/huggingface/tokenizers/pull/490)) - Add support for mapping to sequences ([#506](https://github.com/huggingface/tokenizers/pull/506)) - Add `splitPreTokenizer` pre-tokenizer ([#542](https://github.com/huggingface/tokenizers/pull/542)) - Add `behavior` option to the `punctuationPreTokenizer` ([#657](https://github.com/huggingface/tokenizers/pull/657)) - Add the ability to load tokenizers from the Hugging Face Hub using `fromPretrained` ([#780](https://github.com/huggingface/tokenizers/pull/780)) ### Fixes - Fix a bug where long tokenizer.json files would be incorrectly deserialized ([#459](https://github.com/huggingface/tokenizers/pull/459)) - Fix RobertaProcessing deserialization in PostProcessorWrapper ([#464](https://github.com/huggingface/tokenizers/pull/464)) # [0.7.0](https://github.com/huggingface/tokenizers/compare/node-v0.6.2...node-v0.7.0) (2020-07-01) ### BREAKING CHANGES - `robertaProcessing` now handles trimming the offsets (activated by default) ([#236](https://github.com/huggingface/tokenizers/pull/236)) - `charToTokenOffsets`, `charToWordOffsets` and `tokenToWordOffsets` helper functions on `Encoding` instances are removed and replaced by new `wordToTokens`, `wordToChars`, `tokenToChars`, `tokenToWord` and `charToWord` methods ([#234](https://github.com/huggingface/tokenizers/pull/234)) - `encode` and `encodeBatch` methods on a tokenizer now handle pre-tokenized inputs and have their signatures changed ([#249](https://github.com/huggingface/tokenizers/pull/249)). In addition: - `encodeTokenized`, `encodeTokenizedBatch` methods are therefore removed - `InputSequence`, `EncodeInput` and `EncodeOptions` types are added - Improve management of the additional vocabulary ([#309](https://github.com/huggingface/tokenizers/pull/309)): - New parameter `normalized` in `AddedToken` options, controlling whether a token should be extracted from the normalized version of the input text - The `AddedToken` constructor now takes a `special` boolean as second parameter to indicate if the token is special (in this case it won't be normalized) ### Features - Serialization of a `Tokenizer` and all its parts (`PreTokenizer`, `Normalizer`, ...). This adds some methods to easily save/load an entire tokenizer: new static methods `fromString` / `fromFile`, and instance methods `save` / `toString` on `BaseTokenizer` ([#272](https://github.com/huggingface/tokenizers/pull/272)) - New `padToMultipleOf` parameter for `PaddingOptions`, to pad to a multiple of a specified value ([#289](https://github.com/huggingface/tokenizers/pull/289)) - Improved errors generated during truncation when the provided max length is too low ([02cc977](https://github.com/huggingface/tokenizers/commit/02cc97756ffb9193b5d6d8dfcdeb7bf08adf2516)) - Improve BPE training speeds, by reading files sequentially, but parallelizing the processing of each file ([#276](https://github.com/huggingface/tokenizers/pull/276)) - Use `onig` for byte-level pre-tokenization to remove all the differences with the original implementation from GPT-2 ([#280](https://github.com/huggingface/tokenizers/pull/280)) ### Fixes - Fix various crash when training a BPE model ([#286](https://github.com/huggingface/tokenizers/pull/286)) - Fix a few bugs related to additional vocabulary/tokens ([#309](https://github.com/huggingface/tokenizers/pull/309)) ## [0.6.2](https://github.com/huggingface/tokenizers/compare/node-v0.6.1...node-v0.6.2) (2020-04-13) ### Features - More symbols exposed: `Token`, `BaseTokenizer`, `PaddingConfiguration`, `TruncationConfiguration` ([38d53a7](https://github.com/huggingface/tokenizers/commit/38d53a7b84b2ee86b262eee2de6121351fe03889)) - Expose `setPostProcessor` in `BaseTokenizer` ([38d53a7](https://github.com/huggingface/tokenizers/commit/38d53a7b84b2ee86b262eee2de6121351fe03889)) ### Fixes - Fix the word indexes when there are special tokens ([#226](https://github.com/huggingface/tokenizers/pull/226)) - Fix encoding overflowing offsets ([695ab83](https://github.com/huggingface/tokenizers/commit/695ab8388f5f1a7d63d8aaab9b3762312e0d5ac3)) - Fix Roberta overflowings ([c4ecc6f](https://github.com/huggingface/tokenizers/commit/c4ecc6f7ce7af40c558401a3ec9500732a17f9da)) ## [0.6.1](https://github.com/huggingface/tokenizers/compare/node-v0.6.0...node-v0.6.1) (2020-04-01) ### Fixes - Fix special tokens with wrong id ([b770f36](https://github.com/huggingface/tokenizers/commit/b770f364280af33efeffea8f0003102cda8cf1b7)) - Fix `AddedToken`'s `leftStrip` and `rightStrip` params (thanks @thirdwing) ([85488dd](https://github.com/huggingface/tokenizers/commit/85488dd6330ec7fa64aeb78c1a86b221f77c5ebb)) # [0.6.0](https://github.com/huggingface/tokenizers/compare/node-v0.5.0...node-v0.6.0) (2020-03-30) ### BREAKING CHANGES - The `getOriginalString` method on `Encoding`s has been removed: this brings a reduction of 70% of the memory footprint. You can use the provided new `slice` function as a replacement to get a subpart of a string according to specified indexes while respecting unicode characters. ([#197](https://github.com/huggingface/tokenizers/pull/197)) - The offsets provided on `Encoding` are now relative to the original string, and not the normalized one anymore ([#197](https://github.com/huggingface/tokenizers/pull/197)) - The added tokens given to `addTokens`, `addSpecialTokens` or `train` methods of a tokenizer can now be instances of `AddedToken` to provide more control over these tokens. The support of the `[string, boolean]` format in `addTokens` method is removed. ([#202](https://github.com/huggingface/tokenizers/pull/202)) - The `addSpecialTokens` option for `BertWordpieceTokenizer` has been removed, and must now be passed to `encode` and `encodeBatch` functions ([7dd2400](https://github.com/huggingface/tokenizers/commit/7dd24002148a452f4d9fc55966e181c2dc699203)) ([#193](https://github.com/huggingface/tokenizers/pull/193)) ### Features - `encode` and `encodeBatch` methods on `BaseTokenizer` now take a new optional argument, specifying whether to add the special tokens (activated by default) ([#193](https://github.com/huggingface/tokenizers/pull/193)) - Methods `decode` and `decodeBatch` exposed in `BaseTokenizer` instances ([#184](https://github.com/huggingface/tokenizers/pull/184)) - The `fromFiles` methods for `BPE` and `WordPiece` models are now `async` ([#184](https://github.com/huggingface/tokenizers/pull/184)) - Big improvements in speed for BPE (both training and tokenization) ([#165](https://github.com/huggingface/tokenizers/pull/165)) - `ByteLevel` is also a `PostProcessor` now and handles trimming the offsets if activated. This avoids the unintuitive inclusion of the whitespaces in the produced offsets, even if these whitespaces are part of the actual token. It has been added to `ByteLevelBPETokenizer` but it is off by default. ([#188](https://github.com/huggingface/tokenizers/pull/188)) - New `postProcess`, `encodeTokenized`, `encodeTokenizedBatch` and `normalize` methods on `BaseTokenizer` ([#200](https://github.com/huggingface/tokenizers/pull/200)) ([2aeae55](https://github.com/huggingface/tokenizers/commit/2aeae555e22ac58b11b4956aa3f601bb168e8c3f)) - New `mergeEncodings` static method on `Encoding` class ([#200](https://github.com/huggingface/tokenizers/pull/200)) ([0408567](https://github.com/huggingface/tokenizers/commit/0408567f23d938952f45192a3eff54d48f828882)) - New `wordIndexes` getter and new `charToToken`, `charToTokenOffsets`, `charToWordOffsets` and `tokenToWordOffsets` helper functions on `Encoding` instances ([#200](https://github.com/huggingface/tokenizers/pull/200)) ([ce3cf78](https://github.com/huggingface/tokenizers/commit/ce3cf78ea5423d483895f51f77ff0c7df07f9b0a)) ### Fixes - Fix `longest_first` truncation strategy ([#174](https://github.com/huggingface/tokenizers/issues/174)) - Fix options names in `BPE.fromFiles` ([306f427](https://github.com/huggingface/tokenizers/commit/35540d2e0715e88299f8f04f842e23b5a306f427)) - Actually expose `save` method in `Model` ([ddcf8e8](https://github.com/huggingface/tokenizers/commit/3d143a911bde8d15e1431156fe3cf7676ddcf8e8)) - The errors in async functions are now typed ([7aa6c13](https://github.com/huggingface/tokenizers/commit/4510ea5ce37d84754bb782a99353ac5627aa6c13)) - Trim the decoded string in `bpeDecoder` used by `BPETokenizer` ([#205](https://github.com/huggingface/tokenizers/issues/205)) ([3f4a6b7](https://github.com/huggingface/tokenizers/commit/3f4a6b746b921f339de3279d073b29e019ee2e5a)) # [0.5.0](https://github.com/huggingface/tokenizers/compare/node-v0.4.1...node-v0.5.0) (2020-02-27) ### BREAKING CHANGES - The `Encoding` object now exposes getters instead of `get...` methods (except for `getOriginalString`) ([9179968](https://github.com/huggingface/tokenizers/commit/917996841df2b3385e0212c9d7e9910d4e0d3fbf)) - `BertWordPieceTokenizer` now cleans up some tokenization artifacts by default while decoding ([#145](https://github.com/huggingface/tokenizers/issues/145)) ([#147](https://github.com/huggingface/tokenizers/pull/147)) ### Features - `Encoding` exposes a new `length` property ([9179968](https://github.com/huggingface/tokenizers/commit/917996841df2b3385e0212c9d7e9910d4e0d3fbf)) - Add a new `stripNormalizer` ([#140](https://github.com/huggingface/tokenizers/pull/140)) ([815d743](https://github.com/huggingface/tokenizers/commit/815d743461f9067ab38237862b7be8114d422300)) - `ByteLevelBPETokenizer` and `BPETokenizer` accept more options ([946ac1a](https://github.com/huggingface/tokenizers/commit/946ac1a9517c3090064e9a972ad71a5cf25b7e7f)) - Add `save` method to `Model` class ([aebc97e](https://github.com/huggingface/tokenizers/commit/aebc97eaf34260c9ed7689dd5e087bf8c8af59fc)) - Improved padding performances ([b30be3b](https://github.com/huggingface/tokenizers/commit/b30be3b2bda977b65f9bdb384258829b2bd91e3d)) ([0dc857e](https://github.com/huggingface/tokenizers/commit/0dc857ea8c557532a52628a6bc80141e65e6d974)) ### Fixes - Methods accepting optional arguments now handle explicit `undefined` correctly ([0fe22a7](https://github.com/huggingface/tokenizers/commit/0fe22a7c1c23f8d992f502a3a582e5212b8281ac)) - Special tokens are now declared only if present in the vocabulary ([b70283c](https://github.com/huggingface/tokenizers/commit/b70283c3050056958e8ba020b0386451cc6df80c)) - Add missing mask/padding special tokens in wordpiece tokenizer ([b70283c](https://github.com/huggingface/tokenizers/commit/b70283c3050056958e8ba020b0386451cc6df80c)) - Fix a bug in `ByteLevelBPETokenizer` that caused offsets to be wrong if a char got split up in multiple bytes ([#156](https://github.com/huggingface/tokenizers/pull/156)) ## [0.4.1](https://github.com/huggingface/tokenizers/compare/node-v0.4.0...node-v0.4.1) (2020-02-11) ### Fixes - Fix punctuation in BertWordPieceTokenizer (Thanks to @Mansterteddy with [#134](https://github.com/huggingface/tokenizers/pull/134)) # [0.4.0](https://github.com/huggingface/tokenizers/compare/node-v0.3.1...node-v0.4.0) (2020-02-05) ### BREAKING CHANGES - `getOverflowing()` method on `Encoding` now returns all the overflowing `Encoding`s at once ([#77](https://github.com/huggingface/tokenizers/pull/77)) ([0094393](https://github.com/huggingface/tokenizers/commit/0094393610623bafc269790cd1be81fd1474583a)) ### Features - Add `setTruncation`, `disableTruncation`, `setPadding` and `disablePadding` methods in `Tokenizer` and `BaseTokenizer` ([#109](https://github.com/huggingface/tokenizers/pull/109)) ([78e2690](https://github.com/huggingface/tokenizers/commit/78e26905a735e14e67590cb09ddb42ed141c455b)) - Expose tokenizer / truncation / padding configuration in `BaseTokenizer` ([#126](https://github.com/huggingface/tokenizers/pull/126)) ([cb8585b](https://github.com/huggingface/tokenizers/commit/cb8585bc4eb8037c52049da677e4791857231f03)) - Expose `addTokens`, `addSpecialTokens`, `idToToken` and `tokenToId` in `BaseTokenizer` ([7051480](https://github.com/huggingface/tokenizers/commit/7051480c333f88bef80aa6846b66032a2d47383c)) - Add `getOriginalString()` method on `Encoding` ([a14c633](https://github.com/huggingface/tokenizers/commit/a14c63343b217a2c501359bec52baf717e3a05ef)) - Add `charDelimiterSplitPreTokenizer`: a new `PreTokenizer` that allows splitting sequences on the given delimiter (works like `.split(delimiter)`) ([#114](https://github.com/huggingface/tokenizers/pull/114)) ([6165910](https://github.com/huggingface/tokenizers/commit/6165910ca66b6bfd9fd996aa38c4c0b2b6505953)) - Add `robertaProcessing` as a new `PostProcessor` ([#111](https://github.com/huggingface/tokenizers/pull/111)) ([6524f09](https://github.com/huggingface/tokenizers/commit/6524f09e991c3a52c839d8eb01bfa41e81fde1d1)) ### Fixes - Correctly truncate with `OnlyFirst` and `OnlySecond` strategies ([#108](https://github.com/huggingface/tokenizers/issues/108)) ([6d532fe](https://github.com/huggingface/tokenizers/commit/6d532fedb1d3626328828304a5c39807733d2fa1)) - Fix default special tokens in `BertWordPieceTokenizer` ([10e2d28](https://github.com/huggingface/tokenizers/commit/10e2d286caf517f0977c04cf8e1924aed90403c9)) - Fix return type of `getSpecialTokensMask` on `Encoding` ([9770be5](https://github.com/huggingface/tokenizers/commit/9770be566175dc9c44dd7dcaa00a57d0e4ca632b)) - Actually add special tokens in tokenizers implementations ([acef252](https://github.com/huggingface/tokenizers/commit/acef252dacc43adc414175cfc325668ad1488753)) [#1072]: https://github.com/huggingface/tokenizers/pull/1072 [#956]: https://github.com/huggingface/tokenizers/pull/956 [#1008]: https://github.com/huggingface/tokenizers/pull/1008 [#1009]: https://github.com/huggingface/tokenizers/pull/1009 [#1047]: https://github.com/huggingface/tokenizers/pull/1047 [#1055]: https://github.com/huggingface/tokenizers/pull/1055 [#1051]: https://github.com/huggingface/tokenizers/pull/1051 [#1052]: https://github.com/huggingface/tokenizers/pull/1052 [#938]: https://github.com/huggingface/tokenizers/pull/938 [#939]: https://github.com/huggingface/tokenizers/pull/939 [#952]: https://github.com/huggingface/tokenizers/pull/952 [#954]: https://github.com/huggingface/tokenizers/pull/954 [#962]: https://github.com/huggingface/tokenizers/pull/962 [#961]: https://github.com/huggingface/tokenizers/pull/961 [#960]: https://github.com/huggingface/tokenizers/pull/960
0
hf_public_repos/tokenizers/bindings
hf_public_repos/tokenizers/bindings/node/Makefile
.PHONY: style check-style test DATA_DIR = data dir_guard=@mkdir -p $(@D) # Format source code automatically style: npm run lint # Check the source code is formatted correctly check-style: npm run lint-check TESTS_RESOURCES = $(DATA_DIR)/small.txt $(DATA_DIR)/roberta.json $(DATA_DIR)/tokenizer-wiki.json $(DATA_DIR)/bert-wiki.json # Launch the test suite test: $(TESTS_RESOURCES) npm run test $(DATA_DIR)/big.txt : $(dir_guard) wget https://norvig.com/big.txt -O $@ $(DATA_DIR)/small.txt : $(DATA_DIR)/big.txt head -100 $(DATA_DIR)/big.txt > $@ $(DATA_DIR)/roberta.json : $(dir_guard) wget https://huggingface.co/roberta-large/raw/main/tokenizer.json -O $@ $(DATA_DIR)/tokenizer-wiki.json : $(dir_guard) wget https://s3.amazonaws.com/models.huggingface.co/bert/anthony/doc-quicktour/tokenizer.json -O $@ $(DATA_DIR)/bert-wiki.json : $(dir_guard) wget https://s3.amazonaws.com/models.huggingface.co/bert/anthony/doc-pipeline/tokenizer.json -O $@
0
hf_public_repos/tokenizers/bindings
hf_public_repos/tokenizers/bindings/node/README.md
<p align="center"> <br> <img src="https://huggingface.co/landing/assets/tokenizers/tokenizers-logo.png" width="600"/> <br> <p> <p align="center"> <a href="https://badge.fury.io/js/tokenizers"> <img alt="Build" src="https://badge.fury.io/js/tokenizers.svg"> </a> <a href="https://github.com/huggingface/tokenizers/blob/master/LICENSE"> <img alt="GitHub" src="https://img.shields.io/github/license/huggingface/tokenizers.svg?color=blue"> </a> </p> <br> NodeJS implementation of today's most used tokenizers, with a focus on performance and versatility. Bindings over the [Rust](https://github.com/huggingface/tokenizers/tree/master/tokenizers) implementation. If you are interested in the High-level design, you can go check it there. ## Main features - Train new vocabularies and tokenize using 4 pre-made tokenizers (Bert WordPiece and the 3 most common BPE versions). - Extremely fast (both training and tokenization), thanks to the Rust implementation. Takes less than 20 seconds to tokenize a GB of text on a server's CPU. - Easy to use, but also extremely versatile. - Designed for research and production. - Normalization comes with alignments tracking. It's always possible to get the part of the original sentence that corresponds to a given token. - Does all the pre-processing: Truncate, Pad, add the special tokens your model needs. ## Installation ```bash npm install tokenizers@latest ``` ## Basic example ```ts import { BertWordPieceTokenizer } from "tokenizers"; const wordPieceTokenizer = await BertWordPieceTokenizer.fromOptions({ vocabFile: "./vocab.txt" }); const wpEncoded = await wordPieceTokenizer.encode("Who is John?", "John is a teacher"); console.log(wpEncoded.length); console.log(wpEncoded.tokens); console.log(wpEncoded.ids); console.log(wpEncoded.attentionMask); console.log(wpEncoded.offsets); console.log(wpEncoded.overflowing); console.log(wpEncoded.specialTokensMask); console.log(wpEncoded.typeIds); console.log(wpEncoded.wordIndexes); ``` ## Provided Tokenizers - `BPETokenizer`: The original BPE - `ByteLevelBPETokenizer`: The byte level version of the BPE - `SentencePieceBPETokenizer`: A BPE implementation compatible with the one used by SentencePiece - `BertWordPieceTokenizer`: The famous Bert tokenizer, using WordPiece ## License [Apache License 2.0](../../LICENSE)
0
hf_public_repos/tokenizers/bindings
hf_public_repos/tokenizers/bindings/node/build.js
#!/usr/bin/env node /** * Inspired by https://github.com/IronCoreLabs/recrypt-node-binding * ================================== * * This script is responsible for compiling and building the NPM release bundle for this repo. The following steps are taken: * * + Clean up any existing Rust builds by running `cargo clean`. * + Run `cargo update` to make sure all dependencies are available. * + Compile rust code into index.node file. * + Run unit tests to ensure the library is in good shape for publishing. * + Move all expected content into a `dist` directory. * + Generate a binary distribution in `bin-package`. * + Do a dry run of npm publishing via irish-pub or perform an actual publish step if `--publish` option is provided. */ const fs = require("fs"); const path = require("path"); const shell = require("shelljs"); const distPath = "./dist"; // Fail this script if any of these commands fail shell.set("-e"); // Ensure that our directory is set to the root of the repo const rootDirectory = path.dirname(process.argv[1]); shell.cd(rootDirectory); run() // Prevent "unhandledRejection" events, allowing to actually exit with error .catch(() => process.exit(1)); /***************************************/ async function run() { const arg = process.argv.slice(2)[0]; switch (arg) { case "--all": buildRust(); buildTs(); break; case "--rust": buildRust(); break; case "--typescript": buildTs(); break; case "--package-rust": buildRust(); await packageRust(); break; case "--npm-publish": buildTs(); npmPublish(); break; default: shell.echo("No arg provided, doing nothing..."); break; } } function buildRust() { shell.echo("BUILDING RUST..."); // Cleanup the previous build, if it exists shell.rm("-rf", "./bin-package"); shell.rm("-rf", "./build"); // Cleanup any previous Rust builds, update deps, and compile shell.exec("npm ci --ignore-scripts"); shell.exec("npm run clean-rs"); shell.pushd("./native"); shell.exec("cargo update"); shell.popd(); shell.exec("npm run compile"); shell.echo("BUILDING RUST COMPLETE..."); } async function packageRust() { shell.echo("PACKAGING RUST..."); shell.mkdir("./bin-package"); shell.cp("./native/index.node", "./bin-package"); shell.exec("npm run package"); const version = JSON.parse(await fs.promises.readFile("./package.json")).version; const tarPath = `build/stage/${version}`; const tgz = (await fs.promises.readdir(tarPath)).find(f => f.endsWith(".tar.gz")); shell.cp(`${tarPath}/${tgz}`, "./bin-package/"); shell.echo("PACKAGING RUST COMPLETE..."); } function buildTs() { shell.echo("BUILDING TS..."); // Cleanup the previous build, if it exists shell.rm("-rf", distPath); shell.exec("npm ci --ignore-scripts"); shell.mkdir(distPath); shell.exec("npx tsc -p tsconfig.prod.json"); shell.echo("BUILDING TS COMPLETE..."); } async function npmPublish() { shell.echo("PUBLISHING ON NPM..."); shell.cp("-ur", ["lib/bindings/**/*.{js,d.ts}"], `${distPath}/bindings/`); shell.mv([`${distPath}/bindings/native.prod.js`], [`${distPath}/bindings/native.js`]); // shell.rm("-r", [`${distPath}/**/*.test.ts`]); // No more remaining *.test.ts files for now at this step shell.cp("-r", ["package.json", "README.md", "../../LICENSE"], distPath); // Add a NPM install script to the package.json that we push to NPM so that when consumers pull it down it // runs the expected node-pre-gyp step. const npmPackageJson = require(`${distPath}/package.json`); npmPackageJson.scripts.install = "node-pre-gyp install"; npmPackageJson.main = "./index.js"; npmPackageJson.types = "./index.d.ts"; await fs.promises.writeFile( `${distPath}/package.json`, JSON.stringify(npmPackageJson, null, 2) ); shell.exec(`npm publish ${distPath} --access public`); shell.echo("PUBLISHING ON NPM COMPLETE..."); }
0
hf_public_repos/tokenizers/bindings
hf_public_repos/tokenizers/bindings/node/jest.config.js
/* eslint-disable prettier/prettier */ // For a detailed explanation regarding each configuration property, visit: // https://jestjs.io/docs/en/configuration.html module.exports = { // All imported modules in your tests should be mocked automatically // automock: false, // Stop running tests after `n` failures // bail: 0, // Respect "browser" field in package.json when resolving modules // browser: false, // The directory where Jest should store its cached dependency information // cacheDirectory: "/private/var/folders/y_/n6h0fkqn3m57bg_ktk25j7rm0000gn/T/jest_dx", // Automatically clear mock calls and instances between every test // clearMocks: false, // Indicates whether the coverage information should be collected while executing the test // collectCoverage: false, // An array of glob patterns indicating a set of files for which coverage information should be collected // collectCoverageFrom: null, // The directory where Jest should output its coverage files // coverageDirectory: null, // An array of regexp pattern strings used to skip coverage collection // coveragePathIgnorePatterns: [ // "/node_modules/" // ], // A list of reporter names that Jest uses when writing coverage reports // coverageReporters: [ // "json", // "text", // "lcov", // "clover" // ], // An object that configures minimum threshold enforcement for coverage results // coverageThreshold: null, // A path to a custom dependency extractor // dependencyExtractor: null, // Make calling deprecated APIs throw helpful error messages // errorOnDeprecated: false, // Force coverage collection from ignored files using an array of glob patterns // forceCoverageMatch: [], // A path to a module which exports an async function that is triggered once before all test suites // globalSetup: null, // A path to a module which exports an async function that is triggered once after all test suites // globalTeardown: null, // A set of global variables that need to be available in all test environments // globals: {}, // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. // maxWorkers: "50%", // An array of directory names to be searched recursively up from the requiring module's location // moduleDirectories: [ // "node_modules" // ], // An array of file extensions your modules use // moduleFileExtensions: [ // "js", // "json", // "jsx", // "ts", // "tsx", // "node" // ], // A map from regular expressions to module names that allow to stub out resources with a single module // moduleNameMapper: {}, // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader // modulePathIgnorePatterns: [], // Activates notifications for test results // notify: false, // An enum that specifies notification mode. Requires { notify: true } // notifyMode: "failure-change", // A preset that is used as a base for Jest's configuration preset: "ts-jest", // Run tests from one or more projects // projects: null, // Use this configuration option to add custom reporters to Jest // reporters: undefined, // Automatically reset mock state between every test // resetMocks: false, // Reset the module registry before running each individual test // resetModules: false, // A path to a custom resolver // resolver: null, // Automatically restore mock state between every test // restoreMocks: false, // The root directory that Jest should scan for tests and modules within // rootDir: null, // A list of paths to directories that Jest should use to search for files in // roots: [ // "<rootDir>" // ], // Allows you to use a custom runner instead of Jest's default test runner // runner: "jest-runner", // The paths to modules that run some code to configure or set up the testing environment before each test // setupFiles: [], // A list of paths to modules that run some code to configure or set up the testing framework before each test // setupFilesAfterEnv: [], // A list of paths to snapshot serializer modules Jest should use for snapshot testing // snapshotSerializers: [], // The test environment that will be used for testing testEnvironment: "node", // Options that will be passed to the testEnvironment // testEnvironmentOptions: {}, // Adds a location field to test results // testLocationInResults: false, // The glob patterns Jest uses to detect test files // testMatch: [ // "**/__tests__/**/*.[jt]s?(x)", // "**/?(*.)+(spec|test).[tj]s?(x)" // ], // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped testPathIgnorePatterns: [ "/node_modules/", "/dist/" ], // The regexp pattern or array of patterns that Jest uses to detect test files // testRegex: [], // This option allows the use of a custom results processor // testResultsProcessor: null, // This option allows use of a custom test runner // testRunner: "jasmine2", // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href // testURL: "http://localhost", // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" // timers: "real", // A map from regular expressions to paths to transformers // transform: null, // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation // transformIgnorePatterns: [ // "/node_modules/" // ], // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them // unmockedModulePathPatterns: undefined, // Indicates whether each individual test should be reported during the run // verbose: null, // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode watchPathIgnorePatterns: [ "<rootDir>/node_modules/", "<rootDir>/native/", "<rootDir>/dist/", "<rootDir>/build/" ], // Whether to use watchman for file crawling // watchman: true, };
0
hf_public_repos/tokenizers/bindings
hf_public_repos/tokenizers/bindings/node/package-lock.json
{ "name": "tokenizers", "version": "0.13.3", "lockfileVersion": 1, "requires": true, "dependencies": { "@babel/code-frame": { "version": "7.12.11", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", "integrity": "sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==", "dev": true, "requires": { "@babel/highlight": "^7.10.4" } }, "@babel/compat-data": { "version": "7.15.0", "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.15.0.tgz", "integrity": "sha512-0NqAC1IJE0S0+lL1SWFMxMkz1pKCNCjI4tr2Zx4LJSXxCLAdr6KyArnY+sno5m3yH9g737ygOyPABDsnXkpxiA==", "dev": true }, "@babel/core": { "version": "7.15.0", "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.15.0.tgz", "integrity": "sha512-tXtmTminrze5HEUPn/a0JtOzzfp0nk+UEXQ/tqIJo3WDGypl/2OFQEMll/zSFU8f/lfmfLXvTaORHF3cfXIQMw==", "dev": true, "requires": { "@babel/code-frame": "^7.14.5", "@babel/generator": "^7.15.0", "@babel/helper-compilation-targets": "^7.15.0", "@babel/helper-module-transforms": "^7.15.0", "@babel/helpers": "^7.14.8", "@babel/parser": "^7.15.0", "@babel/template": "^7.14.5", "@babel/traverse": "^7.15.0", "@babel/types": "^7.15.0", "convert-source-map": "^1.7.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.1.2", "semver": "^6.3.0", "source-map": "^0.5.0" }, "dependencies": { "@babel/code-frame": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.14.5.tgz", "integrity": "sha512-9pzDqyc6OLDaqe+zbACgFkb6fKMNG6CObKpnYXChRsvYGyEdc7CA2BaqeOM+vOtCS5ndmJicPJhKAwYRI6UfFw==", "dev": true, "requires": { "@babel/highlight": "^7.14.5" } }, "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", "dev": true, "requires": { "ms": "2.1.2" } }, "semver": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", "dev": true }, "source-map": { "version": "0.5.7", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", "dev": true } } }, "@babel/generator": { "version": "7.15.0", "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.15.0.tgz", "integrity": "sha512-eKl4XdMrbpYvuB505KTta4AV9g+wWzmVBW69tX0H2NwKVKd2YJbKgyK6M8j/rgLbmHOYJn6rUklV677nOyJrEQ==", "dev": true, "requires": { "@babel/types": "^7.15.0", "jsesc": "^2.5.1", "source-map": "^0.5.0" }, "dependencies": { "source-map": { "version": "0.5.7", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", "dev": true } } }, "@babel/helper-compilation-targets": { "version": "7.15.0", "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.15.0.tgz", "integrity": "sha512-h+/9t0ncd4jfZ8wsdAsoIxSa61qhBYlycXiHWqJaQBCXAhDCMbPRSMTGnZIkkmt1u4ag+UQmuqcILwqKzZ4N2A==", "dev": true, "requires": { "@babel/compat-data": "^7.15.0", "@babel/helper-validator-option": "^7.14.5", "browserslist": "^4.16.6", "semver": "^6.3.0" }, "dependencies": { "semver": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", "dev": true } } }, "@babel/helper-function-name": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.14.5.tgz", "integrity": "sha512-Gjna0AsXWfFvrAuX+VKcN/aNNWonizBj39yGwUzVDVTlMYJMK2Wp6xdpy72mfArFq5uK+NOuexfzZlzI1z9+AQ==", "dev": true, "requires": { "@babel/helper-get-function-arity": "^7.14.5", "@babel/template": "^7.14.5", "@babel/types": "^7.14.5" } }, "@babel/helper-get-function-arity": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.14.5.tgz", "integrity": "sha512-I1Db4Shst5lewOM4V+ZKJzQ0JGGaZ6VY1jYvMghRjqs6DWgxLCIyFt30GlnKkfUeFLpJt2vzbMVEXVSXlIFYUg==", "dev": true, "requires": { "@babel/types": "^7.14.5" } }, "@babel/helper-hoist-variables": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.14.5.tgz", "integrity": "sha512-R1PXiz31Uc0Vxy4OEOm07x0oSjKAdPPCh3tPivn/Eo8cvz6gveAeuyUUPB21Hoiif0uoPQSSdhIPS3352nvdyQ==", "dev": true, "requires": { "@babel/types": "^7.14.5" } }, "@babel/helper-member-expression-to-functions": { "version": "7.15.0", "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.15.0.tgz", "integrity": "sha512-Jq8H8U2kYiafuj2xMTPQwkTBnEEdGKpT35lJEQsRRjnG0LW3neucsaMWLgKcwu3OHKNeYugfw+Z20BXBSEs2Lg==", "dev": true, "requires": { "@babel/types": "^7.15.0" } }, "@babel/helper-module-imports": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.14.5.tgz", "integrity": "sha512-SwrNHu5QWS84XlHwGYPDtCxcA0hrSlL2yhWYLgeOc0w7ccOl2qv4s/nARI0aYZW+bSwAL5CukeXA47B/1NKcnQ==", "dev": true, "requires": { "@babel/types": "^7.14.5" } }, "@babel/helper-module-transforms": { "version": "7.15.0", "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.15.0.tgz", "integrity": "sha512-RkGiW5Rer7fpXv9m1B3iHIFDZdItnO2/BLfWVW/9q7+KqQSDY5kUfQEbzdXM1MVhJGcugKV7kRrNVzNxmk7NBg==", "dev": true, "requires": { "@babel/helper-module-imports": "^7.14.5", "@babel/helper-replace-supers": "^7.15.0", "@babel/helper-simple-access": "^7.14.8", "@babel/helper-split-export-declaration": "^7.14.5", "@babel/helper-validator-identifier": "^7.14.9", "@babel/template": "^7.14.5", "@babel/traverse": "^7.15.0", "@babel/types": "^7.15.0" } }, "@babel/helper-optimise-call-expression": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.14.5.tgz", "integrity": "sha512-IqiLIrODUOdnPU9/F8ib1Fx2ohlgDhxnIDU7OEVi+kAbEZcyiF7BLU8W6PfvPi9LzztjS7kcbzbmL7oG8kD6VA==", "dev": true, "requires": { "@babel/types": "^7.14.5" } }, "@babel/helper-plugin-utils": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.14.5.tgz", "integrity": "sha512-/37qQCE3K0vvZKwoK4XU/irIJQdIfCJuhU5eKnNxpFDsOkgFaUAwbv+RYw6eYgsC0E4hS7r5KqGULUogqui0fQ==", "dev": true }, "@babel/helper-replace-supers": { "version": "7.15.0", "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.15.0.tgz", "integrity": "sha512-6O+eWrhx+HEra/uJnifCwhwMd6Bp5+ZfZeJwbqUTuqkhIT6YcRhiZCOOFChRypOIe0cV46kFrRBlm+t5vHCEaA==", "dev": true, "requires": { "@babel/helper-member-expression-to-functions": "^7.15.0", "@babel/helper-optimise-call-expression": "^7.14.5", "@babel/traverse": "^7.15.0", "@babel/types": "^7.15.0" } }, "@babel/helper-simple-access": { "version": "7.14.8", "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.14.8.tgz", "integrity": "sha512-TrFN4RHh9gnWEU+s7JloIho2T76GPwRHhdzOWLqTrMnlas8T9O7ec+oEDNsRXndOmru9ymH9DFrEOxpzPoSbdg==", "dev": true, "requires": { "@babel/types": "^7.14.8" } }, "@babel/helper-split-export-declaration": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.14.5.tgz", "integrity": "sha512-hprxVPu6e5Kdp2puZUmvOGjaLv9TCe58E/Fl6hRq4YiVQxIcNvuq6uTM2r1mT/oPskuS9CgR+I94sqAYv0NGKA==", "dev": true, "requires": { "@babel/types": "^7.14.5" } }, "@babel/helper-validator-identifier": { "version": "7.14.9", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.9.tgz", "integrity": "sha512-pQYxPY0UP6IHISRitNe8bsijHex4TWZXi2HwKVsjPiltzlhse2znVcm9Ace510VT1kxIHjGJCZZQBX2gJDbo0g==", "dev": true }, "@babel/helper-validator-option": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.14.5.tgz", "integrity": "sha512-OX8D5eeX4XwcroVW45NMvoYaIuFI+GQpA2a8Gi+X/U/cDUIRsV37qQfF905F0htTRCREQIB4KqPeaveRJUl3Ow==", "dev": true }, "@babel/helpers": { "version": "7.15.3", "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.15.3.tgz", "integrity": "sha512-HwJiz52XaS96lX+28Tnbu31VeFSQJGOeKHJeaEPQlTl7PnlhFElWPj8tUXtqFIzeN86XxXoBr+WFAyK2PPVz6g==", "dev": true, "requires": { "@babel/template": "^7.14.5", "@babel/traverse": "^7.15.0", "@babel/types": "^7.15.0" } }, "@babel/highlight": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.14.5.tgz", "integrity": "sha512-qf9u2WFWVV0MppaL877j2dBtQIDgmidgjGk5VIMw3OadXvYaXn66U1BFlH2t4+t3i+8PhedppRv+i40ABzd+gg==", "dev": true, "requires": { "@babel/helper-validator-identifier": "^7.14.5", "chalk": "^2.0.0", "js-tokens": "^4.0.0" }, "dependencies": { "chalk": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "dev": true, "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", "dev": true }, "supports-color": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", "dev": true, "requires": { "has-flag": "^3.0.0" } } } }, "@babel/parser": { "version": "7.15.3", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.15.3.tgz", "integrity": "sha512-O0L6v/HvqbdJawj0iBEfVQMc3/6WP+AeOsovsIgBFyJaG+W2w7eqvZB7puddATmWuARlm1SX7DwxJ/JJUnDpEA==", "dev": true }, "@babel/plugin-syntax-async-generators": { "version": "7.8.4", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", "dev": true, "requires": { "@babel/helper-plugin-utils": "^7.8.0" } }, "@babel/plugin-syntax-bigint": { "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", "dev": true, "requires": { "@babel/helper-plugin-utils": "^7.8.0" } }, "@babel/plugin-syntax-class-properties": { "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", "dev": true, "requires": { "@babel/helper-plugin-utils": "^7.12.13" } }, "@babel/plugin-syntax-import-meta": { "version": "7.10.4", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", "dev": true, "requires": { "@babel/helper-plugin-utils": "^7.10.4" } }, "@babel/plugin-syntax-json-strings": { "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", "dev": true, "requires": { "@babel/helper-plugin-utils": "^7.8.0" } }, "@babel/plugin-syntax-logical-assignment-operators": { "version": "7.10.4", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", "dev": true, "requires": { "@babel/helper-plugin-utils": "^7.10.4" } }, "@babel/plugin-syntax-nullish-coalescing-operator": { "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", "dev": true, "requires": { "@babel/helper-plugin-utils": "^7.8.0" } }, "@babel/plugin-syntax-numeric-separator": { "version": "7.10.4", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", "dev": true, "requires": { "@babel/helper-plugin-utils": "^7.10.4" } }, "@babel/plugin-syntax-object-rest-spread": { "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", "dev": true, "requires": { "@babel/helper-plugin-utils": "^7.8.0" } }, "@babel/plugin-syntax-optional-catch-binding": { "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", "dev": true, "requires": { "@babel/helper-plugin-utils": "^7.8.0" } }, "@babel/plugin-syntax-optional-chaining": { "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", "dev": true, "requires": { "@babel/helper-plugin-utils": "^7.8.0" } }, "@babel/plugin-syntax-top-level-await": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", "dev": true, "requires": { "@babel/helper-plugin-utils": "^7.14.5" } }, "@babel/template": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.14.5.tgz", "integrity": "sha512-6Z3Po85sfxRGachLULUhOmvAaOo7xCvqGQtxINai2mEGPFm6pQ4z5QInFnUrRpfoSV60BnjyF5F3c+15fxFV1g==", "dev": true, "requires": { "@babel/code-frame": "^7.14.5", "@babel/parser": "^7.14.5", "@babel/types": "^7.14.5" }, "dependencies": { "@babel/code-frame": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.14.5.tgz", "integrity": "sha512-9pzDqyc6OLDaqe+zbACgFkb6fKMNG6CObKpnYXChRsvYGyEdc7CA2BaqeOM+vOtCS5ndmJicPJhKAwYRI6UfFw==", "dev": true, "requires": { "@babel/highlight": "^7.14.5" } } } }, "@babel/traverse": { "version": "7.15.0", "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.15.0.tgz", "integrity": "sha512-392d8BN0C9eVxVWd8H6x9WfipgVH5IaIoLp23334Sc1vbKKWINnvwRpb4us0xtPaCumlwbTtIYNA0Dv/32sVFw==", "dev": true, "requires": { "@babel/code-frame": "^7.14.5", "@babel/generator": "^7.15.0", "@babel/helper-function-name": "^7.14.5", "@babel/helper-hoist-variables": "^7.14.5", "@babel/helper-split-export-declaration": "^7.14.5", "@babel/parser": "^7.15.0", "@babel/types": "^7.15.0", "debug": "^4.1.0", "globals": "^11.1.0" }, "dependencies": { "@babel/code-frame": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.14.5.tgz", "integrity": "sha512-9pzDqyc6OLDaqe+zbACgFkb6fKMNG6CObKpnYXChRsvYGyEdc7CA2BaqeOM+vOtCS5ndmJicPJhKAwYRI6UfFw==", "dev": true, "requires": { "@babel/highlight": "^7.14.5" } }, "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", "dev": true, "requires": { "ms": "2.1.2" } }, "globals": { "version": "11.12.0", "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", "dev": true } } }, "@babel/types": { "version": "7.15.0", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.15.0.tgz", "integrity": "sha512-OBvfqnllOIdX4ojTHpwZbpvz4j3EWyjkZEdmjH0/cgsd6QOdSgU8rLSk6ard/pcW7rlmjdVSX/AWOaORR1uNOQ==", "dev": true, "requires": { "@babel/helper-validator-identifier": "^7.14.9", "to-fast-properties": "^2.0.0" } }, "@bcoe/v8-coverage": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", "dev": true }, "@cnakazawa/watch": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/@cnakazawa/watch/-/watch-1.0.4.tgz", "integrity": "sha512-v9kIhKwjeZThiWrLmj0y17CWoyddASLj9O2yvbZkbvw/N3rWOYy9zkV66ursAoVr0mV15bL8g0c4QZUE6cdDoQ==", "dev": true, "requires": { "exec-sh": "^0.3.2", "minimist": "^1.2.0" } }, "@eslint/eslintrc": { "version": "0.4.3", "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.3.tgz", "integrity": "sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==", "dev": true, "requires": { "ajv": "^6.12.4", "debug": "^4.1.1", "espree": "^7.3.0", "globals": "^13.9.0", "ignore": "^4.0.6", "import-fresh": "^3.2.1", "js-yaml": "^3.13.1", "minimatch": "^3.0.4", "strip-json-comments": "^3.1.1" }, "dependencies": { "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", "dev": true, "requires": { "ms": "2.1.2" } }, "strip-json-comments": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", "dev": true } } }, "@humanwhocodes/config-array": { "version": "0.5.0", "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.5.0.tgz", "integrity": "sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg==", "dev": true, "requires": { "@humanwhocodes/object-schema": "^1.2.0", "debug": "^4.1.1", "minimatch": "^3.0.4" }, "dependencies": { "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", "dev": true, "requires": { "ms": "2.1.2" } } } }, "@humanwhocodes/object-schema": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.0.tgz", "integrity": "sha512-wdppn25U8z/2yiaT6YGquE6X8sSv7hNMWSXYSSU1jGv/yd6XqjXgTDJ8KP4NgjTXfJ3GbRjeeb8RTV7a/VpM+w==", "dev": true }, "@istanbuljs/load-nyc-config": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", "dev": true, "requires": { "camelcase": "^5.3.1", "find-up": "^4.1.0", "get-package-type": "^0.1.0", "js-yaml": "^3.13.1", "resolve-from": "^5.0.0" }, "dependencies": { "resolve-from": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", "dev": true } } }, "@istanbuljs/schema": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", "dev": true }, "@jest/console": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/@jest/console/-/console-26.6.2.tgz", "integrity": "sha512-IY1R2i2aLsLr7Id3S6p2BA82GNWryt4oSvEXLAKc+L2zdi89dSkE8xC1C+0kpATG4JhBJREnQOH7/zmccM2B0g==", "dev": true, "requires": { "@jest/types": "^26.6.2", "@types/node": "*", "chalk": "^4.0.0", "jest-message-util": "^26.6.2", "jest-util": "^26.6.2", "slash": "^3.0.0" } }, "@jest/core": { "version": "26.6.3", "resolved": "https://registry.npmjs.org/@jest/core/-/core-26.6.3.tgz", "integrity": "sha512-xvV1kKbhfUqFVuZ8Cyo+JPpipAHHAV3kcDBftiduK8EICXmTFddryy3P7NfZt8Pv37rA9nEJBKCCkglCPt/Xjw==", "dev": true, "requires": { "@jest/console": "^26.6.2", "@jest/reporters": "^26.6.2", "@jest/test-result": "^26.6.2", "@jest/transform": "^26.6.2", "@jest/types": "^26.6.2", "@types/node": "*", "ansi-escapes": "^4.2.1", "chalk": "^4.0.0", "exit": "^0.1.2", "graceful-fs": "^4.2.4", "jest-changed-files": "^26.6.2", "jest-config": "^26.6.3", "jest-haste-map": "^26.6.2", "jest-message-util": "^26.6.2", "jest-regex-util": "^26.0.0", "jest-resolve": "^26.6.2", "jest-resolve-dependencies": "^26.6.3", "jest-runner": "^26.6.3", "jest-runtime": "^26.6.3", "jest-snapshot": "^26.6.2", "jest-util": "^26.6.2", "jest-validate": "^26.6.2", "jest-watcher": "^26.6.2", "micromatch": "^4.0.2", "p-each-series": "^2.1.0", "rimraf": "^3.0.0", "slash": "^3.0.0", "strip-ansi": "^6.0.0" }, "dependencies": { "ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "rimraf": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", "dev": true, "requires": { "glob": "^7.1.3" } }, "strip-ansi": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", "dev": true, "requires": { "ansi-regex": "^5.0.0" } } } }, "@jest/environment": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-26.6.2.tgz", "integrity": "sha512-nFy+fHl28zUrRsCeMB61VDThV1pVTtlEokBRgqPrcT1JNq4yRNIyTHfyht6PqtUvY9IsuLGTrbG8kPXjSZIZwA==", "dev": true, "requires": { "@jest/fake-timers": "^26.6.2", "@jest/types": "^26.6.2", "@types/node": "*", "jest-mock": "^26.6.2" } }, "@jest/fake-timers": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-26.6.2.tgz", "integrity": "sha512-14Uleatt7jdzefLPYM3KLcnUl1ZNikaKq34enpb5XG9i81JpppDb5muZvonvKyrl7ftEHkKS5L5/eB/kxJ+bvA==", "dev": true, "requires": { "@jest/types": "^26.6.2", "@sinonjs/fake-timers": "^6.0.1", "@types/node": "*", "jest-message-util": "^26.6.2", "jest-mock": "^26.6.2", "jest-util": "^26.6.2" } }, "@jest/globals": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-26.6.2.tgz", "integrity": "sha512-85Ltnm7HlB/KesBUuALwQ68YTU72w9H2xW9FjZ1eL1U3lhtefjjl5c2MiUbpXt/i6LaPRvoOFJ22yCBSfQ0JIA==", "dev": true, "requires": { "@jest/environment": "^26.6.2", "@jest/types": "^26.6.2", "expect": "^26.6.2" } }, "@jest/reporters": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-26.6.2.tgz", "integrity": "sha512-h2bW53APG4HvkOnVMo8q3QXa6pcaNt1HkwVsOPMBV6LD/q9oSpxNSYZQYkAnjdMjrJ86UuYeLo+aEZClV6opnw==", "dev": true, "requires": { "@bcoe/v8-coverage": "^0.2.3", "@jest/console": "^26.6.2", "@jest/test-result": "^26.6.2", "@jest/transform": "^26.6.2", "@jest/types": "^26.6.2", "chalk": "^4.0.0", "collect-v8-coverage": "^1.0.0", "exit": "^0.1.2", "glob": "^7.1.2", "graceful-fs": "^4.2.4", "istanbul-lib-coverage": "^3.0.0", "istanbul-lib-instrument": "^4.0.3", "istanbul-lib-report": "^3.0.0", "istanbul-lib-source-maps": "^4.0.0", "istanbul-reports": "^3.0.2", "jest-haste-map": "^26.6.2", "jest-resolve": "^26.6.2", "jest-util": "^26.6.2", "jest-worker": "^26.6.2", "node-notifier": "^8.0.0", "slash": "^3.0.0", "source-map": "^0.6.0", "string-length": "^4.0.1", "terminal-link": "^2.0.0", "v8-to-istanbul": "^7.0.0" } }, "@jest/source-map": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-26.6.2.tgz", "integrity": "sha512-YwYcCwAnNmOVsZ8mr3GfnzdXDAl4LaenZP5z+G0c8bzC9/dugL8zRmxZzdoTl4IaS3CryS1uWnROLPFmb6lVvA==", "dev": true, "requires": { "callsites": "^3.0.0", "graceful-fs": "^4.2.4", "source-map": "^0.6.0" } }, "@jest/test-result": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-26.6.2.tgz", "integrity": "sha512-5O7H5c/7YlojphYNrK02LlDIV2GNPYisKwHm2QTKjNZeEzezCbwYs9swJySv2UfPMyZ0VdsmMv7jIlD/IKYQpQ==", "dev": true, "requires": { "@jest/console": "^26.6.2", "@jest/types": "^26.6.2", "@types/istanbul-lib-coverage": "^2.0.0", "collect-v8-coverage": "^1.0.0" } }, "@jest/test-sequencer": { "version": "26.6.3", "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-26.6.3.tgz", "integrity": "sha512-YHlVIjP5nfEyjlrSr8t/YdNfU/1XEt7c5b4OxcXCjyRhjzLYu/rO69/WHPuYcbCWkz8kAeZVZp2N2+IOLLEPGw==", "dev": true, "requires": { "@jest/test-result": "^26.6.2", "graceful-fs": "^4.2.4", "jest-haste-map": "^26.6.2", "jest-runner": "^26.6.3", "jest-runtime": "^26.6.3" } }, "@jest/transform": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-26.6.2.tgz", "integrity": "sha512-E9JjhUgNzvuQ+vVAL21vlyfy12gP0GhazGgJC4h6qUt1jSdUXGWJ1wfu/X7Sd8etSgxV4ovT1pb9v5D6QW4XgA==", "dev": true, "requires": { "@babel/core": "^7.1.0", "@jest/types": "^26.6.2", "babel-plugin-istanbul": "^6.0.0", "chalk": "^4.0.0", "convert-source-map": "^1.4.0", "fast-json-stable-stringify": "^2.0.0", "graceful-fs": "^4.2.4", "jest-haste-map": "^26.6.2", "jest-regex-util": "^26.0.0", "jest-util": "^26.6.2", "micromatch": "^4.0.2", "pirates": "^4.0.1", "slash": "^3.0.0", "source-map": "^0.6.1", "write-file-atomic": "^3.0.0" } }, "@jest/types": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/@jest/types/-/types-26.6.2.tgz", "integrity": "sha512-fC6QCp7Sc5sX6g8Tvbmj4XUTbyrik0akgRy03yjXbQaBWWNWGE7SGtJk98m0N8nzegD/7SggrUlivxo5ax4KWQ==", "dev": true, "requires": { "@types/istanbul-lib-coverage": "^2.0.0", "@types/istanbul-reports": "^3.0.0", "@types/node": "*", "@types/yargs": "^15.0.0", "chalk": "^4.0.0" } }, "@sinonjs/commons": { "version": "1.8.3", "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.3.tgz", "integrity": "sha512-xkNcLAn/wZaX14RPlwizcKicDk9G3F8m2nU3L7Ukm5zBgTwiT0wsoFAHx9Jq56fJA1z/7uKGtCRu16sOUCLIHQ==", "dev": true, "requires": { "type-detect": "4.0.8" } }, "@sinonjs/fake-timers": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-6.0.1.tgz", "integrity": "sha512-MZPUxrmFubI36XS1DI3qmI0YdN1gks62JtFZvxR67ljjSNCeK6U08Zx4msEWOXuofgqUt6zPHSi1H9fbjR/NRA==", "dev": true, "requires": { "@sinonjs/commons": "^1.7.0" } }, "@tootallnate/once": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz", "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==", "dev": true }, "@types/babel__core": { "version": "7.1.15", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.1.15.tgz", "integrity": "sha512-bxlMKPDbY8x5h6HBwVzEOk2C8fb6SLfYQ5Jw3uBYuYF1lfWk/kbLd81la82vrIkBb0l+JdmrZaDikPrNxpS/Ew==", "dev": true, "requires": { "@babel/parser": "^7.1.0", "@babel/types": "^7.0.0", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "@types/babel__generator": { "version": "7.6.3", "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.3.tgz", "integrity": "sha512-/GWCmzJWqV7diQW54smJZzWbSFf4QYtF71WCKhcx6Ru/tFyQIY2eiiITcCAeuPbNSvT9YCGkVMqqvSk2Z0mXiA==", "dev": true, "requires": { "@babel/types": "^7.0.0" } }, "@types/babel__template": { "version": "7.4.1", "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.1.tgz", "integrity": "sha512-azBFKemX6kMg5Io+/rdGT0dkGreboUVR0Cdm3fz9QJWpaQGJRQXl7C+6hOTCZcMll7KFyEQpgbYI2lHdsS4U7g==", "dev": true, "requires": { "@babel/parser": "^7.1.0", "@babel/types": "^7.0.0" } }, "@types/babel__traverse": { "version": "7.14.2", "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.14.2.tgz", "integrity": "sha512-K2waXdXBi2302XUdcHcR1jCeU0LL4TD9HRs/gk0N2Xvrht+G/BfJa4QObBQZfhMdxiCpV3COl5Nfq4uKTeTnJA==", "dev": true, "requires": { "@babel/types": "^7.3.0" } }, "@types/eslint-visitor-keys": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/@types/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz", "integrity": "sha512-OCutwjDZ4aFS6PB1UZ988C4YgwlBHJd6wCeQqaLdmadZ/7e+w79+hbMUFC1QXDNCmdyoRfAFdm0RypzwR+Qpag==", "dev": true }, "@types/graceful-fs": { "version": "4.1.5", "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.5.tgz", "integrity": "sha512-anKkLmZZ+xm4p8JWBf4hElkM4XR+EZeA2M9BAkkTldmcyDY4mbdIJnRghDJH3Ov5ooY7/UAoENtmdMSkaAd7Cw==", "dev": true, "requires": { "@types/node": "*" } }, "@types/istanbul-lib-coverage": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.3.tgz", "integrity": "sha512-sz7iLqvVUg1gIedBOvlkxPlc8/uVzyS5OwGz1cKjXzkl3FpL3al0crU8YGU1WoHkxn0Wxbw5tyi6hvzJKNzFsw==", "dev": true }, "@types/istanbul-lib-report": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", "integrity": "sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg==", "dev": true, "requires": { "@types/istanbul-lib-coverage": "*" } }, "@types/istanbul-reports": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.1.tgz", "integrity": "sha512-c3mAZEuK0lvBp8tmuL74XRKn1+y2dcwOUpH7x4WrF6gk1GIgiluDRgMYQtw2OFcBvAJWlt6ASU3tSqxp0Uu0Aw==", "dev": true, "requires": { "@types/istanbul-lib-report": "*" } }, "@types/jest": { "version": "26.0.24", "resolved": "https://registry.npmjs.org/@types/jest/-/jest-26.0.24.tgz", "integrity": "sha512-E/X5Vib8BWqZNRlDxj9vYXhsDwPYbPINqKF9BsnSoon4RQ0D9moEuLD8txgyypFLH7J4+Lho9Nr/c8H0Fi+17w==", "dev": true, "requires": { "jest-diff": "^26.0.0", "pretty-format": "^26.0.0" } }, "@types/json-schema": { "version": "7.0.9", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.9.tgz", "integrity": "sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ==", "dev": true }, "@types/node": { "version": "13.13.52", "resolved": "https://registry.npmjs.org/@types/node/-/node-13.13.52.tgz", "integrity": "sha512-s3nugnZumCC//n4moGGe6tkNMyYEdaDBitVjwPxXmR5lnMG5dHePinH2EdxkG3Rh1ghFHHixAG4NJhpJW1rthQ==" }, "@types/normalize-package-data": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/@types/normalize-package-data/-/normalize-package-data-2.4.1.tgz", "integrity": "sha512-Gj7cI7z+98M282Tqmp2K5EIsoouUEzbBJhQQzDE3jSIRk6r9gsz0oUokqIUR4u1R3dMHo0pDHM7sNOHyhulypw==", "dev": true }, "@types/prettier": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.3.2.tgz", "integrity": "sha512-eI5Yrz3Qv4KPUa/nSIAi0h+qX0XyewOliug5F2QAtuRg6Kjg6jfmxe1GIwoIRhZspD1A0RP8ANrPwvEXXtRFog==", "dev": true }, "@types/stack-utils": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz", "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==", "dev": true }, "@types/yargs": { "version": "15.0.14", "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.14.tgz", "integrity": "sha512-yEJzHoxf6SyQGhBhIYGXQDSCkJjB6HohDShto7m8vaKg9Yp0Yn8+71J9eakh2bnPg6BfsH9PRMhiRTZnd4eXGQ==", "dev": true, "requires": { "@types/yargs-parser": "*" } }, "@types/yargs-parser": { "version": "20.2.1", "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-20.2.1.tgz", "integrity": "sha512-7tFImggNeNBVMsn0vLrpn1H1uPrUBdnARPTpZoitY37ZrdJREzf7I16tMrlK3hen349gr1NYh8CmZQa7CTG6Aw==", "dev": true }, "@typescript-eslint/eslint-plugin": { "version": "3.10.1", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-3.10.1.tgz", "integrity": "sha512-PQg0emRtzZFWq6PxBcdxRH3QIQiyFO3WCVpRL3fgj5oQS3CDs3AeAKfv4DxNhzn8ITdNJGJ4D3Qw8eAJf3lXeQ==", "dev": true, "requires": { "@typescript-eslint/experimental-utils": "3.10.1", "debug": "^4.1.1", "functional-red-black-tree": "^1.0.1", "regexpp": "^3.0.0", "semver": "^7.3.2", "tsutils": "^3.17.1" }, "dependencies": { "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", "dev": true, "requires": { "ms": "2.1.2" } }, "semver": { "version": "7.3.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", "dev": true, "requires": { "lru-cache": "^6.0.0" } } } }, "@typescript-eslint/experimental-utils": { "version": "3.10.1", "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-3.10.1.tgz", "integrity": "sha512-DewqIgscDzmAfd5nOGe4zm6Bl7PKtMG2Ad0KG8CUZAHlXfAKTF9Ol5PXhiMh39yRL2ChRH1cuuUGOcVyyrhQIw==", "dev": true, "requires": { "@types/json-schema": "^7.0.3", "@typescript-eslint/types": "3.10.1", "@typescript-eslint/typescript-estree": "3.10.1", "eslint-scope": "^5.0.0", "eslint-utils": "^2.0.0" } }, "@typescript-eslint/parser": { "version": "3.10.1", "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-3.10.1.tgz", "integrity": "sha512-Ug1RcWcrJP02hmtaXVS3axPPTTPnZjupqhgj+NnZ6BCkwSImWk/283347+x9wN+lqOdK9Eo3vsyiyDHgsmiEJw==", "dev": true, "requires": { "@types/eslint-visitor-keys": "^1.0.0", "@typescript-eslint/experimental-utils": "3.10.1", "@typescript-eslint/types": "3.10.1", "@typescript-eslint/typescript-estree": "3.10.1", "eslint-visitor-keys": "^1.1.0" } }, "@typescript-eslint/types": { "version": "3.10.1", "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-3.10.1.tgz", "integrity": "sha512-+3+FCUJIahE9q0lDi1WleYzjCwJs5hIsbugIgnbB+dSCYUxl8L6PwmsyOPFZde2hc1DlTo/xnkOgiTLSyAbHiQ==", "dev": true }, "@typescript-eslint/typescript-estree": { "version": "3.10.1", "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-3.10.1.tgz", "integrity": "sha512-QbcXOuq6WYvnB3XPsZpIwztBoquEYLXh2MtwVU+kO8jgYCiv4G5xrSP/1wg4tkvrEE+esZVquIPX/dxPlePk1w==", "dev": true, "requires": { "@typescript-eslint/types": "3.10.1", "@typescript-eslint/visitor-keys": "3.10.1", "debug": "^4.1.1", "glob": "^7.1.6", "is-glob": "^4.0.1", "lodash": "^4.17.15", "semver": "^7.3.2", "tsutils": "^3.17.1" }, "dependencies": { "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", "dev": true, "requires": { "ms": "2.1.2" } }, "semver": { "version": "7.3.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", "dev": true, "requires": { "lru-cache": "^6.0.0" } } } }, "@typescript-eslint/visitor-keys": { "version": "3.10.1", "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-3.10.1.tgz", "integrity": "sha512-9JgC82AaQeglebjZMgYR5wgmfUdUc+EitGUUMW8u2nDckaeimzW+VsoLV6FoimPv2id3VQzfjwBxEMVz08ameQ==", "dev": true, "requires": { "eslint-visitor-keys": "^1.1.0" } }, "abab": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.5.tgz", "integrity": "sha512-9IK9EadsbHo6jLWIpxpR6pL0sazTXV6+SQv25ZB+F7Bj9mJNaOc4nCRabwd5M/JwmUa8idz6Eci6eKfJryPs6Q==", "dev": true }, "abbrev": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" }, "abs": { "version": "1.3.14", "resolved": "https://registry.npmjs.org/abs/-/abs-1.3.14.tgz", "integrity": "sha512-PrS26IzwKLWwuURpiKl8wRmJ2KdR/azaVrLEBWG/TALwT20Y7qjtYp1qcMLHA4206hBHY5phv3w4pjf9NPv4Vw==", "requires": { "ul": "^5.0.0" } }, "acorn": { "version": "7.4.1", "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", "dev": true }, "acorn-globals": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-6.0.0.tgz", "integrity": "sha512-ZQl7LOWaF5ePqqcX4hLuv/bLXYQNfNWw2c0/yX/TsPRKamzHcTGQnlCjHT3TsmkOUVEPS3crCxiPfdzE/Trlhg==", "dev": true, "requires": { "acorn": "^7.1.1", "acorn-walk": "^7.1.1" } }, "acorn-jsx": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", "dev": true }, "acorn-walk": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-7.2.0.tgz", "integrity": "sha512-OPdCF6GsMIP+Az+aWfAAOEt2/+iVDKE7oy6lJ098aoe59oAmK76qV6Gw60SbZ8jHuG2wH058GF4pLFbYamYrVA==", "dev": true }, "agent-base": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", "dev": true, "requires": { "debug": "4" }, "dependencies": { "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", "dev": true, "requires": { "ms": "2.1.2" } } } }, "ajv": { "version": "6.12.6", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "dev": true, "requires": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "ansi-colors": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", "dev": true }, "ansi-escapes": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", "dev": true, "requires": { "type-fest": "^0.21.3" }, "dependencies": { "type-fest": { "version": "0.21.3", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", "dev": true } } }, "ansi-regex": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" }, "ansi-styles": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", "dev": true, "requires": { "color-convert": "^1.9.0" } }, "anymatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz", "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==", "dev": true, "requires": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" } }, "aproba": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/aproba/-/aproba-1.2.0.tgz", "integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==" }, "are-we-there-yet": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-1.1.5.tgz", "integrity": "sha512-5hYdAkZlcG8tOLujVDTgCT+uPX0VnpAH28gWsLfzpXYm7wP6mp5Q/gYyR7YQ0cKVJcXJnl3j2kpBan13PtQf6w==", "requires": { "delegates": "^1.0.0", "readable-stream": "^2.0.6" } }, "argparse": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", "dev": true, "requires": { "sprintf-js": "~1.0.2" } }, "arr-diff": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", "dev": true }, "arr-flatten": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz", "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==", "dev": true }, "arr-union": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=", "dev": true }, "array-back": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/array-back/-/array-back-3.1.0.tgz", "integrity": "sha512-TkuxA4UCOvxuDK6NZYXCalszEzj+TLszyASooky+i742l9TqsOdYCMJJupxRic61hwquNtppB3hgcuq9SVSH1Q==", "dev": true }, "array-unique": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", "dev": true }, "assign-symbols": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz", "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=", "dev": true }, "astral-regex": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", "dev": true }, "asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", "dev": true }, "atob": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==", "dev": true }, "babel-jest": { "version": "26.6.3", "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-26.6.3.tgz", "integrity": "sha512-pl4Q+GAVOHwvjrck6jKjvmGhnO3jHX/xuB9d27f+EJZ/6k+6nMuPjorrYp7s++bKKdANwzElBWnLWaObvTnaZA==", "dev": true, "requires": { "@jest/transform": "^26.6.2", "@jest/types": "^26.6.2", "@types/babel__core": "^7.1.7", "babel-plugin-istanbul": "^6.0.0", "babel-preset-jest": "^26.6.2", "chalk": "^4.0.0", "graceful-fs": "^4.2.4", "slash": "^3.0.0" } }, "babel-plugin-istanbul": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.0.0.tgz", "integrity": "sha512-AF55rZXpe7trmEylbaE1Gv54wn6rwU03aptvRoVIGP8YykoSxqdVLV1TfwflBCE/QtHmqtP8SWlTENqbK8GCSQ==", "dev": true, "requires": { "@babel/helper-plugin-utils": "^7.0.0", "@istanbuljs/load-nyc-config": "^1.0.0", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-instrument": "^4.0.0", "test-exclude": "^6.0.0" } }, "babel-plugin-jest-hoist": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-26.6.2.tgz", "integrity": "sha512-PO9t0697lNTmcEHH69mdtYiOIkkOlj9fySqfO3K1eCcdISevLAE0xY59VLLUj0SoiPiTX/JU2CYFpILydUa5Lw==", "dev": true, "requires": { "@babel/template": "^7.3.3", "@babel/types": "^7.3.3", "@types/babel__core": "^7.0.0", "@types/babel__traverse": "^7.0.6" } }, "babel-preset-current-node-syntax": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz", "integrity": "sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ==", "dev": true, "requires": { "@babel/plugin-syntax-async-generators": "^7.8.4", "@babel/plugin-syntax-bigint": "^7.8.3", "@babel/plugin-syntax-class-properties": "^7.8.3", "@babel/plugin-syntax-import-meta": "^7.8.3", "@babel/plugin-syntax-json-strings": "^7.8.3", "@babel/plugin-syntax-logical-assignment-operators": "^7.8.3", "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", "@babel/plugin-syntax-numeric-separator": "^7.8.3", "@babel/plugin-syntax-object-rest-spread": "^7.8.3", "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", "@babel/plugin-syntax-optional-chaining": "^7.8.3", "@babel/plugin-syntax-top-level-await": "^7.8.3" } }, "babel-preset-jest": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-26.6.2.tgz", "integrity": "sha512-YvdtlVm9t3k777c5NPQIv6cxFFFapys25HiUmuSgHwIZhfifweR5c5Sf5nwE3MAbfu327CYSvps8Yx6ANLyleQ==", "dev": true, "requires": { "babel-plugin-jest-hoist": "^26.6.2", "babel-preset-current-node-syntax": "^1.0.0" } }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" }, "base": { "version": "0.11.2", "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==", "dev": true, "requires": { "cache-base": "^1.0.1", "class-utils": "^0.3.5", "component-emitter": "^1.2.1", "define-property": "^1.0.0", "isobject": "^3.0.1", "mixin-deep": "^1.2.0", "pascalcase": "^0.1.1" }, "dependencies": { "define-property": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", "dev": true, "requires": { "is-descriptor": "^1.0.0" } }, "is-accessor-descriptor": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", "dev": true, "requires": { "kind-of": "^6.0.0" } }, "is-data-descriptor": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", "dev": true, "requires": { "kind-of": "^6.0.0" } }, "is-descriptor": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", "dev": true, "requires": { "is-accessor-descriptor": "^1.0.0", "is-data-descriptor": "^1.0.0", "kind-of": "^6.0.2" } } } }, "bluebird": { "version": "3.5.5", "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.5.tgz", "integrity": "sha512-5am6HnnfN+urzt4yfg7IgTbotDjIT/u8AJpEt0sIU9FtXfVeezXAPKswrG+xKUCOYAINpSdgZVDU6QFh+cuH3w==" }, "brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "braces": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", "dev": true, "requires": { "fill-range": "^7.0.1" } }, "browser-process-hrtime": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/browser-process-hrtime/-/browser-process-hrtime-1.0.0.tgz", "integrity": "sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow==", "dev": true }, "browserslist": { "version": "4.16.8", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.16.8.tgz", "integrity": "sha512-sc2m9ohR/49sWEbPj14ZSSZqp+kbi16aLao42Hmn3Z8FpjuMaq2xCA2l4zl9ITfyzvnvyE0hcg62YkIGKxgaNQ==", "dev": true, "requires": { "caniuse-lite": "^1.0.30001251", "colorette": "^1.3.0", "electron-to-chromium": "^1.3.811", "escalade": "^3.1.1", "node-releases": "^1.1.75" } }, "bs-logger": { "version": "0.2.6", "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", "dev": true, "requires": { "fast-json-stable-stringify": "2.x" } }, "bser": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", "dev": true, "requires": { "node-int64": "^0.4.0" } }, "buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true }, "builtins": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/builtins/-/builtins-1.0.3.tgz", "integrity": "sha1-y5T662HIaWRR2zZTThQi+U8K7og=", "dev": true }, "cache-base": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", "integrity": "sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==", "dev": true, "requires": { "collection-visit": "^1.0.0", "component-emitter": "^1.2.1", "get-value": "^2.0.6", "has-value": "^1.0.0", "isobject": "^3.0.1", "set-value": "^2.0.0", "to-object-path": "^0.3.0", "union-value": "^1.0.0", "unset-value": "^1.0.0" } }, "callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", "dev": true }, "camelcase": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", "dev": true }, "caniuse-lite": { "version": "1.0.30001252", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001252.tgz", "integrity": "sha512-I56jhWDGMtdILQORdusxBOH+Nl/KgQSdDmpJezYddnAkVOmnoU8zwjTV9xAjMIYxr0iPreEAVylCGcmHCjfaOw==", "dev": true }, "capture-exit": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/capture-exit/-/capture-exit-2.0.0.tgz", "integrity": "sha512-PiT/hQmTonHhl/HFGN+Lx3JJUznrVYJ3+AQsnthneZbvW7x+f08Tk7yLJTLEOUvBTbduLeeBkxEaYXUOUrRq6g==", "dev": true, "requires": { "rsvp": "^4.8.4" } }, "capture-stack-trace": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/capture-stack-trace/-/capture-stack-trace-1.0.2.tgz", "integrity": "sha512-X/WM2UQs6VMHUtjUDnZTRI+i1crWteJySFzr9UpGoQa4WQffXVTTXuekjl7TjZRlcF2XfjgITT0HxZ9RnxeT0w==" }, "chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, "requires": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" }, "dependencies": { "ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { "color-convert": "^2.0.1" } }, "color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "requires": { "color-name": "~1.1.4" } }, "color-name": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true } } }, "char-regex": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", "dev": true }, "chardet": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", "dev": true }, "chownr": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==" }, "ci-info": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==", "dev": true }, "cjs-module-lexer": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-0.6.0.tgz", "integrity": "sha512-uc2Vix1frTfnuzxxu1Hp4ktSvM3QaI4oXl4ZUqL1wjTu/BGki9TrCWoqLTg/drR1KwAEarXuRFCG2Svr1GxPFw==", "dev": true }, "class-utils": { "version": "0.3.6", "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", "integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==", "dev": true, "requires": { "arr-union": "^3.1.0", "define-property": "^0.2.5", "isobject": "^3.0.0", "static-extend": "^0.1.1" }, "dependencies": { "define-property": { "version": "0.2.5", "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", "dev": true, "requires": { "is-descriptor": "^0.1.0" } } } }, "cli-cursor": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", "dev": true, "requires": { "restore-cursor": "^3.1.0" } }, "cli-width": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-3.0.0.tgz", "integrity": "sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==", "dev": true }, "cliui": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", "dev": true, "requires": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", "wrap-ansi": "^6.2.0" }, "dependencies": { "ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true }, "string-width": { "version": "4.2.2", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz", "integrity": "sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA==", "dev": true, "requires": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.0" } }, "strip-ansi": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", "dev": true, "requires": { "ansi-regex": "^5.0.0" } } } }, "co": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=", "dev": true }, "code-point-at": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=" }, "collect-v8-coverage": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.1.tgz", "integrity": "sha512-iBPtljfCNcTKNAto0KEtDfZ3qzjJvqE3aTGZsbhjSBlorqpXJlaWWtPO35D+ZImoC3KWejX64o+yPGxhWSTzfg==", "dev": true }, "collection-visit": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/collection-visit/-/collection-visit-1.0.0.tgz", "integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=", "dev": true, "requires": { "map-visit": "^1.0.0", "object-visit": "^1.0.0" } }, "collections": { "version": "5.1.13", "resolved": "https://registry.npmjs.org/collections/-/collections-5.1.13.tgz", "integrity": "sha512-SCb6Qd+d3Z02corWQ7/mqXiXeeTdHvkP6TeFSYfGYdCFp1WrjSNZ3j6y8Y3T/7osGEe0iOcU2g1d346l99m4Lg==", "requires": { "weak-map": "~1.0.x" } }, "color-convert": { "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", "dev": true, "requires": { "color-name": "1.1.3" } }, "color-name": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", "dev": true }, "colorette": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.3.0.tgz", "integrity": "sha512-ecORCqbSFP7Wm8Y6lyqMJjexBQqXSF7SSeaTyGGphogUjBlFP9m9o08wy86HL2uB7fMTxtOUzLMk7ogKcxMg1w==", "dev": true }, "combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", "dev": true, "requires": { "delayed-stream": "~1.0.0" } }, "command-line-args": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.2.0.tgz", "integrity": "sha512-4zqtU1hYsSJzcJBOcNZIbW5Fbk9BkjCp1pZVhQKoRaWL5J7N4XphDLwo8aWwdQpTugxwu+jf9u2ZhkXiqp5Z6A==", "dev": true, "requires": { "array-back": "^3.1.0", "find-replace": "^3.0.0", "lodash.camelcase": "^4.3.0", "typical": "^4.0.0" } }, "command-line-commands": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/command-line-commands/-/command-line-commands-3.0.2.tgz", "integrity": "sha512-ac6PdCtdR6q7S3HN+JiVLIWGHY30PRYIEl2qPo+FuEuzwAUk0UYyimrngrg7FvF/mCr4Jgoqv5ZnHZgads50rw==", "dev": true, "requires": { "array-back": "^4.0.1" }, "dependencies": { "array-back": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/array-back/-/array-back-4.0.2.tgz", "integrity": "sha512-NbdMezxqf94cnNfWLL7V/im0Ub+Anbb0IoZhvzie8+4HJ4nMQuzHuy49FkGYCJK2yAloZ3meiB6AVMClbrI1vg==", "dev": true } } }, "command-line-usage": { "version": "6.1.1", "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-6.1.1.tgz", "integrity": "sha512-F59pEuAR9o1SF/bD0dQBDluhpT4jJQNWUHEuVBqpDmCUo6gPjCi+m9fCWnWZVR/oG6cMTUms4h+3NPl74wGXvA==", "dev": true, "requires": { "array-back": "^4.0.1", "chalk": "^2.4.2", "table-layout": "^1.0.1", "typical": "^5.2.0" }, "dependencies": { "array-back": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/array-back/-/array-back-4.0.2.tgz", "integrity": "sha512-NbdMezxqf94cnNfWLL7V/im0Ub+Anbb0IoZhvzie8+4HJ4nMQuzHuy49FkGYCJK2yAloZ3meiB6AVMClbrI1vg==", "dev": true }, "chalk": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "dev": true, "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", "dev": true }, "supports-color": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", "dev": true, "requires": { "has-flag": "^3.0.0" } }, "typical": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/typical/-/typical-5.2.0.tgz", "integrity": "sha512-dvdQgNDNJo+8B2uBQoqdb11eUCE1JQXhvjC/CZtgvZseVd5TYMXnq0+vuUemXbd/Se29cTaUuPX3YIc2xgbvIg==", "dev": true } } }, "comment-parser": { "version": "0.7.6", "resolved": "https://registry.npmjs.org/comment-parser/-/comment-parser-0.7.6.tgz", "integrity": "sha512-GKNxVA7/iuTnAqGADlTWX4tkhzxZKXp5fLJqKTlQLHkE65XDUKutZ3BHaJC5IGcper2tT3QRD1xr4o3jNpgXXg==", "dev": true }, "component-emitter": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==", "dev": true }, "concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" }, "console-control-strings": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=" }, "convert-source-map": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.8.0.tgz", "integrity": "sha512-+OQdjP49zViI/6i7nIJpA8rAl4sV/JdPfU9nZs3VqOwGIgizICvuN2ru6fMd+4llL0tar18UYJXfZ/TWtmhUjA==", "dev": true, "requires": { "safe-buffer": "~5.1.1" } }, "copy-descriptor": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=", "dev": true }, "core-util-is": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" }, "create-error-class": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/create-error-class/-/create-error-class-3.0.2.tgz", "integrity": "sha512-gYTKKexFO3kh200H1Nit76sRwRtOY32vQd3jpAQKpLtZqyNsSQNfI4N7o3eP2wUjV35pTWKRYqFUDBvUha/Pkw==", "requires": { "capture-stack-trace": "^1.0.0" } }, "cross-spawn": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "dev": true, "requires": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "cssom": { "version": "0.4.4", "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.4.4.tgz", "integrity": "sha512-p3pvU7r1MyyqbTk+WbNJIgJjG2VmTIaB10rI93LzVPrmDJKkzKYMtxxyAvQXR/NS6otuzveI7+7BBq3SjBS2mw==", "dev": true }, "cssstyle": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-2.3.0.tgz", "integrity": "sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A==", "dev": true, "requires": { "cssom": "~0.3.6" }, "dependencies": { "cssom": { "version": "0.3.8", "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz", "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", "dev": true } } }, "d": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/d/-/d-1.0.1.tgz", "integrity": "sha512-m62ShEObQ39CfralilEQRjH6oAMtNCV1xJyEx5LpRYUVN+EviphDgUc/F3hnYbADmkiNs67Y+3ylmlG7Lnu+FA==", "requires": { "es5-ext": "^0.10.50", "type": "^1.0.1" }, "dependencies": { "type": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/type/-/type-1.2.0.tgz", "integrity": "sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg==" } } }, "data-urls": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-2.0.0.tgz", "integrity": "sha512-X5eWTSXO/BJmpdIKCRuKUgSCgAN0OwliVK3yPKbwIWU1Tdw5BRajxlzMidvh+gwko9AfQ9zIj52pzF91Q3YAvQ==", "dev": true, "requires": { "abab": "^2.0.3", "whatwg-mimetype": "^2.3.0", "whatwg-url": "^8.0.0" } }, "debug": { "version": "3.2.6", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", "requires": { "ms": "^2.1.1" } }, "decamelize": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", "dev": true }, "decimal.js": { "version": "10.3.1", "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.3.1.tgz", "integrity": "sha512-V0pfhfr8suzyPGOx3nmq4aHqabehUZn6Ch9kyFpV79TGDTWFmHqUqXdabR7QHqxzrYolF4+tVmJhUG4OURg5dQ==", "dev": true }, "decode-uri-component": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.2.tgz", "integrity": "sha512-FqUYQ+8o158GyGTrMFJms9qh3CqTKvAqgqsTnkLI8sKu0028orqBhxNMFkFen0zGyg6epACD32pjVk58ngIErQ==", "dev": true }, "deep-extend": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==" }, "deep-is": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", "dev": true }, "deepmerge": { "version": "4.2.2", "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", "dev": true }, "deffy": { "version": "2.2.4", "resolved": "https://registry.npmjs.org/deffy/-/deffy-2.2.4.tgz", "integrity": "sha512-pLc9lsbsWjr6RxmJ2OLyvm+9l4j1yK69h+TML/gUit/t3vTijpkNGh8LioaJYTGO7F25m6HZndADcUOo2PsiUg==", "requires": { "typpy": "^2.0.0" } }, "define-property": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", "integrity": "sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==", "dev": true, "requires": { "is-descriptor": "^1.0.2", "isobject": "^3.0.1" }, "dependencies": { "is-accessor-descriptor": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", "dev": true, "requires": { "kind-of": "^6.0.0" } }, "is-data-descriptor": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", "dev": true, "requires": { "kind-of": "^6.0.0" } }, "is-descriptor": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", "dev": true, "requires": { "is-accessor-descriptor": "^1.0.0", "is-data-descriptor": "^1.0.0", "kind-of": "^6.0.2" } } } }, "delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", "dev": true }, "delegates": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=" }, "detect-libc": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-1.0.3.tgz", "integrity": "sha1-+hN8S9aY7fVc1c0CrFWfkaTEups=" }, "detect-newline": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", "dev": true }, "diff-sequences": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-26.6.2.tgz", "integrity": "sha512-Mv/TDa3nZ9sbc5soK+OoA74BsS3mL37yixCvUAQkiuA4Wz6YtwP/K47n2rv2ovzHZvoiQeA5FTQOschKkEwB0Q==", "dev": true }, "doctrine": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", "dev": true, "requires": { "esutils": "^2.0.2" } }, "domelementtype": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.1.tgz", "integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w==" }, "domexception": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/domexception/-/domexception-2.0.1.tgz", "integrity": "sha512-yxJ2mFy/sibVQlu5qHjOkf9J3K6zgmCxgJ94u2EdvDOV09H+32LtRswEcUsmUWN72pVLOEnTSRaIVVzVQgS0dg==", "dev": true, "requires": { "webidl-conversions": "^5.0.0" }, "dependencies": { "webidl-conversions": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-5.0.0.tgz", "integrity": "sha512-VlZwKPCkYKxQgeSbH5EyngOmRp7Ww7I9rQLERETtf5ofd9pGeswWiOtogpEO850jziPRarreGxn5QIiTqpb2wA==", "dev": true } } }, "domhandler": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.0.3.tgz", "integrity": "sha512-D8+qeCUo6LpYvBZsmXWunDJ9zOD8mVg6EwZIdgxmnT+xGWRsReF/TwsZ5EzlIJDipxlE6qJh1dXt9oeplGN3Bg==", "requires": { "domelementtype": "1" } }, "domutils": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.1.6.tgz", "integrity": "sha512-ZeagMzMKyk9GSFMqV3x3uHgRN36hLpSOF6LIRXmftce0UUqFsAx/azJAJ4Jc+9DYKmwROH5HLOcOu1OPARWwNg==", "requires": { "domelementtype": "1" } }, "duplexer2": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", "integrity": "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==", "requires": { "readable-stream": "^2.0.2" } }, "electron-to-chromium": { "version": "1.3.827", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.827.tgz", "integrity": "sha512-ye+4uQOY/jbjRutMcE/EmOcNwUeo1qo9aKL2tPyb09cU3lmxNeyDF4RWiemmkknW+p29h7dyDqy02higTxc9/A==", "dev": true }, "emittery": { "version": "0.7.2", "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.7.2.tgz", "integrity": "sha512-A8OG5SR/ij3SsJdWDJdkkSYUjQdCUx6APQXem0SaEePBSRg4eymGYwBkKo1Y6DU+af/Jn2dBQqDBvjnr9Vi8nQ==", "dev": true }, "emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "dev": true }, "end-of-stream": { "version": "1.4.4", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", "dev": true, "requires": { "once": "^1.4.0" } }, "enquirer": { "version": "2.3.6", "resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.3.6.tgz", "integrity": "sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg==", "dev": true, "requires": { "ansi-colors": "^4.1.1" } }, "err": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/err/-/err-1.1.1.tgz", "integrity": "sha512-N97Ybd2jJHVQ+Ft3Q5+C2gM3kgygkdeQmEqbN2z15UTVyyEsIwLA1VK39O1DHEJhXbwIFcJLqm6iARNhFANcQA==", "requires": { "typpy": "^2.2.0" } }, "error-ex": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", "requires": { "is-arrayish": "^0.2.1" } }, "es5-ext": { "version": "0.10.62", "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.62.tgz", "integrity": "sha512-BHLqn0klhEpnOKSrzn/Xsz2UIW8j+cGmo9JLzr8BiUapV8hPL9+FliFqjwr9ngW7jWdnxv6eO+/LqyhJVqgrjA==", "requires": { "es6-iterator": "^2.0.3", "es6-symbol": "^3.1.3", "next-tick": "^1.1.0" } }, "es6-iterator": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==", "requires": { "d": "1", "es5-ext": "^0.10.35", "es6-symbol": "^3.1.1" } }, "es6-set": { "version": "0.1.6", "resolved": "https://registry.npmjs.org/es6-set/-/es6-set-0.1.6.tgz", "integrity": "sha512-TE3LgGLDIBX332jq3ypv6bcOpkLO0AslAQo7p2VqX/1N46YNsvIWgvjojjSEnWEGWMhr1qUbYeTSir5J6mFHOw==", "requires": { "d": "^1.0.1", "es5-ext": "^0.10.62", "es6-iterator": "~2.0.3", "es6-symbol": "^3.1.3", "event-emitter": "^0.3.5", "type": "^2.7.2" } }, "es6-symbol": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.3.tgz", "integrity": "sha512-NJ6Yn3FuDinBaBRWl/q5X/s4koRHBrgKAu+yGI6JCBeiu3qrcbJhwT2GeR/EXVfylRk8dpQVJoLEFhK+Mu31NA==", "requires": { "d": "^1.0.1", "ext": "^1.1.2" } }, "escalade": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", "dev": true }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", "dev": true }, "escodegen": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.0.0.tgz", "integrity": "sha512-mmHKys/C8BFUGI+MAWNcSYoORYLMdPzjrknd2Vc+bUsjN5bXcr8EhrNB+UTqfL1y3I9c4fw2ihgtMPQLBRiQxw==", "dev": true, "requires": { "esprima": "^4.0.1", "estraverse": "^5.2.0", "esutils": "^2.0.2", "optionator": "^0.8.1", "source-map": "~0.6.1" }, "dependencies": { "estraverse": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", "dev": true }, "levn": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", "dev": true, "requires": { "prelude-ls": "~1.1.2", "type-check": "~0.3.2" } }, "optionator": { "version": "0.8.3", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", "dev": true, "requires": { "deep-is": "~0.1.3", "fast-levenshtein": "~2.0.6", "levn": "~0.3.0", "prelude-ls": "~1.1.2", "type-check": "~0.3.2", "word-wrap": "~1.2.3" } }, "prelude-ls": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", "dev": true }, "type-check": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", "dev": true, "requires": { "prelude-ls": "~1.1.2" } } } }, "eslint": { "version": "7.32.0", "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.32.0.tgz", "integrity": "sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA==", "dev": true, "requires": { "@babel/code-frame": "7.12.11", "@eslint/eslintrc": "^0.4.3", "@humanwhocodes/config-array": "^0.5.0", "ajv": "^6.10.0", "chalk": "^4.0.0", "cross-spawn": "^7.0.2", "debug": "^4.0.1", "doctrine": "^3.0.0", "enquirer": "^2.3.5", "escape-string-regexp": "^4.0.0", "eslint-scope": "^5.1.1", "eslint-utils": "^2.1.0", "eslint-visitor-keys": "^2.0.0", "espree": "^7.3.1", "esquery": "^1.4.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^6.0.1", "functional-red-black-tree": "^1.0.1", "glob-parent": "^5.1.2", "globals": "^13.6.0", "ignore": "^4.0.6", "import-fresh": "^3.0.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "js-yaml": "^3.13.1", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.4.1", "lodash.merge": "^4.6.2", "minimatch": "^3.0.4", "natural-compare": "^1.4.0", "optionator": "^0.9.1", "progress": "^2.0.0", "regexpp": "^3.1.0", "semver": "^7.2.1", "strip-ansi": "^6.0.0", "strip-json-comments": "^3.1.0", "table": "^6.0.9", "text-table": "^0.2.0", "v8-compile-cache": "^2.0.3" }, "dependencies": { "ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", "dev": true, "requires": { "ms": "2.1.2" } }, "escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", "dev": true }, "eslint-visitor-keys": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", "dev": true }, "semver": { "version": "7.3.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", "dev": true, "requires": { "lru-cache": "^6.0.0" } }, "strip-ansi": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", "dev": true, "requires": { "ansi-regex": "^5.0.0" } }, "strip-json-comments": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", "dev": true } } }, "eslint-config-prettier": { "version": "6.15.0", "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-6.15.0.tgz", "integrity": "sha512-a1+kOYLR8wMGustcgAjdydMsQ2A/2ipRPwRKUmfYaSxc9ZPcrku080Ctl6zrZzZNs/U82MjSv+qKREkoq3bJaw==", "dev": true, "requires": { "get-stdin": "^6.0.0" } }, "eslint-plugin-jest": { "version": "23.20.0", "resolved": "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-23.20.0.tgz", "integrity": "sha512-+6BGQt85OREevBDWCvhqj1yYA4+BFK4XnRZSGJionuEYmcglMZYLNNBBemwzbqUAckURaHdJSBcjHPyrtypZOw==", "dev": true, "requires": { "@typescript-eslint/experimental-utils": "^2.5.0" }, "dependencies": { "@typescript-eslint/experimental-utils": { "version": "2.34.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-2.34.0.tgz", "integrity": "sha512-eS6FTkq+wuMJ+sgtuNTtcqavWXqsflWcfBnlYhg/nS4aZ1leewkXGbvBhaapn1q6qf4M71bsR1tez5JTRMuqwA==", "dev": true, "requires": { "@types/json-schema": "^7.0.3", "@typescript-eslint/typescript-estree": "2.34.0", "eslint-scope": "^5.0.0", "eslint-utils": "^2.0.0" } }, "@typescript-eslint/typescript-estree": { "version": "2.34.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-2.34.0.tgz", "integrity": "sha512-OMAr+nJWKdlVM9LOqCqh3pQQPwxHAN7Du8DR6dmwCrAmxtiXQnhHJ6tBNtf+cggqfo51SG/FCwnKhXCIM7hnVg==", "dev": true, "requires": { "debug": "^4.1.1", "eslint-visitor-keys": "^1.1.0", "glob": "^7.1.6", "is-glob": "^4.0.1", "lodash": "^4.17.15", "semver": "^7.3.2", "tsutils": "^3.17.1" } }, "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", "dev": true, "requires": { "ms": "2.1.2" } }, "semver": { "version": "7.3.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", "dev": true, "requires": { "lru-cache": "^6.0.0" } } } }, "eslint-plugin-jsdoc": { "version": "30.7.13", "resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-30.7.13.tgz", "integrity": "sha512-YM4WIsmurrp0rHX6XiXQppqKB8Ne5ATiZLJe2+/fkp9l9ExXFr43BbAbjZaVrpCT+tuPYOZ8k1MICARHnURUNQ==", "dev": true, "requires": { "comment-parser": "^0.7.6", "debug": "^4.3.1", "jsdoctypeparser": "^9.0.0", "lodash": "^4.17.20", "regextras": "^0.7.1", "semver": "^7.3.4", "spdx-expression-parse": "^3.0.1" }, "dependencies": { "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", "dev": true, "requires": { "ms": "2.1.2" } }, "semver": { "version": "7.3.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", "dev": true, "requires": { "lru-cache": "^6.0.0" } } } }, "eslint-plugin-prettier": { "version": "3.4.1", "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-3.4.1.tgz", "integrity": "sha512-htg25EUYUeIhKHXjOinK4BgCcDwtLHjqaxCDsMy5nbnUMkKFvIhMVCp+5GFUXQ4Nr8lBsPqtGAqBenbpFqAA2g==", "dev": true, "requires": { "prettier-linter-helpers": "^1.0.0" } }, "eslint-plugin-simple-import-sort": { "version": "5.0.3", "resolved": "https://registry.npmjs.org/eslint-plugin-simple-import-sort/-/eslint-plugin-simple-import-sort-5.0.3.tgz", "integrity": "sha512-1rf3AWiHeWNCQdAq0iXNnlccnH1UDnelGgrPbjBBHE8d2hXVtOudcmy0vTF4hri3iJ0MKz8jBhmH6lJ0ZWZLHQ==", "dev": true }, "eslint-scope": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", "dev": true, "requires": { "esrecurse": "^4.3.0", "estraverse": "^4.1.1" } }, "eslint-utils": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-2.1.0.tgz", "integrity": "sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg==", "dev": true, "requires": { "eslint-visitor-keys": "^1.1.0" } }, "eslint-visitor-keys": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", "dev": true }, "espree": { "version": "7.3.1", "resolved": "https://registry.npmjs.org/espree/-/espree-7.3.1.tgz", "integrity": "sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g==", "dev": true, "requires": { "acorn": "^7.4.0", "acorn-jsx": "^5.3.1", "eslint-visitor-keys": "^1.3.0" } }, "esprima": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", "dev": true }, "esquery": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz", "integrity": "sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w==", "dev": true, "requires": { "estraverse": "^5.1.0" }, "dependencies": { "estraverse": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", "dev": true } } }, "esrecurse": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", "dev": true, "requires": { "estraverse": "^5.2.0" }, "dependencies": { "estraverse": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", "dev": true } } }, "estraverse": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", "dev": true }, "esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", "dev": true }, "event-emitter": { "version": "0.3.5", "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.5.tgz", "integrity": "sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==", "requires": { "d": "1", "es5-ext": "~0.10.14" } }, "exec-limiter": { "version": "3.2.13", "resolved": "https://registry.npmjs.org/exec-limiter/-/exec-limiter-3.2.13.tgz", "integrity": "sha512-86Ri699bwiHZVBzTzNj8gspqAhCPchg70zPVWIh3qzUOA1pUMcb272Em3LPk8AE0mS95B9yMJhtqF8vFJAn0dA==", "requires": { "limit-it": "^3.0.0", "typpy": "^2.1.0" } }, "exec-sh": { "version": "0.3.6", "resolved": "https://registry.npmjs.org/exec-sh/-/exec-sh-0.3.6.tgz", "integrity": "sha512-nQn+hI3yp+oD0huYhKwvYI32+JFeq+XkNcD1GAo3Y/MjxsfVGmrrzrnzjWiNY6f+pUCP440fThsFh5gZrRAU/w==", "dev": true }, "execa": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", "dev": true, "requires": { "cross-spawn": "^6.0.0", "get-stream": "^4.0.0", "is-stream": "^1.1.0", "npm-run-path": "^2.0.0", "p-finally": "^1.0.0", "signal-exit": "^3.0.0", "strip-eof": "^1.0.0" }, "dependencies": { "cross-spawn": { "version": "6.0.5", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", "dev": true, "requires": { "nice-try": "^1.0.4", "path-key": "^2.0.1", "semver": "^5.5.0", "shebang-command": "^1.2.0", "which": "^1.2.9" } }, "path-key": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", "dev": true }, "shebang-command": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", "dev": true, "requires": { "shebang-regex": "^1.0.0" } }, "shebang-regex": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", "dev": true }, "which": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", "dev": true, "requires": { "isexe": "^2.0.0" } } } }, "exit": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", "dev": true }, "expand-brackets": { "version": "2.1.4", "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", "dev": true, "requires": { "debug": "^2.3.3", "define-property": "^0.2.5", "extend-shallow": "^2.0.1", "posix-character-classes": "^0.1.0", "regex-not": "^1.0.0", "snapdragon": "^0.8.1", "to-regex": "^3.0.1" }, "dependencies": { "debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "dev": true, "requires": { "ms": "2.0.0" } }, "define-property": { "version": "0.2.5", "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", "dev": true, "requires": { "is-descriptor": "^0.1.0" } }, "extend-shallow": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { "is-extendable": "^0.1.0" } }, "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true } } }, "expect": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/expect/-/expect-26.6.2.tgz", "integrity": "sha512-9/hlOBkQl2l/PLHJx6JjoDF6xPKcJEsUlWKb23rKE7KzeDqUZKXKNMW27KIue5JMdBV9HgmoJPcc8HtO85t9IA==", "dev": true, "requires": { "@jest/types": "^26.6.2", "ansi-styles": "^4.0.0", "jest-get-type": "^26.3.0", "jest-matcher-utils": "^26.6.2", "jest-message-util": "^26.6.2", "jest-regex-util": "^26.0.0" }, "dependencies": { "ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { "color-convert": "^2.0.1" } }, "color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "requires": { "color-name": "~1.1.4" } }, "color-name": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true } } }, "ext": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/ext/-/ext-1.7.0.tgz", "integrity": "sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==", "requires": { "type": "^2.7.2" } }, "extend-shallow": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz", "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", "dev": true, "requires": { "assign-symbols": "^1.0.0", "is-extendable": "^1.0.1" }, "dependencies": { "is-extendable": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", "dev": true, "requires": { "is-plain-object": "^2.0.4" } } } }, "external-editor": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", "dev": true, "requires": { "chardet": "^0.7.0", "iconv-lite": "^0.4.24", "tmp": "^0.0.33" } }, "extglob": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", "dev": true, "requires": { "array-unique": "^0.3.2", "define-property": "^1.0.0", "expand-brackets": "^2.1.4", "extend-shallow": "^2.0.1", "fragment-cache": "^0.2.1", "regex-not": "^1.0.0", "snapdragon": "^0.8.1", "to-regex": "^3.0.1" }, "dependencies": { "define-property": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", "dev": true, "requires": { "is-descriptor": "^1.0.0" } }, "extend-shallow": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { "is-extendable": "^0.1.0" } }, "is-accessor-descriptor": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", "dev": true, "requires": { "kind-of": "^6.0.0" } }, "is-data-descriptor": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", "dev": true, "requires": { "kind-of": "^6.0.0" } }, "is-descriptor": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", "dev": true, "requires": { "is-accessor-descriptor": "^1.0.0", "is-data-descriptor": "^1.0.0", "kind-of": "^6.0.2" } } } }, "fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "dev": true }, "fast-diff": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.2.0.tgz", "integrity": "sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w==", "dev": true }, "fast-json-stable-stringify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", "dev": true }, "fast-levenshtein": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", "dev": true }, "fb-watchman": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.1.tgz", "integrity": "sha512-DkPJKQeY6kKwmuMretBhr7G6Vodr7bFwDYTXIkfG1gjvNpaxBTQV3PbXg6bR1c1UP4jPOX0jHUbbHANL9vRjVg==", "dev": true, "requires": { "bser": "2.1.1" } }, "figures": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", "dev": true, "requires": { "escape-string-regexp": "^1.0.5" } }, "file-entry-cache": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", "dev": true, "requires": { "flat-cache": "^3.0.4" } }, "fill-range": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", "dev": true, "requires": { "to-regex-range": "^5.0.1" } }, "find-replace": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-3.0.0.tgz", "integrity": "sha512-6Tb2myMioCAgv5kfvP5/PkZZ/ntTpVK39fHY7WkWBgvbeE+VHd/tZuZ4mrC+bxh4cfOZeYKVPaJIZtZXV7GNCQ==", "dev": true, "requires": { "array-back": "^3.0.1" } }, "find-up": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, "requires": { "locate-path": "^5.0.0", "path-exists": "^4.0.0" } }, "flat-cache": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.0.4.tgz", "integrity": "sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg==", "dev": true, "requires": { "flatted": "^3.1.0", "rimraf": "^3.0.2" }, "dependencies": { "rimraf": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", "dev": true, "requires": { "glob": "^7.1.3" } } } }, "flatted": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.2.tgz", "integrity": "sha512-JaTY/wtrcSyvXJl4IMFHPKyFur1sE9AUqc0QnhOaJ0CxHtAoIV8pYDzeEfAaNEtGkOfq4gr3LBFmdXW5mOQFnA==", "dev": true }, "for-in": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", "dev": true }, "form-data": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz", "integrity": "sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==", "dev": true, "requires": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "mime-types": "^2.1.12" } }, "fragment-cache": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", "dev": true, "requires": { "map-cache": "^0.2.2" } }, "frb": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/frb/-/frb-4.0.3.tgz", "integrity": "sha512-ZdRVqQM72pttQpvuae2GCGfoa5Z7zJUc7jGFSBZJhgeiC8lh2OlUwP0lEmRE2xlaFDrAVzTcyxFmuev/M5KzLg==", "requires": { "collections": "^5.1.3" } }, "fs-minipass": { "version": "1.2.7", "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-1.2.7.tgz", "integrity": "sha512-GWSSJGFy4e9GUeCcbIkED+bgAoFyj7XF1mV8rma3QW4NIqX9Kyx79N/PF61H5udOV3aY1IaMLs6pGbH71nlCTA==", "requires": { "minipass": "^2.6.0" } }, "fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" }, "fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "dev": true, "optional": true }, "function-bind": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", "dev": true }, "function.name": { "version": "1.0.13", "resolved": "https://registry.npmjs.org/function.name/-/function.name-1.0.13.tgz", "integrity": "sha512-mVrqdoy5npWZyoXl4DxCeuVF6delDcQjVS9aPdvLYlBxtMTZDR2B5GVEQEoM1jJyspCqg3C0v4ABkLE7tp9xFA==", "requires": { "noop6": "^1.0.1" } }, "functional-red-black-tree": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", "dev": true }, "gauge": { "version": "2.7.4", "resolved": "https://registry.npmjs.org/gauge/-/gauge-2.7.4.tgz", "integrity": "sha1-LANAXHU4w51+s3sxcCLjJfsBi/c=", "requires": { "aproba": "^1.0.3", "console-control-strings": "^1.0.0", "has-unicode": "^2.0.0", "object-assign": "^4.1.0", "signal-exit": "^3.0.0", "string-width": "^1.0.1", "strip-ansi": "^3.0.1", "wide-align": "^1.1.0" } }, "gensync": { "version": "1.0.0-beta.2", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", "dev": true }, "get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true }, "get-package-type": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", "dev": true }, "get-stdin": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-6.0.0.tgz", "integrity": "sha512-jp4tHawyV7+fkkSKyvjuLZswblUtz+SQKzSWnBbii16BuZksJlU1wuBYXY75r+duh/llF1ur6oNwi+2ZzjKZ7g==", "dev": true }, "get-stream": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz", "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==", "dev": true, "requires": { "pump": "^3.0.0" } }, "get-value": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=", "dev": true }, "git-config": { "version": "0.0.7", "resolved": "https://registry.npmjs.org/git-config/-/git-config-0.0.7.tgz", "integrity": "sha1-qcij7wendsPXImE1bYtye2IgKyg=", "dev": true, "requires": { "iniparser": "~1.0.5" } }, "git-package-json": { "version": "1.4.10", "resolved": "https://registry.npmjs.org/git-package-json/-/git-package-json-1.4.10.tgz", "integrity": "sha512-DRAcvbzd2SxGK7w8OgYfvKqhFliT5keX0lmSmVdgScgf1kkl5tbbo7Pam6uYoCa1liOiipKxQZG8quCtGWl/fA==", "requires": { "deffy": "^2.2.1", "err": "^1.1.1", "gry": "^5.0.0", "normalize-package-data": "^2.3.5", "oargv": "^3.4.1", "one-by-one": "^3.1.0", "r-json": "^1.2.1", "r-package-json": "^1.0.0", "tmp": "0.0.28" }, "dependencies": { "tmp": { "version": "0.0.28", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.28.tgz", "integrity": "sha512-c2mmfiBmND6SOVxzogm1oda0OJ1HZVIk/5n26N59dDTh80MUeavpiCls4PGAdkX1PFkKokLpcf7prSjCeXLsJg==", "requires": { "os-tmpdir": "~1.0.1" } } } }, "git-source": { "version": "1.1.10", "resolved": "https://registry.npmjs.org/git-source/-/git-source-1.1.10.tgz", "integrity": "sha512-XZZ7ZgnLL35oLgM/xjnLYgtlKlxJG0FohC1kWDvGkU7s1VKGXK0pFF/g1itQEwQ3D+uTQzBnzPi8XbqOv7Wc1Q==", "requires": { "git-url-parse": "^5.0.1" } }, "git-up": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/git-up/-/git-up-1.2.1.tgz", "integrity": "sha512-SRVN3rOLACva8imc7BFrB6ts5iISWKH1/h/1Z+JZYoUI7UVQM7gQqk4M2yxUENbq2jUUT09NEND5xwP1i7Ktlw==", "requires": { "is-ssh": "^1.0.0", "parse-url": "^1.0.0" } }, "git-url-parse": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/git-url-parse/-/git-url-parse-5.0.1.tgz", "integrity": "sha512-4uSiOgrryNEMBX+gTWogenYRUh2j1D+95STTSEF2RCTgLkfJikl8c7BGr0Bn274hwuxTsbS2/FQ5pVS9FoXegQ==", "requires": { "git-up": "^1.0.0" } }, "glob": { "version": "7.1.6", "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.0.4", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "glob-parent": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dev": true, "requires": { "is-glob": "^4.0.1" } }, "globals": { "version": "13.11.0", "resolved": "https://registry.npmjs.org/globals/-/globals-13.11.0.tgz", "integrity": "sha512-08/xrJ7wQjK9kkkRoI3OFUBbLx4f+6x3SGwcPvQ0QH6goFDrOU2oyAWrmh3dJezu65buo+HBMzAMQy6rovVC3g==", "dev": true, "requires": { "type-fest": "^0.20.2" } }, "got": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/got/-/got-5.7.1.tgz", "integrity": "sha512-1qd54GLxvVgzuidFmw9ze9umxS3rzhdBH6Wt6BTYrTQUXTN01vGGYXwzLzYLowNx8HBH3/c7kRyvx90fh13i7Q==", "requires": { "create-error-class": "^3.0.1", "duplexer2": "^0.1.4", "is-redirect": "^1.0.0", "is-retry-allowed": "^1.0.0", "is-stream": "^1.0.0", "lowercase-keys": "^1.0.0", "node-status-codes": "^1.0.0", "object-assign": "^4.0.1", "parse-json": "^2.1.0", "pinkie-promise": "^2.0.0", "read-all-stream": "^3.0.0", "readable-stream": "^2.0.5", "timed-out": "^3.0.0", "unzip-response": "^1.0.2", "url-parse-lax": "^1.0.0" }, "dependencies": { "parse-json": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", "integrity": "sha512-QR/GGaKCkhwk1ePQNYDRKYZ3mwU9ypsKhB0XyFnLQdomyEqk3e8wpW3V5Jp88zbxK4n5ST1nqo+g9juTpownhQ==", "requires": { "error-ex": "^1.2.0" } } } }, "graceful-fs": { "version": "4.2.8", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.8.tgz", "integrity": "sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg==", "dev": true }, "growly": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/growly/-/growly-1.3.0.tgz", "integrity": "sha1-8QdIy+dq+WS3yWyTxrzCivEgwIE=", "dev": true, "optional": true }, "gry": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/gry/-/gry-5.0.8.tgz", "integrity": "sha512-meq9ZjYVpLzZh3ojhTg7IMad9grGsx6rUUKHLqPnhLXzJkRQvEL2U3tQpS5/WentYTtHtxkT3Ew/mb10D6F6/g==", "requires": { "abs": "^1.2.1", "exec-limiter": "^3.0.0", "one-by-one": "^3.0.0", "ul": "^5.0.0" } }, "handlebars": { "version": "4.7.7", "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.7.tgz", "integrity": "sha512-aAcXm5OAfE/8IXkcZvCepKU3VzW1/39Fb5ZuqMtgI/hT8X2YgoMvBY5dLhq/cpOvw7Lk1nK/UF71aLG/ZnVYRA==", "dev": true, "requires": { "minimist": "^1.2.5", "neo-async": "^2.6.0", "source-map": "^0.6.1", "uglify-js": "^3.1.4", "wordwrap": "^1.0.0" } }, "has": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", "dev": true, "requires": { "function-bind": "^1.1.1" } }, "has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true }, "has-unicode": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=" }, "has-value": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", "dev": true, "requires": { "get-value": "^2.0.6", "has-values": "^1.0.0", "isobject": "^3.0.0" } }, "has-values": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/has-values/-/has-values-1.0.0.tgz", "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", "dev": true, "requires": { "is-number": "^3.0.0", "kind-of": "^4.0.0" }, "dependencies": { "is-number": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", "dev": true, "requires": { "kind-of": "^3.0.2" }, "dependencies": { "kind-of": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { "is-buffer": "^1.1.5" } } } }, "kind-of": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", "dev": true, "requires": { "is-buffer": "^1.1.5" } } } }, "hosted-git-info": { "version": "2.8.9", "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz", "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==" }, "html-encoding-sniffer": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-2.0.1.tgz", "integrity": "sha512-D5JbOMBIR/TVZkubHT+OyT2705QvogUW4IBn6nHd756OwieSF9aDYFj4dv6HHEVGYbHaLETa3WggZYWWMyy3ZQ==", "dev": true, "requires": { "whatwg-encoding": "^1.0.5" } }, "html-escaper": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", "dev": true }, "htmlparser2": { "version": "3.0.5", "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.0.5.tgz", "integrity": "sha512-O6tfy29gD7hjemI+HI0iJJNHH/YCkM44UO+9A7nJfmWhDi6g2rHUC05xnudONt214aqsBLHmdVnGXc2rPB8tsw==", "requires": { "domelementtype": "1", "domhandler": "2.0", "domutils": "1.1", "readable-stream": "1.0" }, "dependencies": { "isarray": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", "integrity": "sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ==" }, "readable-stream": { "version": "1.0.34", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", "integrity": "sha512-ok1qVCJuRkNmvebYikljxJA/UEsKwLl2nI1OmaqAu4/UE+h0wKCHok4XkL/gvi39OacXvw59RJUOFUkDib2rHg==", "requires": { "core-util-is": "~1.0.0", "inherits": "~2.0.1", "isarray": "0.0.1", "string_decoder": "~0.10.x" } }, "string_decoder": { "version": "0.10.31", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", "integrity": "sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ==" } } }, "http-proxy-agent": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz", "integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==", "dev": true, "requires": { "@tootallnate/once": "1", "agent-base": "6", "debug": "4" }, "dependencies": { "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", "dev": true, "requires": { "ms": "2.1.2" } } } }, "https-proxy-agent": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.0.tgz", "integrity": "sha512-EkYm5BcKUGiduxzSt3Eppko+PiNWNEpa4ySk9vTC6wDsQJW9rHSa+UhGNJoRYp7bz6Ht1eaRIa6QaJqO5rCFbA==", "dev": true, "requires": { "agent-base": "6", "debug": "4" }, "dependencies": { "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", "dev": true, "requires": { "ms": "2.1.2" } } } }, "human-signals": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-1.1.1.tgz", "integrity": "sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw==", "dev": true }, "iconv-lite": { "version": "0.4.24", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", "requires": { "safer-buffer": ">= 2.1.2 < 3" } }, "ignore": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", "dev": true }, "ignore-walk": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/ignore-walk/-/ignore-walk-3.0.3.tgz", "integrity": "sha512-m7o6xuOaT1aqheYHKf8W6J5pYH85ZI9w077erOzLje3JsB1gkafkAhHHY19dqjulgIZHFm32Cp5uNZgcQqdJKw==", "requires": { "minimatch": "^3.0.4" } }, "import-fresh": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", "dev": true, "requires": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" } }, "import-local": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.0.2.tgz", "integrity": "sha512-vjL3+w0oulAVZ0hBHnxa/Nm5TAurf9YLQJDhqRZyqb+VKGOB6LU8t9H1Nr5CIo16vh9XfJTOoHwU0B71S557gA==", "dev": true, "requires": { "pkg-dir": "^4.2.0", "resolve-cwd": "^3.0.0" } }, "imurmurhash": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", "dev": true }, "inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", "requires": { "once": "^1.3.0", "wrappy": "1" } }, "inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, "ini": { "version": "1.3.8", "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==" }, "iniparser": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/iniparser/-/iniparser-1.0.5.tgz", "integrity": "sha1-g21r7+bfv87gvM8c+fKsxwJ/eD0=", "dev": true }, "inquirer": { "version": "7.3.3", "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-7.3.3.tgz", "integrity": "sha512-JG3eIAj5V9CwcGvuOmoo6LB9kbAYT8HXffUl6memuszlwDC/qvFAJw49XJ5NROSFNPxp3iQg1GqkFhaY/CR0IA==", "dev": true, "requires": { "ansi-escapes": "^4.2.1", "chalk": "^4.1.0", "cli-cursor": "^3.1.0", "cli-width": "^3.0.0", "external-editor": "^3.0.3", "figures": "^3.0.0", "lodash": "^4.17.19", "mute-stream": "0.0.8", "run-async": "^2.4.0", "rxjs": "^6.6.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0", "through": "^2.3.6" }, "dependencies": { "ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true }, "string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, "requires": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, "requires": { "ansi-regex": "^5.0.1" } } } }, "interpret": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.4.0.tgz", "integrity": "sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA==", "dev": true }, "is-accessor-descriptor": { "version": "0.1.6", "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", "dev": true, "requires": { "kind-of": "^3.0.2" }, "dependencies": { "kind-of": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { "is-buffer": "^1.1.5" } } } }, "is-arrayish": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=" }, "is-buffer": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", "dev": true }, "is-ci": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz", "integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==", "dev": true, "requires": { "ci-info": "^2.0.0" } }, "is-core-module": { "version": "2.6.0", "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.6.0.tgz", "integrity": "sha512-wShG8vs60jKfPWpF2KZRaAtvt3a20OAn7+IJ6hLPECpSABLcKtFKTTI4ZtH5QcBruBHlq+WsdHWyz0BCZW7svQ==", "dev": true, "requires": { "has": "^1.0.3" } }, "is-data-descriptor": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", "dev": true, "requires": { "kind-of": "^3.0.2" }, "dependencies": { "kind-of": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { "is-buffer": "^1.1.5" } } } }, "is-descriptor": { "version": "0.1.6", "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", "dev": true, "requires": { "is-accessor-descriptor": "^0.1.6", "is-data-descriptor": "^0.1.4", "kind-of": "^5.0.0" }, "dependencies": { "kind-of": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", "dev": true } } }, "is-docker": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", "dev": true, "optional": true }, "is-extendable": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=", "dev": true }, "is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", "dev": true }, "is-fullwidth-code-point": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", "requires": { "number-is-nan": "^1.0.0" } }, "is-generator-fn": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", "dev": true }, "is-glob": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", "dev": true, "requires": { "is-extglob": "^2.1.1" } }, "is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "dev": true }, "is-plain-object": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", "dev": true, "requires": { "isobject": "^3.0.1" } }, "is-potential-custom-element-name": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", "dev": true }, "is-redirect": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-redirect/-/is-redirect-1.0.0.tgz", "integrity": "sha512-cr/SlUEe5zOGmzvj9bUyC4LVvkNVAXu4GytXLNMr1pny+a65MpQ9IJzFHD5vi7FyJgb4qt27+eS3TuQnqB+RQw==" }, "is-retry-allowed": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-1.2.0.tgz", "integrity": "sha512-RUbUeKwvm3XG2VYamhJL1xFktgjvPzL0Hq8C+6yrWIswDy3BIXGqCxhxkc30N9jqK311gVU137K8Ei55/zVJRg==" }, "is-ssh": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/is-ssh/-/is-ssh-1.4.0.tgz", "integrity": "sha512-x7+VxdxOdlV3CYpjvRLBv5Lo9OJerlYanjwFrPR9fuGPjCiNiCzFgAWpiLAohSbsnH4ZAys3SBh+hq5rJosxUQ==", "requires": { "protocols": "^2.0.1" } }, "is-stream": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=" }, "is-typedarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", "dev": true }, "is-windows": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", "dev": true }, "is-wsl": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", "dev": true, "optional": true, "requires": { "is-docker": "^2.0.0" } }, "isarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" }, "isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", "dev": true }, "isobject": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", "dev": true }, "istanbul-lib-coverage": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.0.0.tgz", "integrity": "sha512-UiUIqxMgRDET6eR+o5HbfRYP1l0hqkWOs7vNxC/mggutCMUIhWMm8gAHb8tHlyfD3/l6rlgNA5cKdDzEAf6hEg==", "dev": true }, "istanbul-lib-instrument": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-4.0.3.tgz", "integrity": "sha512-BXgQl9kf4WTCPCCpmFGoJkz/+uhvm7h7PFKUYxh7qarQd3ER33vHG//qaE8eN25l07YqZPpHXU9I09l/RD5aGQ==", "dev": true, "requires": { "@babel/core": "^7.7.5", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-coverage": "^3.0.0", "semver": "^6.3.0" }, "dependencies": { "semver": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", "dev": true } } }, "istanbul-lib-report": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", "dev": true, "requires": { "istanbul-lib-coverage": "^3.0.0", "make-dir": "^3.0.0", "supports-color": "^7.1.0" } }, "istanbul-lib-source-maps": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.0.tgz", "integrity": "sha512-c16LpFRkR8vQXyHZ5nLpY35JZtzj1PQY1iZmesUbf1FZHbIupcWfjgOXBY9YHkLEQ6puz1u4Dgj6qmU/DisrZg==", "dev": true, "requires": { "debug": "^4.1.1", "istanbul-lib-coverage": "^3.0.0", "source-map": "^0.6.1" }, "dependencies": { "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", "dev": true, "requires": { "ms": "2.1.2" } } } }, "istanbul-reports": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.0.2.tgz", "integrity": "sha512-9tZvz7AiR3PEDNGiV9vIouQ/EAcqMXFmkcA1CDFTwOB98OZVDL0PH9glHotf5Ugp6GCOTypfzGWI/OqjWNCRUw==", "dev": true, "requires": { "html-escaper": "^2.0.0", "istanbul-lib-report": "^3.0.0" } }, "iterate-object": { "version": "1.3.4", "resolved": "https://registry.npmjs.org/iterate-object/-/iterate-object-1.3.4.tgz", "integrity": "sha512-4dG1D1x/7g8PwHS9aK6QV5V94+ZvyP4+d19qDv43EzImmrndysIl4prmJ1hWWIGCqrZHyaHBm6BSEWHOLnpoNw==" }, "jest": { "version": "26.6.3", "resolved": "https://registry.npmjs.org/jest/-/jest-26.6.3.tgz", "integrity": "sha512-lGS5PXGAzR4RF7V5+XObhqz2KZIDUA1yD0DG6pBVmy10eh0ZIXQImRuzocsI/N2XZ1GrLFwTS27In2i2jlpq1Q==", "dev": true, "requires": { "@jest/core": "^26.6.3", "import-local": "^3.0.2", "jest-cli": "^26.6.3" }, "dependencies": { "jest-cli": { "version": "26.6.3", "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-26.6.3.tgz", "integrity": "sha512-GF9noBSa9t08pSyl3CY4frMrqp+aQXFGFkf5hEPbh/pIUFYWMK6ZLTfbmadxJVcJrdRoChlWQsA2VkJcDFK8hg==", "dev": true, "requires": { "@jest/core": "^26.6.3", "@jest/test-result": "^26.6.2", "@jest/types": "^26.6.2", "chalk": "^4.0.0", "exit": "^0.1.2", "graceful-fs": "^4.2.4", "import-local": "^3.0.2", "is-ci": "^2.0.0", "jest-config": "^26.6.3", "jest-util": "^26.6.2", "jest-validate": "^26.6.2", "prompts": "^2.0.1", "yargs": "^15.4.1" } } } }, "jest-changed-files": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-26.6.2.tgz", "integrity": "sha512-fDS7szLcY9sCtIip8Fjry9oGf3I2ht/QT21bAHm5Dmf0mD4X3ReNUf17y+bO6fR8WgbIZTlbyG1ak/53cbRzKQ==", "dev": true, "requires": { "@jest/types": "^26.6.2", "execa": "^4.0.0", "throat": "^5.0.0" }, "dependencies": { "execa": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/execa/-/execa-4.1.0.tgz", "integrity": "sha512-j5W0//W7f8UxAn8hXVnwG8tLwdiUy4FJLcSupCg6maBYZDpyBvTApK7KyuI4bKj8KOh1r2YH+6ucuYtJv1bTZA==", "dev": true, "requires": { "cross-spawn": "^7.0.0", "get-stream": "^5.0.0", "human-signals": "^1.1.1", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.0", "onetime": "^5.1.0", "signal-exit": "^3.0.2", "strip-final-newline": "^2.0.0" } }, "get-stream": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", "dev": true, "requires": { "pump": "^3.0.0" } }, "is-stream": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", "dev": true }, "npm-run-path": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", "dev": true, "requires": { "path-key": "^3.0.0" } } } }, "jest-config": { "version": "26.6.3", "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-26.6.3.tgz", "integrity": "sha512-t5qdIj/bCj2j7NFVHb2nFB4aUdfucDn3JRKgrZnplb8nieAirAzRSHP8uDEd+qV6ygzg9Pz4YG7UTJf94LPSyg==", "dev": true, "requires": { "@babel/core": "^7.1.0", "@jest/test-sequencer": "^26.6.3", "@jest/types": "^26.6.2", "babel-jest": "^26.6.3", "chalk": "^4.0.0", "deepmerge": "^4.2.2", "glob": "^7.1.1", "graceful-fs": "^4.2.4", "jest-environment-jsdom": "^26.6.2", "jest-environment-node": "^26.6.2", "jest-get-type": "^26.3.0", "jest-jasmine2": "^26.6.3", "jest-regex-util": "^26.0.0", "jest-resolve": "^26.6.2", "jest-util": "^26.6.2", "jest-validate": "^26.6.2", "micromatch": "^4.0.2", "pretty-format": "^26.6.2" } }, "jest-diff": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-26.6.2.tgz", "integrity": "sha512-6m+9Z3Gv9wN0WFVasqjCL/06+EFCMTqDEUl/b87HYK2rAPTyfz4ZIuSlPhY51PIQRWx5TaxeF1qmXKe9gfN3sA==", "dev": true, "requires": { "chalk": "^4.0.0", "diff-sequences": "^26.6.2", "jest-get-type": "^26.3.0", "pretty-format": "^26.6.2" } }, "jest-docblock": { "version": "26.0.0", "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-26.0.0.tgz", "integrity": "sha512-RDZ4Iz3QbtRWycd8bUEPxQsTlYazfYn/h5R65Fc6gOfwozFhoImx+affzky/FFBuqISPTqjXomoIGJVKBWoo0w==", "dev": true, "requires": { "detect-newline": "^3.0.0" } }, "jest-each": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-26.6.2.tgz", "integrity": "sha512-Mer/f0KaATbjl8MCJ+0GEpNdqmnVmDYqCTJYTvoo7rqmRiDllmp2AYN+06F93nXcY3ur9ShIjS+CO/uD+BbH4A==", "dev": true, "requires": { "@jest/types": "^26.6.2", "chalk": "^4.0.0", "jest-get-type": "^26.3.0", "jest-util": "^26.6.2", "pretty-format": "^26.6.2" } }, "jest-environment-jsdom": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-26.6.2.tgz", "integrity": "sha512-jgPqCruTlt3Kwqg5/WVFyHIOJHsiAvhcp2qiR2QQstuG9yWox5+iHpU3ZrcBxW14T4fe5Z68jAfLRh7joCSP2Q==", "dev": true, "requires": { "@jest/environment": "^26.6.2", "@jest/fake-timers": "^26.6.2", "@jest/types": "^26.6.2", "@types/node": "*", "jest-mock": "^26.6.2", "jest-util": "^26.6.2", "jsdom": "^16.4.0" } }, "jest-environment-node": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-26.6.2.tgz", "integrity": "sha512-zhtMio3Exty18dy8ee8eJ9kjnRyZC1N4C1Nt/VShN1apyXc8rWGtJ9lI7vqiWcyyXS4BVSEn9lxAM2D+07/Tag==", "dev": true, "requires": { "@jest/environment": "^26.6.2", "@jest/fake-timers": "^26.6.2", "@jest/types": "^26.6.2", "@types/node": "*", "jest-mock": "^26.6.2", "jest-util": "^26.6.2" } }, "jest-get-type": { "version": "26.3.0", "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-26.3.0.tgz", "integrity": "sha512-TpfaviN1R2pQWkIihlfEanwOXK0zcxrKEE4MlU6Tn7keoXdN6/3gK/xl0yEh8DOunn5pOVGKf8hB4R9gVh04ig==", "dev": true }, "jest-haste-map": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-26.6.2.tgz", "integrity": "sha512-easWIJXIw71B2RdR8kgqpjQrbMRWQBgiBwXYEhtGUTaX+doCjBheluShdDMeR8IMfJiTqH4+zfhtg29apJf/8w==", "dev": true, "requires": { "@jest/types": "^26.6.2", "@types/graceful-fs": "^4.1.2", "@types/node": "*", "anymatch": "^3.0.3", "fb-watchman": "^2.0.0", "fsevents": "^2.1.2", "graceful-fs": "^4.2.4", "jest-regex-util": "^26.0.0", "jest-serializer": "^26.6.2", "jest-util": "^26.6.2", "jest-worker": "^26.6.2", "micromatch": "^4.0.2", "sane": "^4.0.3", "walker": "^1.0.7" } }, "jest-jasmine2": { "version": "26.6.3", "resolved": "https://registry.npmjs.org/jest-jasmine2/-/jest-jasmine2-26.6.3.tgz", "integrity": "sha512-kPKUrQtc8aYwBV7CqBg5pu+tmYXlvFlSFYn18ev4gPFtrRzB15N2gW/Roew3187q2w2eHuu0MU9TJz6w0/nPEg==", "dev": true, "requires": { "@babel/traverse": "^7.1.0", "@jest/environment": "^26.6.2", "@jest/source-map": "^26.6.2", "@jest/test-result": "^26.6.2", "@jest/types": "^26.6.2", "@types/node": "*", "chalk": "^4.0.0", "co": "^4.6.0", "expect": "^26.6.2", "is-generator-fn": "^2.0.0", "jest-each": "^26.6.2", "jest-matcher-utils": "^26.6.2", "jest-message-util": "^26.6.2", "jest-runtime": "^26.6.3", "jest-snapshot": "^26.6.2", "jest-util": "^26.6.2", "pretty-format": "^26.6.2", "throat": "^5.0.0" } }, "jest-leak-detector": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-26.6.2.tgz", "integrity": "sha512-i4xlXpsVSMeKvg2cEKdfhh0H39qlJlP5Ex1yQxwF9ubahboQYMgTtz5oML35AVA3B4Eu+YsmwaiKVev9KCvLxg==", "dev": true, "requires": { "jest-get-type": "^26.3.0", "pretty-format": "^26.6.2" } }, "jest-matcher-utils": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-26.6.2.tgz", "integrity": "sha512-llnc8vQgYcNqDrqRDXWwMr9i7rS5XFiCwvh6DTP7Jqa2mqpcCBBlpCbn+trkG0KNhPu/h8rzyBkriOtBstvWhw==", "dev": true, "requires": { "chalk": "^4.0.0", "jest-diff": "^26.6.2", "jest-get-type": "^26.3.0", "pretty-format": "^26.6.2" } }, "jest-message-util": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-26.6.2.tgz", "integrity": "sha512-rGiLePzQ3AzwUshu2+Rn+UMFk0pHN58sOG+IaJbk5Jxuqo3NYO1U2/MIR4S1sKgsoYSXSzdtSa0TgrmtUwEbmA==", "dev": true, "requires": { "@babel/code-frame": "^7.0.0", "@jest/types": "^26.6.2", "@types/stack-utils": "^2.0.0", "chalk": "^4.0.0", "graceful-fs": "^4.2.4", "micromatch": "^4.0.2", "pretty-format": "^26.6.2", "slash": "^3.0.0", "stack-utils": "^2.0.2" } }, "jest-mock": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-26.6.2.tgz", "integrity": "sha512-YyFjePHHp1LzpzYcmgqkJ0nm0gg/lJx2aZFzFy1S6eUqNjXsOqTK10zNRff2dNfssgokjkG65OlWNcIlgd3zew==", "dev": true, "requires": { "@jest/types": "^26.6.2", "@types/node": "*" } }, "jest-pnp-resolver": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.2.tgz", "integrity": "sha512-olV41bKSMm8BdnuMsewT4jqlZ8+3TCARAXjZGT9jcoSnrfUnRCqnMoF9XEeoWjbzObpqF9dRhHQj0Xb9QdF6/w==", "dev": true }, "jest-regex-util": { "version": "26.0.0", "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-26.0.0.tgz", "integrity": "sha512-Gv3ZIs/nA48/Zvjrl34bf+oD76JHiGDUxNOVgUjh3j890sblXryjY4rss71fPtD/njchl6PSE2hIhvyWa1eT0A==", "dev": true }, "jest-resolve": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-26.6.2.tgz", "integrity": "sha512-sOxsZOq25mT1wRsfHcbtkInS+Ek7Q8jCHUB0ZUTP0tc/c41QHriU/NunqMfCUWsL4H3MHpvQD4QR9kSYhS7UvQ==", "dev": true, "requires": { "@jest/types": "^26.6.2", "chalk": "^4.0.0", "graceful-fs": "^4.2.4", "jest-pnp-resolver": "^1.2.2", "jest-util": "^26.6.2", "read-pkg-up": "^7.0.1", "resolve": "^1.18.1", "slash": "^3.0.0" }, "dependencies": { "resolve": { "version": "1.20.0", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", "dev": true, "requires": { "is-core-module": "^2.2.0", "path-parse": "^1.0.6" } } } }, "jest-resolve-dependencies": { "version": "26.6.3", "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-26.6.3.tgz", "integrity": "sha512-pVwUjJkxbhe4RY8QEWzN3vns2kqyuldKpxlxJlzEYfKSvY6/bMvxoFrYYzUO1Gx28yKWN37qyV7rIoIp2h8fTg==", "dev": true, "requires": { "@jest/types": "^26.6.2", "jest-regex-util": "^26.0.0", "jest-snapshot": "^26.6.2" } }, "jest-runner": { "version": "26.6.3", "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-26.6.3.tgz", "integrity": "sha512-atgKpRHnaA2OvByG/HpGA4g6CSPS/1LK0jK3gATJAoptC1ojltpmVlYC3TYgdmGp+GLuhzpH30Gvs36szSL2JQ==", "dev": true, "requires": { "@jest/console": "^26.6.2", "@jest/environment": "^26.6.2", "@jest/test-result": "^26.6.2", "@jest/types": "^26.6.2", "@types/node": "*", "chalk": "^4.0.0", "emittery": "^0.7.1", "exit": "^0.1.2", "graceful-fs": "^4.2.4", "jest-config": "^26.6.3", "jest-docblock": "^26.0.0", "jest-haste-map": "^26.6.2", "jest-leak-detector": "^26.6.2", "jest-message-util": "^26.6.2", "jest-resolve": "^26.6.2", "jest-runtime": "^26.6.3", "jest-util": "^26.6.2", "jest-worker": "^26.6.2", "source-map-support": "^0.5.6", "throat": "^5.0.0" } }, "jest-runtime": { "version": "26.6.3", "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-26.6.3.tgz", "integrity": "sha512-lrzyR3N8sacTAMeonbqpnSka1dHNux2uk0qqDXVkMv2c/A3wYnvQ4EXuI013Y6+gSKSCxdaczvf4HF0mVXHRdw==", "dev": true, "requires": { "@jest/console": "^26.6.2", "@jest/environment": "^26.6.2", "@jest/fake-timers": "^26.6.2", "@jest/globals": "^26.6.2", "@jest/source-map": "^26.6.2", "@jest/test-result": "^26.6.2", "@jest/transform": "^26.6.2", "@jest/types": "^26.6.2", "@types/yargs": "^15.0.0", "chalk": "^4.0.0", "cjs-module-lexer": "^0.6.0", "collect-v8-coverage": "^1.0.0", "exit": "^0.1.2", "glob": "^7.1.3", "graceful-fs": "^4.2.4", "jest-config": "^26.6.3", "jest-haste-map": "^26.6.2", "jest-message-util": "^26.6.2", "jest-mock": "^26.6.2", "jest-regex-util": "^26.0.0", "jest-resolve": "^26.6.2", "jest-snapshot": "^26.6.2", "jest-util": "^26.6.2", "jest-validate": "^26.6.2", "slash": "^3.0.0", "strip-bom": "^4.0.0", "yargs": "^15.4.1" } }, "jest-serializer": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-serializer/-/jest-serializer-26.6.2.tgz", "integrity": "sha512-S5wqyz0DXnNJPd/xfIzZ5Xnp1HrJWBczg8mMfMpN78OJ5eDxXyf+Ygld9wX1DnUWbIbhM1YDY95NjR4CBXkb2g==", "dev": true, "requires": { "@types/node": "*", "graceful-fs": "^4.2.4" } }, "jest-snapshot": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-26.6.2.tgz", "integrity": "sha512-OLhxz05EzUtsAmOMzuupt1lHYXCNib0ECyuZ/PZOx9TrZcC8vL0x+DUG3TL+GLX3yHG45e6YGjIm0XwDc3q3og==", "dev": true, "requires": { "@babel/types": "^7.0.0", "@jest/types": "^26.6.2", "@types/babel__traverse": "^7.0.4", "@types/prettier": "^2.0.0", "chalk": "^4.0.0", "expect": "^26.6.2", "graceful-fs": "^4.2.4", "jest-diff": "^26.6.2", "jest-get-type": "^26.3.0", "jest-haste-map": "^26.6.2", "jest-matcher-utils": "^26.6.2", "jest-message-util": "^26.6.2", "jest-resolve": "^26.6.2", "natural-compare": "^1.4.0", "pretty-format": "^26.6.2", "semver": "^7.3.2" }, "dependencies": { "semver": { "version": "7.3.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", "dev": true, "requires": { "lru-cache": "^6.0.0" } } } }, "jest-util": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-26.6.2.tgz", "integrity": "sha512-MDW0fKfsn0OI7MS7Euz6h8HNDXVQ0gaM9uW6RjfDmd1DAFcaxX9OqIakHIqhbnmF08Cf2DLDG+ulq8YQQ0Lp0Q==", "dev": true, "requires": { "@jest/types": "^26.6.2", "@types/node": "*", "chalk": "^4.0.0", "graceful-fs": "^4.2.4", "is-ci": "^2.0.0", "micromatch": "^4.0.2" } }, "jest-validate": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-26.6.2.tgz", "integrity": "sha512-NEYZ9Aeyj0i5rQqbq+tpIOom0YS1u2MVu6+euBsvpgIme+FOfRmoC4R5p0JiAUpaFvFy24xgrpMknarR/93XjQ==", "dev": true, "requires": { "@jest/types": "^26.6.2", "camelcase": "^6.0.0", "chalk": "^4.0.0", "jest-get-type": "^26.3.0", "leven": "^3.1.0", "pretty-format": "^26.6.2" }, "dependencies": { "camelcase": { "version": "6.2.0", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.2.0.tgz", "integrity": "sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg==", "dev": true } } }, "jest-watcher": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-26.6.2.tgz", "integrity": "sha512-WKJob0P/Em2csiVthsI68p6aGKTIcsfjH9Gsx1f0A3Italz43e3ho0geSAVsmj09RWOELP1AZ/DXyJgOgDKxXQ==", "dev": true, "requires": { "@jest/test-result": "^26.6.2", "@jest/types": "^26.6.2", "@types/node": "*", "ansi-escapes": "^4.2.1", "chalk": "^4.0.0", "jest-util": "^26.6.2", "string-length": "^4.0.1" } }, "jest-worker": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-26.6.2.tgz", "integrity": "sha512-KWYVV1c4i+jbMpaBC+U++4Va0cp8OisU185o73T1vo99hqi7w8tSJfUXYswwqqrjzwxa6KpRK54WhPvwf5w6PQ==", "dev": true, "requires": { "@types/node": "*", "merge-stream": "^2.0.0", "supports-color": "^7.0.0" } }, "js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", "dev": true }, "js-yaml": { "version": "3.14.1", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", "dev": true, "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" } }, "jsdoctypeparser": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/jsdoctypeparser/-/jsdoctypeparser-9.0.0.tgz", "integrity": "sha512-jrTA2jJIL6/DAEILBEh2/w9QxCuwmvNXIry39Ay/HVfhE3o2yVV0U44blYkqdHA/OKloJEqvJy0xU+GSdE2SIw==", "dev": true }, "jsdom": { "version": "16.7.0", "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-16.7.0.tgz", "integrity": "sha512-u9Smc2G1USStM+s/x1ru5Sxrl6mPYCbByG1U/hUmqaVsm4tbNyS7CicOSRyuGQYZhTu0h84qkZZQ/I+dzizSVw==", "dev": true, "requires": { "abab": "^2.0.5", "acorn": "^8.2.4", "acorn-globals": "^6.0.0", "cssom": "^0.4.4", "cssstyle": "^2.3.0", "data-urls": "^2.0.0", "decimal.js": "^10.2.1", "domexception": "^2.0.1", "escodegen": "^2.0.0", "form-data": "^3.0.0", "html-encoding-sniffer": "^2.0.1", "http-proxy-agent": "^4.0.1", "https-proxy-agent": "^5.0.0", "is-potential-custom-element-name": "^1.0.1", "nwsapi": "^2.2.0", "parse5": "6.0.1", "saxes": "^5.0.1", "symbol-tree": "^3.2.4", "tough-cookie": "^4.0.0", "w3c-hr-time": "^1.0.2", "w3c-xmlserializer": "^2.0.0", "webidl-conversions": "^6.1.0", "whatwg-encoding": "^1.0.5", "whatwg-mimetype": "^2.3.0", "whatwg-url": "^8.5.0", "ws": "^7.4.6", "xml-name-validator": "^3.0.0" }, "dependencies": { "acorn": { "version": "8.4.1", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.4.1.tgz", "integrity": "sha512-asabaBSkEKosYKMITunzX177CXxQ4Q8BSSzMTKD+FefUhipQC70gfW5SiUDhYQ3vk8G+81HqQk7Fv9OXwwn9KA==", "dev": true } } }, "jsesc": { "version": "2.5.2", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", "dev": true }, "json-parse-even-better-errors": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", "dev": true }, "json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", "dev": true }, "json-stable-stringify-without-jsonify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", "dev": true }, "json5": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", "dev": true }, "kind-of": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", "dev": true }, "kleur": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", "dev": true }, "leven": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", "dev": true }, "levn": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", "dev": true, "requires": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "limit-it": { "version": "3.2.10", "resolved": "https://registry.npmjs.org/limit-it/-/limit-it-3.2.10.tgz", "integrity": "sha512-T0NK99pHnkimldr1WUqvbGV1oWDku/xC9J/OqzJFsV1jeOS6Bwl8W7vkeQIBqwiON9dTALws+rX/XPMQqWerDQ==", "requires": { "typpy": "^2.0.0" } }, "lines-and-columns": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.1.6.tgz", "integrity": "sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA=", "dev": true }, "locate-path": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, "requires": { "p-locate": "^4.1.0" } }, "lodash": { "version": "4.17.21", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "dev": true }, "lodash.camelcase": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", "integrity": "sha1-soqmKIorn8ZRA1x3EfZathkDMaY=" }, "lodash.clonedeep": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", "integrity": "sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=", "dev": true }, "lodash.kebabcase": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/lodash.kebabcase/-/lodash.kebabcase-4.1.1.tgz", "integrity": "sha512-N8XRTIMMqqDgSy4VLKPnJ/+hpGZN+PHQiJnSenYqPaVV/NCqEogTnAdZLQiGKhxX+JCs8waWq2t1XHWKOmlY8g==" }, "lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", "dev": true }, "lodash.snakecase": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==" }, "lodash.trim": { "version": "4.5.1", "resolved": "https://registry.npmjs.org/lodash.trim/-/lodash.trim-4.5.1.tgz", "integrity": "sha512-nJAlRl/K+eiOehWKDzoBVrSMhK0K3A3YQsUNXHQa5yIrKBAhsZgSu3KoAFoFT+mEgiyBHddZ0pRk1ITpIp90Wg==" }, "lodash.truncate": { "version": "4.4.2", "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", "integrity": "sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM=", "dev": true }, "lowercase-keys": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.1.tgz", "integrity": "sha512-G2Lj61tXDnVFFOi8VZds+SoQjtQC3dgokKdDG2mTm1tx4m50NUHBOZSBwQQHyy0V12A0JTG4icfZQH+xPyh8VA==" }, "lru-cache": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", "dev": true, "requires": { "yallist": "^4.0.0" }, "dependencies": { "yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "dev": true } } }, "make-dir": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", "dev": true, "requires": { "semver": "^6.0.0" }, "dependencies": { "semver": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", "dev": true } } }, "make-error": { "version": "1.3.6", "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", "dev": true }, "make-promises-safe": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/make-promises-safe/-/make-promises-safe-5.1.0.tgz", "integrity": "sha512-AfdZ49rtyhQR/6cqVKGoH7y4ql7XkS5HJI1lZm0/5N6CQosy1eYbBJ/qbhkKHzo17UH7M918Bysf6XB9f3kS1g==", "dev": true }, "makeerror": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.11.tgz", "integrity": "sha1-4BpckQnyr3lmDk6LlYd5AYT1qWw=", "dev": true, "requires": { "tmpl": "1.0.x" } }, "map-cache": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", "dev": true }, "map-visit": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", "dev": true, "requires": { "object-visit": "^1.0.0" } }, "merge-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", "dev": true }, "micromatch": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.4.tgz", "integrity": "sha512-pRmzw/XUcwXGpD9aI9q/0XOwLNygjETJ8y0ao0wdqprrzDa4YnxLcz7fQRZr8voh8V10kGhABbNcHVk5wHgWwg==", "dev": true, "requires": { "braces": "^3.0.1", "picomatch": "^2.2.3" } }, "mime": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==" }, "mime-db": { "version": "1.49.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.49.0.tgz", "integrity": "sha512-CIc8j9URtOVApSFCQIF+VBkX1RwXp/oMMOrqdyXSBXq5RWNEsRfyj1kiRnQgmNXmHxPoFIxOroKA3zcU9P+nAA==", "dev": true }, "mime-types": { "version": "2.1.32", "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.32.tgz", "integrity": "sha512-hJGaVS4G4c9TSMYh2n6SQAGrC4RnfU+daP8G7cSCmaqNjiOoUY0VHCMS42pxnQmVF1GWwFhbHWn3RIxCqTmZ9A==", "dev": true, "requires": { "mime-db": "1.49.0" } }, "mimeparse": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/mimeparse/-/mimeparse-0.1.4.tgz", "integrity": "sha512-jiuAsJJY4c0oF97oHKic9nva2y1QF2yhYJG3LXLys//f8SNQ89eFuGZ29z62Z29CAY4endJS6zFiKUtURFErog==" }, "mimic-fn": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", "dev": true }, "minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "requires": { "brace-expansion": "^1.1.7" } }, "minimist": { "version": "1.2.6", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==" }, "minipass": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/minipass/-/minipass-2.9.0.tgz", "integrity": "sha512-wxfUjg9WebH+CUDX/CdbRlh5SmfZiy/hpkxaRI16Y9W56Pa75sWgd/rvFilSgrauD9NyFymP/+JFV3KwzIsJeg==", "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0" } }, "minizlib": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-1.3.3.tgz", "integrity": "sha512-6ZYMOEnmVsdCeTJVE0W9ZD+pVnE8h9Hma/iOwwRDsdQoePpoX56/8B6z3P9VNwppJuBKNRuFDRNRqRWexT9G9Q==", "requires": { "minipass": "^2.9.0" } }, "mixin-deep": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.2.tgz", "integrity": "sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA==", "dev": true, "requires": { "for-in": "^1.0.2", "is-extendable": "^1.0.1" }, "dependencies": { "is-extendable": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", "dev": true, "requires": { "is-plain-object": "^2.0.4" } } } }, "mkdirp": { "version": "0.5.5", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", "requires": { "minimist": "^1.2.5" } }, "montage": { "version": "17.2.2", "resolved": "https://registry.npmjs.org/montage/-/montage-17.2.2.tgz", "integrity": "sha512-YITyDIFh2hRFMU2KJDmprqKhEx0l/bfIIJEGxeLI08GLytDnf2WY+jOfSKmCOuePQF/GhCTyDE7T5wDz2i6OOA==", "requires": { "bluebird": "~3.5.0", "collections": "~5.1.x", "frb": "~4.0.x", "htmlparser2": "~3.0.5", "lodash.camelcase": "^4.3.0", "lodash.kebabcase": "^4.1.1", "lodash.snakecase": "^4.1.1", "lodash.trim": "^4.5.1", "mr": "^17.0.11", "proxy-polyfill": "~0.1.7", "q-io": "^1.13.3", "weak-map": "^1.0.5" } }, "mr": { "version": "17.0.14", "resolved": "https://registry.npmjs.org/mr/-/mr-17.0.14.tgz", "integrity": "sha512-ADXntqwl7wStHsrFLJnoOt69Gv42lxuoccR0V/6fy1sLJDtH4beoA+YwOWQHNQ7kCF7lOCJaW8cBACdTy3qzUA==", "requires": { "bluebird": "~3.5.0" } }, "ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, "mute-stream": { "version": "0.0.8", "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", "dev": true }, "nanomatch": { "version": "1.2.13", "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz", "integrity": "sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==", "dev": true, "requires": { "arr-diff": "^4.0.0", "array-unique": "^0.3.2", "define-property": "^2.0.2", "extend-shallow": "^3.0.2", "fragment-cache": "^0.2.1", "is-windows": "^1.0.2", "kind-of": "^6.0.2", "object.pick": "^1.3.0", "regex-not": "^1.0.0", "snapdragon": "^0.8.1", "to-regex": "^3.0.1" } }, "native": { "version": "0.3.3", "resolved": "https://registry.npmjs.org/native/-/native-0.3.3.tgz", "integrity": "sha512-NtzhjGaXTMMCE2rkJ6kSZW+6UbPqdnlY5ZQ2PK+ZDRu5W3UiGqEBJqIRhaDdYywxaX9stFMDnPEv/hTvyhnbEg==", "requires": { "montage": ">=16.0.4" } }, "natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", "dev": true }, "needle": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/needle/-/needle-2.5.0.tgz", "integrity": "sha512-o/qITSDR0JCyCKEQ1/1bnUXMmznxabbwi/Y4WwJElf+evwJNFNwIDMCCt5IigFVxgeGBJESLohGtIS9gEzo1fA==", "requires": { "debug": "^3.2.6", "iconv-lite": "^0.4.4", "sax": "^1.2.4" } }, "neo-async": { "version": "2.6.2", "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", "dev": true }, "neon-cli": { "version": "0.9.1", "resolved": "https://registry.npmjs.org/neon-cli/-/neon-cli-0.9.1.tgz", "integrity": "sha512-iWwKjI1Q4o1lWVc4vkr59BXEYlBl5HggKx5ETw5kStpuvT1nVcolPtTdydisx8pLRRxN+gjER571DOGnA0Yxcg==", "dev": true, "requires": { "chalk": "^4.1.0", "command-line-args": "^5.1.1", "command-line-commands": "^3.0.1", "command-line-usage": "^6.1.0", "git-config": "0.0.7", "handlebars": "^4.7.6", "inquirer": "^7.3.3", "make-promises-safe": "^5.1.0", "rimraf": "^3.0.2", "semver": "^7.3.2", "toml": "^3.0.0", "ts-typed-json": "^0.3.2", "validate-npm-package-license": "^3.0.4", "validate-npm-package-name": "^3.0.0" }, "dependencies": { "rimraf": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", "dev": true, "requires": { "glob": "^7.1.3" } }, "semver": { "version": "7.3.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", "dev": true, "requires": { "lru-cache": "^6.0.0" } } } }, "next-tick": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz", "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==" }, "nice-try": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", "dev": true }, "node-int64": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", "integrity": "sha1-h6kGXNs1XTGC2PlM4RGIuCXGijs=", "dev": true }, "node-modules-regexp": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/node-modules-regexp/-/node-modules-regexp-1.0.0.tgz", "integrity": "sha1-jZ2+KJZKSsVxLpExZCEHxx6Q7EA=", "dev": true }, "node-notifier": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/node-notifier/-/node-notifier-8.0.2.tgz", "integrity": "sha512-oJP/9NAdd9+x2Q+rfphB2RJCHjod70RcRLjosiPMMu5gjIfwVnOUGq2nbTjTUbmy0DJ/tFIVT30+Qe3nzl4TJg==", "dev": true, "optional": true, "requires": { "growly": "^1.3.0", "is-wsl": "^2.2.0", "semver": "^7.3.2", "shellwords": "^0.1.1", "uuid": "^8.3.0", "which": "^2.0.2" }, "dependencies": { "semver": { "version": "7.3.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", "dev": true, "optional": true, "requires": { "lru-cache": "^6.0.0" } } } }, "node-pre-gyp": { "version": "0.14.0", "resolved": "https://registry.npmjs.org/node-pre-gyp/-/node-pre-gyp-0.14.0.tgz", "integrity": "sha512-+CvDC7ZttU/sSt9rFjix/P05iS43qHCOOGzcr3Ry99bXG7VX953+vFyEuph/tfqoYu8dttBkE86JSKBO2OzcxA==", "requires": { "detect-libc": "^1.0.2", "mkdirp": "^0.5.1", "needle": "^2.2.1", "nopt": "^4.0.1", "npm-packlist": "^1.1.6", "npmlog": "^4.0.2", "rc": "^1.2.7", "rimraf": "^2.6.1", "semver": "^5.3.0", "tar": "^4.4.2" } }, "node-releases": { "version": "1.1.75", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-1.1.75.tgz", "integrity": "sha512-Qe5OUajvqrqDSy6wrWFmMwfJ0jVgwiw4T3KqmbTcZ62qW0gQkheXYhcFM1+lOVcGUoRxcEcfyvFMAnDgaF1VWw==", "dev": true }, "node-status-codes": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/node-status-codes/-/node-status-codes-1.0.0.tgz", "integrity": "sha512-1cBMgRxdMWE8KeWCqk2RIOrvUb0XCwYfEsY5/y2NlXyq4Y/RumnOZvTj4Nbr77+Vb2C+kyBoRTdkNOS8L3d/aQ==" }, "noop6": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/noop6/-/noop6-1.0.9.tgz", "integrity": "sha512-DB3Hwyd89dPr5HqEPg3YHjzvwh/mCqizC1zZ8vyofqc+TQRyPDnT4wgXXbLGF4z9YAzwwTLi8pNLhGqcbSjgkA==" }, "nopt": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/nopt/-/nopt-4.0.3.tgz", "integrity": "sha512-CvaGwVMztSMJLOeXPrez7fyfObdZqNUK1cPAEzLHrTybIua9pMdmmPR5YwtfNftIOMv3DPUhFaxsZMNTQO20Kg==", "requires": { "abbrev": "1", "osenv": "^0.1.4" } }, "normalize-package-data": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", "requires": { "hosted-git-info": "^2.1.4", "resolve": "^1.10.0", "semver": "2 || 3 || 4 || 5", "validate-npm-package-license": "^3.0.1" } }, "normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", "dev": true }, "npm-bundled": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/npm-bundled/-/npm-bundled-1.1.1.tgz", "integrity": "sha512-gqkfgGePhTpAEgUsGEgcq1rqPXA+tv/aVBlgEzfXwA1yiUJF7xtEt3CtVwOjNYQOVknDk0F20w58Fnm3EtG0fA==", "requires": { "npm-normalize-package-bin": "^1.0.1" } }, "npm-normalize-package-bin": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-1.0.1.tgz", "integrity": "sha512-EPfafl6JL5/rU+ot6P3gRSCpPDW5VmIzX959Ob1+ySFUuuYHWHekXpwdUZcKP5C+DS4GEtdJluwBjnsNDl+fSA==" }, "npm-packlist": { "version": "1.4.8", "resolved": "https://registry.npmjs.org/npm-packlist/-/npm-packlist-1.4.8.tgz", "integrity": "sha512-5+AZgwru5IevF5ZdnFglB5wNlHG1AOOuw28WhUq8/8emhBmLv6jX5by4WJCh7lW0uSYZYS6DXqIsyZVIXRZU9A==", "requires": { "ignore-walk": "^3.0.1", "npm-bundled": "^1.0.1", "npm-normalize-package-bin": "^1.0.1" } }, "npm-run-path": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", "dev": true, "requires": { "path-key": "^2.0.0" }, "dependencies": { "path-key": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", "dev": true } } }, "npmlog": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-4.1.2.tgz", "integrity": "sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==", "requires": { "are-we-there-yet": "~1.1.2", "console-control-strings": "~1.1.0", "gauge": "~2.7.3", "set-blocking": "~2.0.0" } }, "number-is-nan": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=" }, "nwsapi": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.0.tgz", "integrity": "sha512-h2AatdwYH+JHiZpv7pt/gSX1XoRGb7L/qSIeuqA6GwYoF9w1vP1cw42TO0aI2pNyshRK5893hNSl+1//vHK7hQ==", "dev": true }, "oargv": { "version": "3.4.10", "resolved": "https://registry.npmjs.org/oargv/-/oargv-3.4.10.tgz", "integrity": "sha512-SXaMANv9sr7S/dP0vj0+Ybipa47UE1ntTWQ2rpPRhC6Bsvfl+Jg03Xif7jfL0sWKOYWK8oPjcZ5eJ82t8AP/8g==", "requires": { "iterate-object": "^1.1.0", "ul": "^5.0.0" } }, "obj-def": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/obj-def/-/obj-def-1.0.9.tgz", "integrity": "sha512-bQ4ya3VYD6FAA1+s6mEhaURRHSmw4+sKaXE6UyXZ1XDYc5D+c7look25dFdydmLd18epUegh398gdDkMUZI9xg==", "requires": { "deffy": "^2.2.2" } }, "object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=" }, "object-copy": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz", "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=", "dev": true, "requires": { "copy-descriptor": "^0.1.0", "define-property": "^0.2.5", "kind-of": "^3.0.3" }, "dependencies": { "define-property": { "version": "0.2.5", "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", "dev": true, "requires": { "is-descriptor": "^0.1.0" } }, "kind-of": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { "is-buffer": "^1.1.5" } } } }, "object-visit": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", "dev": true, "requires": { "isobject": "^3.0.0" } }, "object.pick": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", "dev": true, "requires": { "isobject": "^3.0.1" } }, "once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", "requires": { "wrappy": "1" } }, "one-by-one": { "version": "3.2.8", "resolved": "https://registry.npmjs.org/one-by-one/-/one-by-one-3.2.8.tgz", "integrity": "sha512-HR/pSzZdm46Xqj58K+Bu64kMbSTw8/u77AwWvV+rprO/OsuR++pPlkUJn+SmwqBGRgHKwSKQ974V3uls7crIeQ==", "requires": { "obj-def": "^1.0.0", "sliced": "^1.0.1" } }, "onetime": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", "dev": true, "requires": { "mimic-fn": "^2.1.0" } }, "optionator": { "version": "0.9.1", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", "integrity": "sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==", "dev": true, "requires": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.3" } }, "os-homedir": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=" }, "os-tmpdir": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=" }, "osenv": { "version": "0.1.5", "resolved": "https://registry.npmjs.org/osenv/-/osenv-0.1.5.tgz", "integrity": "sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==", "requires": { "os-homedir": "^1.0.0", "os-tmpdir": "^1.0.0" } }, "p-each-series": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/p-each-series/-/p-each-series-2.2.0.tgz", "integrity": "sha512-ycIL2+1V32th+8scbpTvyHNaHe02z0sjgh91XXjAk+ZeXoPN4Z46DVUnzdso0aX4KckKw0FNNFHdjZ2UsZvxiA==", "dev": true }, "p-finally": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=", "dev": true }, "p-limit": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "dev": true, "requires": { "p-try": "^2.0.0" } }, "p-locate": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, "requires": { "p-limit": "^2.2.0" } }, "p-try": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", "dev": true }, "package-json": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/package-json/-/package-json-2.4.0.tgz", "integrity": "sha512-PRg65iXMTt/uK8Rfh5zvzkUbfAPitF17YaCY+IbHsYgksiLvtzWWTUildHth3mVaZ7871OJ7gtP4LBRBlmAdXg==", "requires": { "got": "^5.0.0", "registry-auth-token": "^3.0.1", "registry-url": "^3.0.3", "semver": "^5.1.0" } }, "package-json-path": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/package-json-path/-/package-json-path-1.0.9.tgz", "integrity": "sha512-uNu7f6Ef7tQHZRnkyVnCtzdSYVN9uBtge/sG7wzcUaawFWkPYUq67iXxRGrQSg/q0tzxIB8jSyIYUKjG2Jn//A==", "requires": { "abs": "^1.2.1" } }, "package.json": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/package.json/-/package.json-2.0.1.tgz", "integrity": "sha512-pSxZ6XR5yEawRN2ekxx9IKgPN5uNAYco7MCPxtBEWMKO3UKWa1X2CtQMzMgloeGj2g2o6cue3Sb5iPkByIJqlw==", "requires": { "git-package-json": "^1.4.0", "git-source": "^1.1.0", "package-json": "^2.3.1" } }, "parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", "dev": true, "requires": { "callsites": "^3.0.0" } }, "parse-json": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", "dev": true, "requires": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", "json-parse-even-better-errors": "^2.3.0", "lines-and-columns": "^1.1.6" } }, "parse-url": { "version": "1.3.11", "resolved": "https://registry.npmjs.org/parse-url/-/parse-url-1.3.11.tgz", "integrity": "sha512-1wj9nkgH/5EboDxLwaTMGJh3oH3f+Gue+aGdh631oCqoSBpokzmMmOldvOeBPtB8GJBYJbaF93KPzlkU+Y1ksg==", "requires": { "is-ssh": "^1.3.0", "protocols": "^1.4.0" }, "dependencies": { "protocols": { "version": "1.4.8", "resolved": "https://registry.npmjs.org/protocols/-/protocols-1.4.8.tgz", "integrity": "sha512-IgjKyaUSjsROSO8/D49Ab7hP8mJgTYcqApOqdPhLoPxAplXmkp+zRvsrSQjFn5by0rhm4VH0GAUELIPpx7B1yg==" } } }, "parse5": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==", "dev": true }, "pascalcase": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=", "dev": true }, "path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true }, "path-is-absolute": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" }, "path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", "dev": true }, "path-parse": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==" }, "picomatch": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.0.tgz", "integrity": "sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==", "dev": true }, "pinkie": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", "integrity": "sha512-MnUuEycAemtSaeFSjXKW/aroV7akBbY+Sv+RkyqFjgAe73F+MR0TBWKBRDkmfWq/HiFmdavfZ1G7h4SPZXaCSg==" }, "pinkie-promise": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", "integrity": "sha512-0Gni6D4UcLTbv9c57DfxDGdr41XfgUjqWZu492f0cIGr16zDU06BWP/RAEvOuo7CQ0CNjHaLlM59YJJFm3NWlw==", "requires": { "pinkie": "^2.0.0" } }, "pirates": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.1.tgz", "integrity": "sha512-WuNqLTbMI3tmfef2TKxlQmAiLHKtFhlsCZnPIpuv2Ow0RDVO8lfy1Opf4NUzlMXLjPl+Men7AuVdX6TA+s+uGA==", "dev": true, "requires": { "node-modules-regexp": "^1.0.0" } }, "pkg-dir": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", "dev": true, "requires": { "find-up": "^4.0.0" } }, "posix-character-classes": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", "dev": true }, "prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", "dev": true }, "prepend-http": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", "integrity": "sha512-PhmXi5XmoyKw1Un4E+opM2KcsJInDvKyuOumcjjw3waw86ZNjHwVUOOWLc4bCzLdcKNaWBH9e99sbWzDQsVaYg==" }, "prettier": { "version": "2.5.1", "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.5.1.tgz", "integrity": "sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==", "dev": true }, "prettier-linter-helpers": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz", "integrity": "sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w==", "dev": true, "requires": { "fast-diff": "^1.1.2" } }, "pretty-format": { "version": "26.6.2", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-26.6.2.tgz", "integrity": "sha512-7AeGuCYNGmycyQbCqd/3PWH4eOoX/OiCa0uphp57NVTeAGdJGaAliecxwBDHYQCIvrW7aDBZCYeNTP/WX69mkg==", "dev": true, "requires": { "@jest/types": "^26.6.2", "ansi-regex": "^5.0.0", "ansi-styles": "^4.0.0", "react-is": "^17.0.1" }, "dependencies": { "ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { "color-convert": "^2.0.1" } }, "color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "requires": { "color-name": "~1.1.4" } }, "color-name": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true } } }, "process-nextick-args": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" }, "progress": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", "dev": true }, "prompts": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.1.tgz", "integrity": "sha512-EQyfIuO2hPDsX1L/blblV+H7I0knhgAd82cVneCwcdND9B8AuCDuRcBH6yIcG4dFzlOUqbazQqwGjx5xmsNLuQ==", "dev": true, "requires": { "kleur": "^3.0.3", "sisteransi": "^1.0.5" } }, "protocols": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/protocols/-/protocols-2.0.1.tgz", "integrity": "sha512-/XJ368cyBJ7fzLMwLKv1e4vLxOju2MNAIokcr7meSaNcVbWz/CPcW22cP04mwxOErdA5mwjA8Q6w/cdAQxVn7Q==" }, "proxy-polyfill": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/proxy-polyfill/-/proxy-polyfill-0.1.7.tgz", "integrity": "sha512-WUob/kKCMt4IDJthdKv8GYi89pFsKhv14E/Ej+bTPcKJFa2xw4cmSRD9MDJFCExanfhViIARMBL7SJY7/S7aMA==" }, "psl": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==", "dev": true }, "pump": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", "dev": true, "requires": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "punycode": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", "dev": true }, "q": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/q/-/q-1.5.1.tgz", "integrity": "sha512-kV/CThkXo6xyFEZUugw/+pIOywXcDbFYgSct5cT3gqlbkBE1SJdwy6UQoZvodiWF/ckQLZyDE/Bu1M6gVu5lVw==" }, "q-io": { "version": "1.13.6", "resolved": "https://registry.npmjs.org/q-io/-/q-io-1.13.6.tgz", "integrity": "sha512-xgxlfN3iOQ4LMuyhb8+aibtv57HnqZqycCLaE3o/qkeqvBuEfbq4tU4oHjIHgY/LVN3vJs+Gy9hKh8kzlnug7g==", "requires": { "es6-set": "^0.1.1", "mime": "^1.2.11", "mimeparse": "^0.1.4", "q": "^1.0.1", "qs": "^1.2.1", "url2": "^0.0.0" } }, "qs": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/qs/-/qs-1.2.2.tgz", "integrity": "sha512-xEqT+49YIt+BdwQthXKTOkp7atENe6JqrGGerxBPiER6BArOIiVJtpZZYpWOpq2IOkTPVnDM8CgYvppFoJNwyQ==" }, "querystringify": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", "dev": true }, "r-json": { "version": "1.2.10", "resolved": "https://registry.npmjs.org/r-json/-/r-json-1.2.10.tgz", "integrity": "sha512-hu9vyLjSlHXT62NAS7DjI9WazDlvjN0lgp3n431dCVnirVcLkZIpzSwA3orhZEKzdDD2jqNYI+w0yG0aFf4kpA==" }, "r-package-json": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/r-package-json/-/r-package-json-1.0.9.tgz", "integrity": "sha512-G4Vpf1KImWmmPFGdtWQTU0L9zk0SjqEC4qs/jE7AQ+Ylmr5kizMzGeC4wnHp5+ijPqNN+2ZPpvyjVNdN1CDVcg==", "requires": { "package-json-path": "^1.0.0", "r-json": "^1.2.1" } }, "rc": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", "requires": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" } }, "react-is": { "version": "17.0.2", "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", "dev": true }, "read-all-stream": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/read-all-stream/-/read-all-stream-3.1.0.tgz", "integrity": "sha512-DI1drPHbmBcUDWrJ7ull/F2Qb8HkwBncVx8/RpKYFSIACYaVRQReISYPdZz/mt1y1+qMCOrfReTopERmaxtP6w==", "requires": { "pinkie-promise": "^2.0.0", "readable-stream": "^2.0.0" } }, "read-pkg": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-5.2.0.tgz", "integrity": "sha512-Ug69mNOpfvKDAc2Q8DRpMjjzdtrnv9HcSMX+4VsZxD1aZ6ZzrIE7rlzXBtWTyhULSMKg076AW6WR5iZpD0JiOg==", "dev": true, "requires": { "@types/normalize-package-data": "^2.4.0", "normalize-package-data": "^2.5.0", "parse-json": "^5.0.0", "type-fest": "^0.6.0" }, "dependencies": { "type-fest": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.6.0.tgz", "integrity": "sha512-q+MB8nYR1KDLrgr4G5yemftpMC7/QLqVndBmEEdqzmNj5dcFOO4Oo8qlwZE3ULT3+Zim1F8Kq4cBnikNhlCMlg==", "dev": true } } }, "read-pkg-up": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-7.0.1.tgz", "integrity": "sha512-zK0TB7Xd6JpCLmlLmufqykGE+/TlOePD6qKClNW7hHDKFh/J7/7gCWGR7joEQEW1bKq3a3yUZSObOoWLFQ4ohg==", "dev": true, "requires": { "find-up": "^4.1.0", "read-pkg": "^5.2.0", "type-fest": "^0.8.1" }, "dependencies": { "type-fest": { "version": "0.8.1", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz", "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", "dev": true } } }, "readable-stream": { "version": "2.3.7", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", "requires": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "rechoir": { "version": "0.6.2", "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz", "integrity": "sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q=", "dev": true, "requires": { "resolve": "^1.1.6" } }, "reduce-flatten": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/reduce-flatten/-/reduce-flatten-2.0.0.tgz", "integrity": "sha512-EJ4UNY/U1t2P/2k6oqotuX2Cc3T6nxJwsM0N0asT7dhrtH1ltUxDn4NalSYmPE2rCkVpcf/X6R0wDwcFpzhd4w==", "dev": true }, "regex-not": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz", "integrity": "sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==", "dev": true, "requires": { "extend-shallow": "^3.0.2", "safe-regex": "^1.1.0" } }, "regexpp": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==", "dev": true }, "regextras": { "version": "0.7.1", "resolved": "https://registry.npmjs.org/regextras/-/regextras-0.7.1.tgz", "integrity": "sha512-9YXf6xtW+qzQ+hcMQXx95MOvfqXFgsKDZodX3qZB0x2n5Z94ioetIITsBtvJbiOyxa/6s9AtyweBLCdPmPko/w==", "dev": true }, "registry-auth-token": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", "requires": { "rc": "^1.1.6", "safe-buffer": "^5.0.1" } }, "registry-url": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/registry-url/-/registry-url-3.1.0.tgz", "integrity": "sha512-ZbgR5aZEdf4UKZVBPYIgaglBmSF2Hi94s2PcIHhRGFjKYu+chjJdYfHn4rt3hB6eCKLJ8giVIIfgMa1ehDfZKA==", "requires": { "rc": "^1.0.1" } }, "remove-trailing-separator": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=", "dev": true }, "repeat-element": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.4.tgz", "integrity": "sha512-LFiNfRcSu7KK3evMyYOuCzv3L10TW7yC1G2/+StMjK8Y6Vqd2MG7r/Qjw4ghtuCOjFvlnms/iMmLqpvW/ES/WQ==", "dev": true }, "repeat-string": { "version": "1.6.1", "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", "dev": true }, "require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", "dev": true }, "require-from-string": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", "dev": true }, "require-main-filename": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "dev": true }, "requires-port": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", "dev": true }, "resolve": { "version": "1.17.0", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz", "integrity": "sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w==", "requires": { "path-parse": "^1.0.6" } }, "resolve-cwd": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", "dev": true, "requires": { "resolve-from": "^5.0.0" }, "dependencies": { "resolve-from": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", "dev": true } } }, "resolve-from": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", "dev": true }, "resolve-url": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", "dev": true }, "restore-cursor": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", "dev": true, "requires": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" } }, "ret": { "version": "0.1.15", "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", "dev": true }, "rimraf": { "version": "2.7.1", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", "requires": { "glob": "^7.1.3" } }, "rsvp": { "version": "4.8.5", "resolved": "https://registry.npmjs.org/rsvp/-/rsvp-4.8.5.tgz", "integrity": "sha512-nfMOlASu9OnRJo1mbEk2cz0D56a1MBNrJ7orjRZQG10XDyuvwksKbuXNp6qa+kbn839HwjwhBzhFmdsaEAfauA==", "dev": true }, "run-async": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", "dev": true }, "rxjs": { "version": "6.6.7", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", "integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==", "dev": true, "requires": { "tslib": "^1.9.0" } }, "safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" }, "safe-regex": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", "dev": true, "requires": { "ret": "~0.1.10" } }, "safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, "sane": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/sane/-/sane-4.1.0.tgz", "integrity": "sha512-hhbzAgTIX8O7SHfp2c8/kREfEn4qO/9q8C9beyY6+tvZ87EpoZ3i1RIEvp27YBswnNbY9mWd6paKVmKbAgLfZA==", "dev": true, "requires": { "@cnakazawa/watch": "^1.0.3", "anymatch": "^2.0.0", "capture-exit": "^2.0.0", "exec-sh": "^0.3.2", "execa": "^1.0.0", "fb-watchman": "^2.0.0", "micromatch": "^3.1.4", "minimist": "^1.1.1", "walker": "~1.0.5" }, "dependencies": { "anymatch": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-2.0.0.tgz", "integrity": "sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==", "dev": true, "requires": { "micromatch": "^3.1.4", "normalize-path": "^2.1.1" } }, "braces": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz", "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", "dev": true, "requires": { "arr-flatten": "^1.1.0", "array-unique": "^0.3.2", "extend-shallow": "^2.0.1", "fill-range": "^4.0.0", "isobject": "^3.0.1", "repeat-element": "^1.1.2", "snapdragon": "^0.8.1", "snapdragon-node": "^2.0.1", "split-string": "^3.0.2", "to-regex": "^3.0.1" }, "dependencies": { "extend-shallow": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { "is-extendable": "^0.1.0" } } } }, "fill-range": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", "dev": true, "requires": { "extend-shallow": "^2.0.1", "is-number": "^3.0.0", "repeat-string": "^1.6.1", "to-regex-range": "^2.1.0" }, "dependencies": { "extend-shallow": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { "is-extendable": "^0.1.0" } } } }, "is-number": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", "dev": true, "requires": { "kind-of": "^3.0.2" }, "dependencies": { "kind-of": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { "is-buffer": "^1.1.5" } } } }, "micromatch": { "version": "3.1.10", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", "dev": true, "requires": { "arr-diff": "^4.0.0", "array-unique": "^0.3.2", "braces": "^2.3.1", "define-property": "^2.0.2", "extend-shallow": "^3.0.2", "extglob": "^2.0.4", "fragment-cache": "^0.2.1", "kind-of": "^6.0.2", "nanomatch": "^1.2.9", "object.pick": "^1.3.0", "regex-not": "^1.0.0", "snapdragon": "^0.8.1", "to-regex": "^3.0.2" } }, "normalize-path": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", "dev": true, "requires": { "remove-trailing-separator": "^1.0.1" } }, "to-regex-range": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-2.1.1.tgz", "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=", "dev": true, "requires": { "is-number": "^3.0.0", "repeat-string": "^1.6.1" } } } }, "sax": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" }, "saxes": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz", "integrity": "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==", "dev": true, "requires": { "xmlchars": "^2.2.0" } }, "semver": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" }, "set-blocking": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=" }, "set-value": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.1.tgz", "integrity": "sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw==", "dev": true, "requires": { "extend-shallow": "^2.0.1", "is-extendable": "^0.1.1", "is-plain-object": "^2.0.3", "split-string": "^3.0.1" }, "dependencies": { "extend-shallow": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { "is-extendable": "^0.1.0" } } } }, "shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", "dev": true, "requires": { "shebang-regex": "^3.0.0" } }, "shebang-regex": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", "dev": true }, "shelljs": { "version": "0.8.5", "resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.8.5.tgz", "integrity": "sha512-TiwcRcrkhHvbrZbnRcFYMLl30Dfov3HKqzp5tO5b4pt6G/SezKcYhmDg15zXVBswHmctSAQKznqNW2LO5tTDow==", "dev": true, "requires": { "glob": "^7.0.0", "interpret": "^1.0.0", "rechoir": "^0.6.2" } }, "shellwords": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/shellwords/-/shellwords-0.1.1.tgz", "integrity": "sha512-vFwSUfQvqybiICwZY5+DAWIPLKsWO31Q91JSKl3UYv+K5c2QRPzn0qzec6QPu1Qc9eHYItiP3NdJqNVqetYAww==", "dev": true, "optional": true }, "signal-exit": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==" }, "sisteransi": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", "dev": true }, "slash": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true }, "slice-ansi": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", "dev": true, "requires": { "ansi-styles": "^4.0.0", "astral-regex": "^2.0.0", "is-fullwidth-code-point": "^3.0.0" }, "dependencies": { "ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { "color-convert": "^2.0.1" } }, "color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "requires": { "color-name": "~1.1.4" } }, "color-name": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, "is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true } } }, "sliced": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz", "integrity": "sha512-VZBmZP8WU3sMOZm1bdgTadsQbcscK0UM8oKxKVBs4XAhUo2Xxzm/OFMGBkPusxw9xL3Uy8LrzEqGqJhclsr0yA==" }, "snapdragon": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", "integrity": "sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==", "dev": true, "requires": { "base": "^0.11.1", "debug": "^2.2.0", "define-property": "^0.2.5", "extend-shallow": "^2.0.1", "map-cache": "^0.2.2", "source-map": "^0.5.6", "source-map-resolve": "^0.5.0", "use": "^3.1.0" }, "dependencies": { "debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "dev": true, "requires": { "ms": "2.0.0" } }, "define-property": { "version": "0.2.5", "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", "dev": true, "requires": { "is-descriptor": "^0.1.0" } }, "extend-shallow": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { "is-extendable": "^0.1.0" } }, "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true }, "source-map": { "version": "0.5.7", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", "dev": true } } }, "snapdragon-node": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/snapdragon-node/-/snapdragon-node-2.1.1.tgz", "integrity": "sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==", "dev": true, "requires": { "define-property": "^1.0.0", "isobject": "^3.0.0", "snapdragon-util": "^3.0.1" }, "dependencies": { "define-property": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", "dev": true, "requires": { "is-descriptor": "^1.0.0" } }, "is-accessor-descriptor": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", "dev": true, "requires": { "kind-of": "^6.0.0" } }, "is-data-descriptor": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", "dev": true, "requires": { "kind-of": "^6.0.0" } }, "is-descriptor": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", "dev": true, "requires": { "is-accessor-descriptor": "^1.0.0", "is-data-descriptor": "^1.0.0", "kind-of": "^6.0.2" } } } }, "snapdragon-util": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/snapdragon-util/-/snapdragon-util-3.0.1.tgz", "integrity": "sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==", "dev": true, "requires": { "kind-of": "^3.2.0" }, "dependencies": { "kind-of": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { "is-buffer": "^1.1.5" } } } }, "source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true }, "source-map-resolve": { "version": "0.5.3", "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.3.tgz", "integrity": "sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw==", "dev": true, "requires": { "atob": "^2.1.2", "decode-uri-component": "^0.2.0", "resolve-url": "^0.2.1", "source-map-url": "^0.4.0", "urix": "^0.1.0" } }, "source-map-support": { "version": "0.5.19", "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.19.tgz", "integrity": "sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw==", "dev": true, "requires": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" } }, "source-map-url": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.1.tgz", "integrity": "sha512-cPiFOTLUKvJFIg4SKVScy4ilPPW6rFgMgfuZJPNoDuMs3nC1HbMUycBoJw77xFIp6z1UJQJOfx6C9GMH80DiTw==", "dev": true }, "spdx-correct": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.1.tgz", "integrity": "sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w==", "requires": { "spdx-expression-parse": "^3.0.0", "spdx-license-ids": "^3.0.0" } }, "spdx-exceptions": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz", "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==" }, "spdx-expression-parse": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", "requires": { "spdx-exceptions": "^2.1.0", "spdx-license-ids": "^3.0.0" } }, "spdx-license-ids": { "version": "3.0.5", "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.5.tgz", "integrity": "sha512-J+FWzZoynJEXGphVIS+XEh3kFSjZX/1i9gFBaWQcB+/tmpe2qUsSBABpcxqxnAxFdiUFEgAX1bjYGQvIZmoz9Q==" }, "split-string": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==", "dev": true, "requires": { "extend-shallow": "^3.0.0" } }, "sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", "dev": true }, "stack-utils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.3.tgz", "integrity": "sha512-gL//fkxfWUsIlFL2Tl42Cl6+HFALEaB1FU76I/Fy+oZjRreP7OPMXFlGbxM7NQsI0ZpUfw76sHnv0WNYuTb7Iw==", "dev": true, "requires": { "escape-string-regexp": "^2.0.0" }, "dependencies": { "escape-string-regexp": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", "dev": true } } }, "static-extend": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=", "dev": true, "requires": { "define-property": "^0.2.5", "object-copy": "^0.1.0" }, "dependencies": { "define-property": { "version": "0.2.5", "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", "dev": true, "requires": { "is-descriptor": "^0.1.0" } } } }, "string-length": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", "dev": true, "requires": { "char-regex": "^1.0.2", "strip-ansi": "^6.0.0" }, "dependencies": { "ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "strip-ansi": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", "dev": true, "requires": { "ansi-regex": "^5.0.0" } } } }, "string-width": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", "strip-ansi": "^3.0.0" } }, "string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "requires": { "safe-buffer": "~5.1.0" } }, "strip-ansi": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "requires": { "ansi-regex": "^2.0.0" } }, "strip-bom": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", "dev": true }, "strip-eof": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=", "dev": true }, "strip-final-newline": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", "dev": true }, "strip-json-comments": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=" }, "supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" } }, "supports-hyperlinks": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-2.2.0.tgz", "integrity": "sha512-6sXEzV5+I5j8Bmq9/vUphGRM/RJNT9SCURJLjwfOg51heRtguGWDzcaBlgAzKhQa0EVNpPEKzQuBwZ8S8WaCeQ==", "dev": true, "requires": { "has-flag": "^4.0.0", "supports-color": "^7.0.0" } }, "symbol-tree": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", "dev": true }, "table": { "version": "6.7.1", "resolved": "https://registry.npmjs.org/table/-/table-6.7.1.tgz", "integrity": "sha512-ZGum47Yi6KOOFDE8m223td53ath2enHcYLgOCjGr5ngu8bdIARQk6mN/wRMv4yMRcHnCSnHbCEha4sobQx5yWg==", "dev": true, "requires": { "ajv": "^8.0.1", "lodash.clonedeep": "^4.5.0", "lodash.truncate": "^4.4.2", "slice-ansi": "^4.0.0", "string-width": "^4.2.0", "strip-ansi": "^6.0.0" }, "dependencies": { "ajv": { "version": "8.6.2", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.6.2.tgz", "integrity": "sha512-9807RlWAgT564wT+DjeyU5OFMPjmzxVobvDFmNAhY+5zD6A2ly3jDp6sgnfyDtlIQ+7H97oc/DGCzzfu9rjw9w==", "dev": true, "requires": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2", "uri-js": "^4.2.2" } }, "ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true }, "json-schema-traverse": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", "dev": true }, "string-width": { "version": "4.2.2", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz", "integrity": "sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA==", "dev": true, "requires": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.0" } }, "strip-ansi": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", "dev": true, "requires": { "ansi-regex": "^5.0.0" } } } }, "table-layout": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-1.0.2.tgz", "integrity": "sha512-qd/R7n5rQTRFi+Zf2sk5XVVd9UQl6ZkduPFC3S7WEGJAmetDTjY3qPN50eSKzwuzEyQKy5TN2TiZdkIjos2L6A==", "dev": true, "requires": { "array-back": "^4.0.1", "deep-extend": "~0.6.0", "typical": "^5.2.0", "wordwrapjs": "^4.0.0" }, "dependencies": { "array-back": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/array-back/-/array-back-4.0.2.tgz", "integrity": "sha512-NbdMezxqf94cnNfWLL7V/im0Ub+Anbb0IoZhvzie8+4HJ4nMQuzHuy49FkGYCJK2yAloZ3meiB6AVMClbrI1vg==", "dev": true }, "typical": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/typical/-/typical-5.2.0.tgz", "integrity": "sha512-dvdQgNDNJo+8B2uBQoqdb11eUCE1JQXhvjC/CZtgvZseVd5TYMXnq0+vuUemXbd/Se29cTaUuPX3YIc2xgbvIg==", "dev": true } } }, "tar": { "version": "4.4.19", "resolved": "https://registry.npmjs.org/tar/-/tar-4.4.19.tgz", "integrity": "sha512-a20gEsvHnWe0ygBY8JbxoM4w3SJdhc7ZAuxkLqh+nvNQN2IOt0B5lLgM490X5Hl8FF0dl0tOf2ewFYAlIFgzVA==", "requires": { "chownr": "^1.1.4", "fs-minipass": "^1.2.7", "minipass": "^2.9.0", "minizlib": "^1.3.3", "mkdirp": "^0.5.5", "safe-buffer": "^5.2.1", "yallist": "^3.1.1" }, "dependencies": { "safe-buffer": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" } } }, "terminal-link": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/terminal-link/-/terminal-link-2.1.1.tgz", "integrity": "sha512-un0FmiRUQNr5PJqy9kP7c40F5BOfpGlYTrxonDChEZB7pzZxRNp/bt+ymiy9/npwXya9KH99nJ/GXFIiUkYGFQ==", "dev": true, "requires": { "ansi-escapes": "^4.2.1", "supports-hyperlinks": "^2.0.0" } }, "test-exclude": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", "dev": true, "requires": { "@istanbuljs/schema": "^0.1.2", "glob": "^7.1.4", "minimatch": "^3.0.4" } }, "text-table": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", "dev": true }, "throat": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/throat/-/throat-5.0.0.tgz", "integrity": "sha512-fcwX4mndzpLQKBS1DVYhGAcYaYt7vsHNIvQV+WXMvnow5cgjPphq5CaayLaGsjRdSCKZFNGt7/GYAuXaNOiYCA==", "dev": true }, "through": { "version": "2.3.8", "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", "dev": true }, "timed-out": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/timed-out/-/timed-out-3.1.3.tgz", "integrity": "sha512-3RB4qgvPkxF/FGPnrzaWLhW1rxNK2sdH0mFjbhxkfTR6QXvcM3EtYm9L44UrhODZrZ+yhDXeMncLqi8QXn2MJg==" }, "tmp": { "version": "0.0.33", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", "dev": true, "requires": { "os-tmpdir": "~1.0.2" } }, "tmpl": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", "dev": true }, "to-fast-properties": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", "dev": true }, "to-object-path": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz", "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", "dev": true, "requires": { "kind-of": "^3.0.2" }, "dependencies": { "kind-of": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { "is-buffer": "^1.1.5" } } } }, "to-regex": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/to-regex/-/to-regex-3.0.2.tgz", "integrity": "sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==", "dev": true, "requires": { "define-property": "^2.0.2", "extend-shallow": "^3.0.2", "regex-not": "^1.0.2", "safe-regex": "^1.1.0" } }, "to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "dev": true, "requires": { "is-number": "^7.0.0" } }, "toml": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/toml/-/toml-3.0.0.tgz", "integrity": "sha512-y/mWCZinnvxjTKYhJ+pYxwD0mRLVvOtdS2Awbgxln6iEnt4rk0yBxeSBHkGJcPucRiG0e55mwWp+g/05rsrd6w==", "dev": true }, "tough-cookie": { "version": "4.1.3", "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.3.tgz", "integrity": "sha512-aX/y5pVRkfRnfmuX+OdbSdXvPe6ieKX/G2s7e98f4poJHnqH3281gDPm/metm6E/WRamfx7WC4HUqkWHfQHprw==", "dev": true, "requires": { "psl": "^1.1.33", "punycode": "^2.1.1", "universalify": "^0.2.0", "url-parse": "^1.5.3" }, "dependencies": { "universalify": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", "dev": true } } }, "tr46": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/tr46/-/tr46-2.1.0.tgz", "integrity": "sha512-15Ih7phfcdP5YxqiB+iDtLoaTz4Nd35+IiAv0kQ5FNKHzXgdWqPoTIqEDDJmXceQt4JZk6lVPT8lnDlPpGDppw==", "dev": true, "requires": { "punycode": "^2.1.1" } }, "ts-jest": { "version": "26.5.6", "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-26.5.6.tgz", "integrity": "sha512-rua+rCP8DxpA8b4DQD/6X2HQS8Zy/xzViVYfEs2OQu68tkCuKLV0Md8pmX55+W24uRIyAsf/BajRfxOs+R2MKA==", "dev": true, "requires": { "bs-logger": "0.x", "buffer-from": "1.x", "fast-json-stable-stringify": "2.x", "jest-util": "^26.1.0", "json5": "2.x", "lodash": "4.x", "make-error": "1.x", "mkdirp": "1.x", "semver": "7.x", "yargs-parser": "20.x" }, "dependencies": { "mkdirp": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", "dev": true }, "semver": { "version": "7.3.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", "dev": true, "requires": { "lru-cache": "^6.0.0" } }, "yargs-parser": { "version": "20.2.9", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", "dev": true } } }, "ts-typed-json": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/ts-typed-json/-/ts-typed-json-0.3.2.tgz", "integrity": "sha512-Tdu3BWzaer7R5RvBIJcg9r8HrTZgpJmsX+1meXMJzYypbkj8NK2oJN0yvm4Dp/Iv6tzFa/L5jKRmEVTga6K3nA==", "dev": true }, "tslib": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", "dev": true }, "tsutils": { "version": "3.21.0", "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz", "integrity": "sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==", "dev": true, "requires": { "tslib": "^1.8.1" } }, "type": { "version": "2.7.2", "resolved": "https://registry.npmjs.org/type/-/type-2.7.2.tgz", "integrity": "sha512-dzlvlNlt6AXU7EBSfpAscydQ7gXB+pPGsPnfJnZpiNJBDj7IaJzQlBZYGdEi4R9HmPdBv2XmWJ6YUtoTa7lmCw==" }, "type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", "dev": true, "requires": { "prelude-ls": "^1.2.1" } }, "type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", "dev": true }, "type-fest": { "version": "0.20.2", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", "dev": true }, "typedarray-to-buffer": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", "dev": true, "requires": { "is-typedarray": "^1.0.0" } }, "typescript": { "version": "3.9.10", "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.10.tgz", "integrity": "sha512-w6fIxVE/H1PkLKcCPsFqKE7Kv7QUwhU8qQY2MueZXWx5cPZdwFupLgKK3vntcK98BtNHZtAF4LA/yl2a7k8R6Q==", "dev": true }, "typical": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/typical/-/typical-4.0.0.tgz", "integrity": "sha512-VAH4IvQ7BDFYglMd7BPRDfLgxZZX4O4TFcRDA6EN5X7erNJJq+McIEp8np9aVtxrCJ6qx4GTYVfOWNjcqwZgRw==", "dev": true }, "typpy": { "version": "2.3.13", "resolved": "https://registry.npmjs.org/typpy/-/typpy-2.3.13.tgz", "integrity": "sha512-vOxIcQz9sxHi+rT09SJ5aDgVgrPppQjwnnayTrMye1ODaU8gIZTDM19t9TxmEElbMihx2Nq/0/b/MtyKfayRqA==", "requires": { "function.name": "^1.0.3" } }, "uglify-js": { "version": "3.14.5", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.14.5.tgz", "integrity": "sha512-qZukoSxOG0urUTvjc2ERMTcAy+BiFh3weWAkeurLwjrCba73poHmG3E36XEjd/JGukMzwTL7uCxZiAexj8ppvQ==", "dev": true, "optional": true }, "ul": { "version": "5.2.15", "resolved": "https://registry.npmjs.org/ul/-/ul-5.2.15.tgz", "integrity": "sha512-svLEUy8xSCip5IWnsRa0UOg+2zP0Wsj4qlbjTmX6GJSmvKMHADBuHOm1dpNkWqWPIGuVSqzUkV3Cris5JrlTRQ==", "requires": { "deffy": "^2.2.2", "typpy": "^2.3.4" } }, "union-value": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.1.tgz", "integrity": "sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg==", "dev": true, "requires": { "arr-union": "^3.1.0", "get-value": "^2.0.6", "is-extendable": "^0.1.1", "set-value": "^2.0.1" } }, "unset-value": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz", "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", "dev": true, "requires": { "has-value": "^0.3.1", "isobject": "^3.0.0" }, "dependencies": { "has-value": { "version": "0.3.1", "resolved": "https://registry.npmjs.org/has-value/-/has-value-0.3.1.tgz", "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", "dev": true, "requires": { "get-value": "^2.0.3", "has-values": "^0.1.4", "isobject": "^2.0.0" }, "dependencies": { "isobject": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", "dev": true, "requires": { "isarray": "1.0.0" } } } }, "has-values": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/has-values/-/has-values-0.1.4.tgz", "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=", "dev": true } } }, "unzip-response": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/unzip-response/-/unzip-response-1.0.2.tgz", "integrity": "sha512-pwCcjjhEcpW45JZIySExBHYv5Y9EeL2OIGEfrSKp2dMUFGFv4CpvZkwJbVge8OvGH2BNNtJBx67DuKuJhf+N5Q==" }, "uri-js": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", "dev": true, "requires": { "punycode": "^2.1.0" } }, "urix": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=", "dev": true }, "url-parse": { "version": "1.5.10", "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", "dev": true, "requires": { "querystringify": "^2.1.1", "requires-port": "^1.0.0" } }, "url-parse-lax": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/url-parse-lax/-/url-parse-lax-1.0.0.tgz", "integrity": "sha512-BVA4lR5PIviy2PMseNd2jbFQ+jwSwQGdJejf5ctd1rEXt0Ypd7yanUK9+lYechVlN5VaTJGsu2U/3MDDu6KgBA==", "requires": { "prepend-http": "^1.0.1" } }, "url2": { "version": "0.0.0", "resolved": "https://registry.npmjs.org/url2/-/url2-0.0.0.tgz", "integrity": "sha512-gb/XT1m2mnWOIbQwa5V9Dq2O07fkZbtu1K0WAAKuaNSX0c8psp2jovJTbbvPKCpimutdoK9jXOejDCtvQOoKOA==" }, "use": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", "integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==", "dev": true }, "util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" }, "uuid": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", "dev": true, "optional": true }, "v8-compile-cache": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", "integrity": "sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==", "dev": true }, "v8-to-istanbul": { "version": "7.1.2", "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-7.1.2.tgz", "integrity": "sha512-TxNb7YEUwkLXCQYeudi6lgQ/SZrzNO4kMdlqVxaZPUIUjCv6iSSypUQX70kNBSERpQ8fk48+d61FXk+tgqcWow==", "dev": true, "requires": { "@types/istanbul-lib-coverage": "^2.0.1", "convert-source-map": "^1.6.0", "source-map": "^0.7.3" }, "dependencies": { "source-map": { "version": "0.7.3", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz", "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", "dev": true } } }, "validate-npm-package-license": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", "requires": { "spdx-correct": "^3.0.0", "spdx-expression-parse": "^3.0.0" } }, "validate-npm-package-name": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-3.0.0.tgz", "integrity": "sha1-X6kS2B630MdK/BQN5zF/DKffQ34=", "dev": true, "requires": { "builtins": "^1.0.3" } }, "w3c-hr-time": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz", "integrity": "sha512-z8P5DvDNjKDoFIHK7q8r8lackT6l+jo/Ye3HOle7l9nICP9lf1Ci25fy9vHd0JOWewkIFzXIEig3TdKT7JQ5fQ==", "dev": true, "requires": { "browser-process-hrtime": "^1.0.0" } }, "w3c-xmlserializer": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-2.0.0.tgz", "integrity": "sha512-4tzD0mF8iSiMiNs30BiLO3EpfGLZUT2MSX/G+o7ZywDzliWQ3OPtTZ0PTC3B3ca1UAf4cJMHB+2Bf56EriJuRA==", "dev": true, "requires": { "xml-name-validator": "^3.0.0" } }, "walker": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.7.tgz", "integrity": "sha1-L3+bj9ENZ3JisYqITijRlhjgKPs=", "dev": true, "requires": { "makeerror": "1.0.x" } }, "weak-map": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/weak-map/-/weak-map-1.0.8.tgz", "integrity": "sha512-lNR9aAefbGPpHO7AEnY0hCFjz1eTkWCXYvkTRrTHs9qv8zJp+SkVYpzfLIFXQQiG3tVvbNFQgVg2bQS8YGgxyw==" }, "webidl-conversions": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-6.1.0.tgz", "integrity": "sha512-qBIvFLGiBpLjfwmYAaHPXsn+ho5xZnGvyGvsarywGNc8VyQJUMHJ8OBKGGrPER0okBeMDaan4mNBlgBROxuI8w==", "dev": true }, "whatwg-encoding": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-1.0.5.tgz", "integrity": "sha512-b5lim54JOPN9HtzvK9HFXvBma/rnfFeqsic0hSpjtDbVxR3dJKLc+KB4V6GgiGOvl7CY/KNh8rxSo9DKQrnUEw==", "dev": true, "requires": { "iconv-lite": "0.4.24" } }, "whatwg-mimetype": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz", "integrity": "sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g==", "dev": true }, "whatwg-url": { "version": "8.7.0", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-8.7.0.tgz", "integrity": "sha512-gAojqb/m9Q8a5IV96E3fHJM70AzCkgt4uXYX2O7EmuyOnLrViCQlsEBmF9UQIu3/aeAIp2U17rtbpZWNntQqdg==", "dev": true, "requires": { "lodash": "^4.7.0", "tr46": "^2.1.0", "webidl-conversions": "^6.1.0" } }, "which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", "dev": true, "requires": { "isexe": "^2.0.0" } }, "which-module": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", "dev": true }, "wide-align": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.3.tgz", "integrity": "sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA==", "requires": { "string-width": "^1.0.2 || 2" } }, "word-wrap": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.4.tgz", "integrity": "sha512-2V81OA4ugVo5pRo46hAoD2ivUJx8jXmWXfUkY4KFNw0hEptvN0QfH3K4nHiwzGeKl5rFKedV48QVoqYavy4YpA==", "dev": true }, "wordwrap": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", "dev": true }, "wordwrapjs": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-4.0.1.tgz", "integrity": "sha512-kKlNACbvHrkpIw6oPeYDSmdCTu2hdMHoyXLTcUKala++lx5Y+wjJ/e474Jqv5abnVmwxw08DiTuHmw69lJGksA==", "dev": true, "requires": { "reduce-flatten": "^2.0.0", "typical": "^5.2.0" }, "dependencies": { "typical": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/typical/-/typical-5.2.0.tgz", "integrity": "sha512-dvdQgNDNJo+8B2uBQoqdb11eUCE1JQXhvjC/CZtgvZseVd5TYMXnq0+vuUemXbd/Se29cTaUuPX3YIc2xgbvIg==", "dev": true } } }, "wrap-ansi": { "version": "6.2.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", "dev": true, "requires": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" }, "dependencies": { "ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true }, "ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { "color-convert": "^2.0.1" } }, "color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "requires": { "color-name": "~1.1.4" } }, "color-name": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, "is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true }, "string-width": { "version": "4.2.2", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz", "integrity": "sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA==", "dev": true, "requires": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.0" } }, "strip-ansi": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", "dev": true, "requires": { "ansi-regex": "^5.0.0" } } } }, "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write-file-atomic": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz", "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", "dev": true, "requires": { "imurmurhash": "^0.1.4", "is-typedarray": "^1.0.0", "signal-exit": "^3.0.2", "typedarray-to-buffer": "^3.1.5" } }, "ws": { "version": "7.5.4", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.4.tgz", "integrity": "sha512-zP9z6GXm6zC27YtspwH99T3qTG7bBFv2VIkeHstMLrLlDJuzA7tQ5ls3OJ1hOGGCzTQPniNJoHXIAOS0Jljohg==", "dev": true }, "xml-name-validator": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-3.0.0.tgz", "integrity": "sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw==", "dev": true }, "xmlchars": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", "dev": true }, "y18n": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", "dev": true }, "yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==" }, "yargs": { "version": "15.4.1", "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", "dev": true, "requires": { "cliui": "^6.0.0", "decamelize": "^1.2.0", "find-up": "^4.1.0", "get-caller-file": "^2.0.1", "require-directory": "^2.1.1", "require-main-filename": "^2.0.0", "set-blocking": "^2.0.0", "string-width": "^4.2.0", "which-module": "^2.0.0", "y18n": "^4.0.0", "yargs-parser": "^18.1.2" }, "dependencies": { "ansi-regex": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", "dev": true }, "is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true }, "string-width": { "version": "4.2.2", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz", "integrity": "sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA==", "dev": true, "requires": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.0" } }, "strip-ansi": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", "dev": true, "requires": { "ansi-regex": "^5.0.0" } } } }, "yargs-parser": { "version": "18.1.3", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", "dev": true, "requires": { "camelcase": "^5.0.0", "decamelize": "^1.2.0" } } } }
0
hf_public_repos/tokenizers/bindings
hf_public_repos/tokenizers/bindings/node/package.json
{ "name": "tokenizers", "version": "0.13.3", "description": "", "main": "./dist/index.js", "types": "./dist/index.d.ts", "repository": { "type": "git", "url": "git+https://github.com/huggingface/tokenizers.git" }, "bugs": { "url": "https://github.com/huggingface/tokenizers/issues" }, "homepage": "https://github.com/huggingface/tokenizers/tree/master/bindings/node", "author": "Anthony MOI <m.anthony.moi@gmail.com>", "license": "Apache-2.0", "dependencies": { "@types/node": "^13.13.52", "native": "^0.3.3", "node-pre-gyp": "^0.14.0", "package.json": "^2.0.1" }, "devDependencies": { "@types/jest": "^26.0.24", "@typescript-eslint/eslint-plugin": "^3.10.1", "@typescript-eslint/parser": "^3.10.1", "eslint": "^7.32.0", "eslint-config-prettier": "^6.15.0", "eslint-plugin-jest": "^23.20.0", "eslint-plugin-jsdoc": "^30.7.13", "eslint-plugin-prettier": "^3.4.1", "eslint-plugin-simple-import-sort": "^5.0.3", "jest": "^26.6.3", "neon-cli": "^0.9.1", "prettier": "^2.5.1", "shelljs": "^0.8.3", "ts-jest": "^26.5.6", "typescript": "^3.9.10" }, "engines": { "node": ">=10 < 11 || >=12 <14" }, "scripts": { "dev-ts": "rm -rf dist && tsc -p tsconfig.lib.json && rsync -a $(pwd)/lib/bindings/ dist/bindings/", "dev-rs": "neon build", "dev": "npm run dev-rs && npm run dev-ts", "compile": "neon build --release", "clean-rs": "neon clean", "package": "node-pre-gyp package", "test": "jest && cargo test --manifest-path native/Cargo.toml", "lint-check": "eslint --ext .js,.ts lib examples", "lint": "eslint --fix --ext .js,.ts lib examples" }, "binary": { "module_name": "index", "module_path": "./bin-package", "host": "https://tokenizers-releases.s3.amazonaws.com/node", "package_name": "{module_name}-v{version}-{node_abi}-{platform}-{arch}-{libc}.tar.gz", "remote_path": "{version}" } }
0
hf_public_repos/tokenizers/bindings
hf_public_repos/tokenizers/bindings/node/tsconfig.json
{ "include": [ "./lib" ], "compilerOptions": { /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ "target": "ES2017", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ "lib": [], /* Specify library files to be included in the compilation. */ // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ "declaration": true, /* Generates corresponding '.d.ts' file. */ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ "outDir": "./dist", /* Redirect output structure to the directory. */ "rootDir": "./lib", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "composite": true, /* Enable project compilation */ // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ // "removeComments": true, /* Do not emit comments to output. */ // "noEmit": true, /* Do not emit outputs. */ // "importHelpers": true, /* Import emit helpers from 'tslib'. */ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ /* Strict Type-Checking Options */ "strict": true, /* Enable all strict type-checking options. */ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* Enable strict null checks. */ // "strictFunctionTypes": true, /* Enable strict checking of function types. */ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ /* Additional Checks */ // "noUnusedLocals": true, /* Report errors on unused locals. */ // "noUnusedParameters": true, /* Report errors on unused parameters. */ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ /* Module Resolution Options */ "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ } }
0
hf_public_repos/tokenizers/bindings
hf_public_repos/tokenizers/bindings/node/tsconfig.lib.json
{ "extends": "./tsconfig.json", "exclude": [ "./**/*.test.ts" ] }
0
hf_public_repos/tokenizers/bindings
hf_public_repos/tokenizers/bindings/node/tsconfig.prod.json
{ "extends": "./tsconfig.json", "exclude": [ "./**/*.test.ts" ], "compilerOptions": { "sourceMap": false } }
0
hf_public_repos/tokenizers/bindings/node/examples
hf_public_repos/tokenizers/bindings/node/examples/documentation/pipeline.test.ts
/* eslint-disable */ var globRequire = require; describe("pipelineExample", () => { // This is a hack to let us require using path similar to what the user has to use function require(mod: string) { if (mod.startsWith("tokenizers/")) { let path = mod.slice("tokenizers/".length); return globRequire("../../lib/" + path); } else { return globRequire(mod); } } let console = { log: (..._args: any[]) => {} }; it("shows pipeline parts", async () => { // START reload_tokenizer let { Tokenizer } = require("tokenizers/bindings/tokenizer"); let tokenizer = Tokenizer.fromFile("data/tokenizer-wiki.json"); // END reload_tokenizer // START setup_normalizer let { sequenceNormalizer, nfdNormalizer, stripAccentsNormalizer } = require("tokenizers/bindings/normalizers"); let normalizer = sequenceNormalizer([nfdNormalizer(), stripAccentsNormalizer()]); // END setup_normalizer // START test_normalizer let normalized = normalizer.normalizeString("Héllò hôw are ü?") // "Hello how are u?" // END test_normalizer expect(normalized).toEqual("Hello how are u?"); // START replace_normalizer tokenizer.setNormalizer(normalizer) // END replace_normalizer // START setup_pre_tokenizer let { whitespacePreTokenizer } = require("tokenizers/bindings/pre-tokenizers"); var preTokenizer = whitespacePreTokenizer(); var preTokenized = preTokenizer.preTokenizeString("Hello! How are you? I'm fine, thank you."); // END setup_pre_tokenizer expect(preTokenized).toEqual([ ["Hello", [0, 5]], ["!", [5, 6]], ["How", [7, 10]], ["are", [11, 14]], ["you", [15, 18]], ["?", [18, 19]], ["I", [20, 21]], ["'", [21, 22]], ['m', [22, 23]], ["fine", [24, 28]], [",", [28, 29]], ["thank", [30, 35]], ["you", [36, 39]], [".", [39, 40]] ]); // START combine_pre_tokenizer let { sequencePreTokenizer, digitsPreTokenizer } = require("tokenizers/bindings/pre-tokenizers"); var preTokenizer = sequencePreTokenizer([whitespacePreTokenizer(), digitsPreTokenizer(true)]); var preTokenized = preTokenizer.preTokenizeString("Call 911!"); // END combine_pre_tokenizer // START replace_pre_tokenizer tokenizer.setPreTokenizer(preTokenizer) // END replace_pre_tokenizer // START setup_processor let { templateProcessing } = require("tokenizers/bindings/post-processors"); tokenizer.setPostProcessor(templateProcessing( "[CLS] $A [SEP]", "[CLS] $A [SEP] $B:1 [SEP]:1", [["[CLS]", 1], ["[SEP]", 2]] )); // END setup_processor // START test_decoding let { promisify } = require('util'); let encode = promisify(tokenizer.encode.bind(tokenizer)); let decode = promisify(tokenizer.decode.bind(tokenizer)); let output = await encode("Hello, y'all! How are you 😁 ?"); console.log(output.getIds()); // [1, 27253, 16, 93, 11, 5097, 5, 7961, 5112, 6218, 0, 35, 2] let decoded = await decode([1, 27253, 16, 93, 11, 5097, 5, 7961, 5112, 6218, 0, 35, 2], true); // "Hello , y ' all ! How are you ?" // END test_decoding expect(decoded).toEqual("Hello , y ' all ! How are you ?"); }); it.skip("trains the tokenizer", async () => { // START bert_setup_tokenizer let { Tokenizer } = require("tokenizers/bindings/tokenizer"); let { WordPiece } = require("tokenizers/bindings/models"); let bertTokenizer = new Tokenizer(WordPiece.init({}, { unkToken: "[UNK]" })); // END bert_setup_tokenizer // START bert_setup_normalizer let { sequenceNormalizer, lowercaseNormalizer, nfdNormalizer, stripAccentsNormalizer } = require("tokenizers/bindings/normalizers"); bertTokenizer.setNormalizer(sequenceNormalizer([ nfdNormalizer(), lowercaseNormalizer(), stripAccentsNormalizer() ])) // END bert_setup_normalizer // START bert_setup_pre_tokenizer let { whitespacePreTokenizer } = require("tokenizers/bindings/pre-tokenizers"); bertTokenizer.setPreTokenizer(whitespacePreTokenizer()); // END bert_setup_pre_tokenizer // START bert_setup_processor let { templateProcessing } = require("tokenizers/bindings/post-processors"); bertTokenizer.setPostProcessor(templateProcessing( "[CLS] $A [SEP]", "[CLS] $A [SEP] $B:1 [SEP]:1", [["[CLS]", 1], ["[SEP]", 2]] )); // END bert_setup_processor // START bert_train_tokenizer let { wordPieceTrainer } = require("tokenizers/bindings/trainers"); let trainer = wordPieceTrainer({ vocabSize: 30522, specialTokens: ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"] }); let files = ["test", "train", "valid"].map(split => `data/wikitext-103-raw/wiki.${split}.raw`); bertTokenizer.train(files, trainer); bertTokenizer.save("data/bert-wiki.json") // END bert_train_tokenizer }); it("shows a full bert example", async () => { let { Tokenizer } = require("tokenizers/bindings/tokenizer"); let bertTokenizer = await Tokenizer.fromFile("data/bert-wiki.json") // START bert_test_decoding let { promisify } = require("util"); let encode = promisify(bertTokenizer.encode.bind(bertTokenizer)); let decode = promisify(bertTokenizer.decode.bind(bertTokenizer)); let output = await encode("Welcome to the 🤗 Tokenizers library."); console.log(output.getTokens()); // ["[CLS]", "welcome", "to", "the", "[UNK]", "tok", "##eni", "##zer", "##s", "library", ".", "[SEP]"] var decoded = await decode(output.getIds(), true); // "welcome to the tok ##eni ##zer ##s library ." // END bert_test_decoding expect(decoded).toEqual("welcome to the tok ##eni ##zer ##s library ."); // START bert_proper_decoding let { wordPieceDecoder } = require("tokenizers/bindings/decoders"); bertTokenizer.setDecoder(wordPieceDecoder()); var decoded = await decode(output.getIds(), true); // "welcome to the tokenizers library." // END bert_proper_decoding expect(decoded).toEqual("welcome to the tokenizers library."); }); });
0
hf_public_repos/tokenizers/bindings/node/examples
hf_public_repos/tokenizers/bindings/node/examples/documentation/quicktour.test.ts
/* eslint-disable */ var globRequire = require; describe("quicktourExample", () => { function require(mod: string) { if (mod.startsWith("tokenizers/")) { let path = mod.slice("tokenizers/".length); return globRequire("../../lib/" + path); } else { return globRequire(mod); } } it.skip("trains the tokenizer", async () => { // START init_tokenizer let { Tokenizer } = require("tokenizers/bindings/tokenizer"); let { BPE } = require("tokenizers/bindings/models"); let tokenizer = new Tokenizer(BPE.init({}, [], { unkToken: "[UNK]" })); // END init_tokenizer // START init_trainer let { bpeTrainer } = require("tokenizers/bindings/trainers"); let trainer = bpeTrainer({ specialTokens: ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"] }); // END init_trainer // START init_pretok let { whitespacePreTokenizer } = require("tokenizers/bindings/pre-tokenizers"); tokenizer.setPreTokenizer(whitespacePreTokenizer()); // END init_pretok // START train let files = ["test", "train", "valid"].map(split => `data/wikitext-103-raw/wiki.${split}.raw`); tokenizer.train(files, trainer); // END train // START save tokenizer.save("data/tokenizer-wiki.json"); // END save }); it("shows a quicktour example", async () => { let { Tokenizer } = require("tokenizers/bindings/tokenizer"); let console = { log: (..._args: any[]) => {} }; // START reload_tokenizer let tokenizer = Tokenizer.fromFile("data/tokenizer-wiki.json"); // END reload_tokenizer // START encode let { promisify } = require('util'); let encode = promisify(tokenizer.encode.bind(tokenizer)); var output = await encode("Hello, y'all! How are you 😁 ?"); // END encode // START print_tokens console.log(output.getTokens()); // ["Hello", ",", "y", "'", "all", "!", "How", "are", "you", "[UNK]", "?"] // END print_tokens expect(output.getTokens()).toEqual([ "Hello", ",", "y", "'", "all", "!", "How", "are", "you", "[UNK]", "?", ]); // START print_ids console.log(output.getIds()); // [27253, 16, 93, 11, 5097, 5, 7961, 5112, 6218, 0, 35] // END print_ids expect(output.getIds()).toEqual([27253, 16, 93, 11, 5097, 5, 7961, 5112, 6218, 0, 35]); // START print_offsets let offsets = output.getOffsets(); console.log(offsets[9]); // (26, 27) // END print_offsets expect(offsets[9]).toEqual([26, 27]); // START use_offsets let { slice } = require("tokenizers/bindings/utils"); let sentence = "Hello, y'all! How are you 😁 ?" let [start, end] = offsets[9]; console.log(slice(sentence, start, end)); // "😁" // END use_offsets expect(slice(sentence, start, end)).toEqual("😁"); // START check_sep console.log(tokenizer.tokenToId("[SEP]")); // 2 // END check_sep expect(tokenizer.tokenToId("[SEP]")).toEqual(2); // START init_template_processing let { templateProcessing } = require("tokenizers/bindings/post-processors"); tokenizer.setPostProcessor(templateProcessing( "[CLS] $A [SEP]", "[CLS] $A [SEP] $B:1 [SEP]:1", [ ["[CLS]", tokenizer.tokenToId("[CLS]")], ["[SEP]", tokenizer.tokenToId("[SEP]")], ], )); // END init_template_processing // START print_special_tokens var output = await encode("Hello, y'all! How are you 😁 ?"); console.log(output.getTokens()); // ["[CLS]", "Hello", ",", "y", "'", "all", "!", "How", "are", "you", "[UNK]", "?", "[SEP]"] // END print_special_tokens expect(output.getTokens()).toEqual([ "[CLS]", "Hello", ",", "y", "'", "all", "!", "How", "are", "you", "[UNK]", "?", "[SEP]", ]); // START print_special_tokens_pair var output = await encode("Hello, y'all!", "How are you 😁 ?"); console.log(output.getTokens()); // ["[CLS]", "Hello", ",", "y", "'", "all", "!", "[SEP]", "How", "are", "you", "[UNK]", "?", "[SEP]"] // END print_special_tokens_pair expect(output.getTokens()).toEqual([ "[CLS]", "Hello", ",", "y", "'", "all", "!", "[SEP]", "How", "are", "you", "[UNK]", "?", "[SEP]", ]); // START print_type_ids console.log(output.getTypeIds()); // [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] // END print_type_ids expect(output.getTypeIds()).toEqual([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]); // START encode_batch let encodeBatch = promisify(tokenizer.encodeBatch.bind(tokenizer)); var output = await encodeBatch(["Hello, y'all!", "How are you 😁 ?"]); // END encode_batch // START encode_batch_pair var output = await encodeBatch( [["Hello, y'all!", "How are you 😁 ?"], ["Hello to you too!", "I'm fine, thank you!"]] ); // END encode_batch_pair // START enable_padding tokenizer.setPadding({ padId: 3, padToken: "[PAD]" }); // END enable_padding // START print_batch_tokens var output = await encodeBatch(["Hello, y'all!", "How are you 😁 ?"]); console.log(output[1].getTokens()); // ["[CLS]", "How", "are", "you", "[UNK]", "?", "[SEP]", "[PAD]"] // END print_batch_tokens expect(output[1].getTokens()).toEqual(["[CLS]", "How", "are", "you", "[UNK]", "?", "[SEP]", "[PAD]"]); // START print_attention_mask console.log(output[1].getAttentionMask()); // [1, 1, 1, 1, 1, 1, 1, 0] // END print_attention_mask expect(output[1].getAttentionMask()).toEqual([1, 1, 1, 1, 1, 1, 1, 0]); }); });
0
hf_public_repos/tokenizers/bindings/node
hf_public_repos/tokenizers/bindings/node/lib/index.ts
// export * from "./bindings"; export * from "./implementations/tokenizers"; export * from "./bindings/enums"; export { slice } from "./bindings/utils"; export { AddedToken, AddedTokenOptions, PaddingConfiguration, PaddingOptions, InputSequence, EncodeInput, EncodeOptions, Tokenizer, TruncationConfiguration, TruncationOptions, } from "./bindings/tokenizer"; export * as models from "./bindings/models"; export * as normalizers from "./bindings/normalizers"; export * as pre_tokenizers from "./bindings/pre-tokenizers"; export * as decoders from "./bindings/decoders"; export * as post_processors from "./bindings/post-processors"; export * as trainers from "./bindings/trainers"; export { Encoding } from "./implementations/encoding";
0
hf_public_repos/tokenizers/bindings/node/lib
hf_public_repos/tokenizers/bindings/node/lib/bindings/decoders.d.ts
/** * This class is not supposed to be instantiated directly. Instead, any implementation of * a Decoder will return an instance of this class when instantiated. */ // eslint-disable-next-line @typescript-eslint/no-empty-interface interface Decoder { decode(tokens: string[]): string; } /** * Instantiate a new ByteLevel Decoder */ export function byteLevelDecoder(): Decoder; /** * Instantiate a new Replace Decoder * @param [pattern] The pattern to replace * @param [content] The replacement. */ export function replaceDecoder(pattern: string, content: string): Decoder; /** * Instantiate a new WordPiece Decoder * @param [prefix='##'] The prefix to use for subwords that are not a beginning-of-word * @param [cleanup=true] Whether to cleanup some tokenization artifacts. * Mainly spaces before punctuation, and some abbreviated english forms. */ export function wordPieceDecoder(prefix?: string, cleanup?: boolean): Decoder; /** * Instantiate a new ByteFallback Decoder * ByteFallback is a simple trick which converts tokens looking like `<0x61>` * to pure bytes, and attempts to make them into a string. If the tokens * cannot be decoded you will get � instead for each inconvertable byte token */ export function byteFallbackDecoder(): Decoder; /** * Instantiate a new Fuse Decoder which fuses all tokens into one string */ export function fuseDecoder(): Decoder; /** * Instantiate a new Strip Decoder * @param [content] The character to strip * @param [left] The number of chars to remove from the left of each token * @param [right] The number of chars to remove from the right of each token */ export function stripDecoder(content: string, left: number, right: number): Decoder; /** * Instantiate a new Metaspace * * @param [replacement='▁'] The replacement character. * Must be exactly one character. By default we use the `▁` (U+2581) meta symbol (same as in SentencePiece). * @param [addPrefixSpace=true] Whether to add a space to the first word if there isn't already one. * This lets us treat `hello` exactly like `say hello`. */ export function metaspaceDecoder(replacement?: string, addPrefixSpace?: boolean): Decoder; /** * Instantiate a new BPE Decoder * @param [suffix='</w>'] The suffix that was used to characterize an end-of-word. * This suffix will be replaced by whitespaces during the decoding */ export function bpeDecoder(suffix?: string): Decoder; /** * Instantiate a new CTC Decoder * @param [pad_token='pad'] The pad token used by CTC to delimit a new token. * @param [word_delimiter_token='|'] The word delimiter token. It will be replaced by a space * @param [cleanup=true] Whether to cleanup some tokenization artifacts. * Mainly spaces before punctuation, and some abbreviated english forms. */ export function ctcDecoder( pad_token?: string, word_delimiter_token?: string, cleanup?: boolean ): Decoder; /** * Instantiate a new Sequence Decoder * @param [decoders] The decoders to chain */ export function sequenceDecoder(decoders: Decoder[]): Decoder;
0