Datasets:

License:
biblenlp-corpus / biblenlp-corpus.py
ajland's picture
Convert name keyword argument to an md5 hash
cd72cf9 verified
raw
history blame
22.1 kB
# coding=utf-8
# Copyright 2020 HuggingFace Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
import os
import datasets
from tqdm import tqdm
import numpy as np
import ijson
import hashlib
_VERSION = "1.0.0"
_LANGUAGES = ['aai', 'aak', 'aau', 'aaz', 'abt', 'abx', 'aby', 'acf', 'acr', 'acu', 'adz', 'aer', 'aey', 'agd', 'agg', 'agm', 'agn', 'agr', 'agt', 'agu', 'aia', 'aii', 'aka', 'ake', 'alp', 'alq', 'als', 'aly', 'ame', 'amf', 'amk', 'amm', 'amn', 'amo', 'amp', 'amr', 'amu', 'amx', 'anh', 'anv', 'aoi', 'aoj', 'aom', 'aon', 'apb', 'ape', 'apn', 'apr', 'apu', 'apw', 'apz', 'arb', 'are', 'arl', 'arn', 'arp', 'asm', 'aso', 'ata', 'atb', 'atd', 'atg', 'att', 'auc', 'aui', 'auy', 'avt', 'awb', 'awk', 'awx', 'azb', 'azg', 'azz', 'bao', 'bba', 'bbb', 'bbr', 'bch', 'bco', 'bdd', 'bea', 'bef', 'bel', 'ben', 'beo', 'beu', 'bgs', 'bgt', 'bhg', 'bhl', 'big', 'bjk', 'bjp', 'bjr', 'bjv', 'bjz', 'bkd', 'bki', 'bkq', 'bkx', 'bla', 'blw', 'blz', 'bmh', 'bmk', 'bmr', 'bmu', 'bnp', 'boa', 'boj', 'bon', 'box', 'bpr', 'bps', 'bqc', 'bqp', 'bre', 'bsj', 'bsn', 'bsp', 'bss', 'buk', 'bus', 'bvd', 'bvr', 'bxh', 'byr', 'byx', 'bzd', 'bzh', 'bzj', 'caa', 'cab', 'cac', 'caf', 'cak', 'cao', 'cap', 'car', 'cav', 'cax', 'cbc', 'cbi', 'cbk', 'cbr', 'cbs', 'cbt', 'cbu', 'cbv', 'cco', 'ceb', 'cek', 'ces', 'cgc', 'cha', 'chd', 'chf', 'chk', 'chq', 'chz', 'cjo', 'cjv', 'ckb', 'cle', 'clu', 'cme', 'cmn', 'cni', 'cnl', 'cnt', 'cof', 'con', 'cop', 'cot', 'cpa', 'cpb', 'cpc', 'cpu', 'cpy', 'crn', 'crx', 'cso', 'csy', 'cta', 'cth', 'ctp', 'ctu', 'cub', 'cuc', 'cui', 'cuk', 'cut', 'cux', 'cwe', 'cya', 'daa', 'dad', 'dah', 'dan', 'ded', 'deu', 'dgc', 'dgr', 'dgz', 'dhg', 'dif', 'dik', 'dji', 'djk', 'djr', 'dob', 'dop', 'dov', 'dwr', 'dww', 'dwy', 'ebk', 'eko', 'emi', 'emp', 'eng', 'enq', 'epo', 'eri', 'ese', 'esk', 'etr', 'ewe', 'faa', 'fai', 'far', 'ffm', 'for', 'fra', 'fue', 'fuf', 'fuh', 'gah', 'gai', 'gam', 'gaw', 'gdn', 'gdr', 'geb', 'gfk', 'ghs', 'glk', 'gmv', 'gng', 'gnn', 'gnw', 'gof', 'grc', 'gub', 'guh', 'gui', 'guj', 'gul', 'gum', 'gun', 'guo', 'gup', 'gux', 'gvc', 'gvf', 'gvn', 'gvs', 'gwi', 'gym', 'gyr', 'hat', 'hau', 'haw', 'hbo', 'hch', 'heb', 'heg', 'hin', 'hix', 'hla', 'hlt', 'hmo', 'hns', 'hop', 'hot', 'hrv', 'hto', 'hub', 'hui', 'hun', 'hus', 'huu', 'huv', 'hvn', 'ian', 'ign', 'ikk', 'ikw', 'ilo', 'imo', 'inb', 'ind', 'ino', 'iou', 'ipi', 'isn', 'ita', 'iws', 'ixl', 'jac', 'jae', 'jao', 'jic', 'jid', 'jiv', 'jni', 'jpn', 'jvn', 'kan', 'kaq', 'kbc', 'kbh', 'kbm', 'kbq', 'kdc', 'kde', 'kdl', 'kek', 'ken', 'kew', 'kgf', 'kgk', 'kgp', 'khs', 'khz', 'kik', 'kiw', 'kiz', 'kje', 'kjn', 'kjs', 'kkc', 'kkl', 'klt', 'klv', 'kmg', 'kmh', 'kmk', 'kmo', 'kms', 'kmu', 'kne', 'knf', 'knj', 'knv', 'kos', 'kpf', 'kpg', 'kpj', 'kpr', 'kpw', 'kpx', 'kqa', 'kqc', 'kqf', 'kql', 'kqw', 'ksd', 'ksj', 'ksr', 'ktm', 'kto', 'kud', 'kue', 'kup', 'kvg', 'kvn', 'kwd', 'kwf', 'kwi', 'kwj', 'kyc', 'kyf', 'kyg', 'kyq', 'kyz', 'kze', 'lac', 'lat', 'lbb', 'lbk', 'lcm', 'leu', 'lex', 'lgl', 'lid', 'lif', 'lin', 'lit', 'llg', 'lug', 'luo', 'lww', 'maa', 'maj', 'mal', 'mam', 'maq', 'mar', 'mau', 'mav', 'maz', 'mbb', 'mbc', 'mbh', 'mbj', 'mbl', 'mbs', 'mbt', 'mca', 'mcb', 'mcd', 'mcf', 'mco', 'mcp', 'mcq', 'mcr', 'mdy', 'med', 'mee', 'mek', 'meq', 'met', 'meu', 'mgc', 'mgh', 'mgw', 'mhl', 'mib', 'mic', 'mie', 'mig', 'mih', 'mil', 'mio', 'mir', 'mit', 'miz', 'mjc', 'mkj', 'mkl', 'mkn', 'mks', 'mle', 'mlh', 'mlp', 'mmo', 'mmx', 'mna', 'mop', 'mox', 'mph', 'mpj', 'mpm', 'mpp', 'mps', 'mpt', 'mpx', 'mqb', 'mqj', 'msb', 'msc', 'msk', 'msm', 'msy', 'mti', 'mto', 'mux', 'muy', 'mva', 'mvn', 'mwc', 'mwe', 'mwf', 'mwp', 'mxb', 'mxp', 'mxq', 'mxt', 'mya', 'myk', 'myu', 'myw', 'myy', 'mzz', 'nab', 'naf', 'nak', 'nas', 'nay', 'nbq', 'nca', 'nch', 'ncj', 'ncl', 'ncu', 'ndg', 'ndj', 'nfa', 'ngp', 'ngu', 'nhe', 'nhg', 'nhi', 'nho', 'nhr', 'nhu', 'nhw', 'nhy', 'nif', 'nii', 'nin', 'nko', 'nld', 'nlg', 'nmw', 'nna', 'nnq', 'noa', 'nop', 'not', 'nou', 'npi', 'npl', 'nsn', 'nss', 'ntj', 'ntp', 'ntu', 'nuy', 'nvm', 'nwi', 'nya', 'nys', 'nyu', 'obo', 'okv', 'omw', 'ong', 'ons', 'ood', 'opm', 'ory', 'ote', 'otm', 'otn', 'otq', 'ots', 'pab', 'pad', 'pah', 'pan', 'pao', 'pes', 'pib', 'pio', 'pir', 'piu', 'pjt', 'pls', 'plu', 'pma', 'poe', 'poh', 'poi', 'pol', 'pon', 'por', 'poy', 'ppo', 'prf', 'pri', 'ptp', 'ptu', 'pwg', 'qub', 'quc', 'quf', 'quh', 'qul', 'qup', 'qvc', 'qve', 'qvh', 'qvm', 'qvn', 'qvs', 'qvw', 'qvz', 'qwh', 'qxh', 'qxn', 'qxo', 'rai', 'reg', 'rgu', 'rkb', 'rmc', 'rmy', 'ron', 'roo', 'rop', 'row', 'rro', 'ruf', 'rug', 'rus', 'rwo', 'sab', 'san', 'sbe', 'sbk', 'sbs', 'seh', 'sey', 'sgb', 'sgz', 'shj', 'shp', 'sim', 'sja', 'sll', 'smk', 'snc', 'snn', 'snp', 'snx', 'sny', 'som', 'soq', 'soy', 'spa', 'spl', 'spm', 'spp', 'sps', 'spy', 'sri', 'srm', 'srn', 'srp', 'srq', 'ssd', 'ssg', 'ssx', 'stp', 'sua', 'sue', 'sus', 'suz', 'swe', 'swh', 'swp', 'sxb', 'tac', 'taj', 'tam', 'tav', 'taw', 'tbc', 'tbf', 'tbg', 'tbl', 'tbo', 'tbz', 'tca', 'tcs', 'tcz', 'tdt', 'tee', 'tel', 'ter', 'tet', 'tew', 'tfr', 'tgk', 'tgl', 'tgo', 'tgp', 'tha', 'thd', 'tif', 'tim', 'tiw', 'tiy', 'tke', 'tku', 'tlf', 'tmd', 'tna', 'tnc', 'tnk', 'tnn', 'tnp', 'toc', 'tod', 'tof', 'toj', 'ton', 'too', 'top', 'tos', 'tpa', 'tpi', 'tpt', 'tpz', 'trc', 'tsw', 'ttc', 'tte', 'tuc', 'tue', 'tuf', 'tuo', 'tur', 'tvk', 'twi', 'txq', 'txu', 'tzj', 'tzo', 'ubr', 'ubu', 'udu', 'uig', 'ukr', 'uli', 'ulk', 'upv', 'ura', 'urb', 'urd', 'uri', 'urt', 'urw', 'usa', 'usp', 'uvh', 'uvl', 'vid', 'vie', 'viv', 'vmy', 'waj', 'wal', 'wap', 'wat', 'wbi', 'wbp', 'wed', 'wer', 'wim', 'wiu', 'wiv', 'wmt', 'wmw', 'wnc', 'wnu', 'wol', 'wos', 'wrk', 'wro', 'wrs', 'wsk', 'wuv', 'xav', 'xbi', 'xed', 'xla', 'xnn', 'xon', 'xsi', 'xtd', 'xtm', 'yaa', 'yad', 'yal', 'yap', 'yaq', 'yby', 'ycn', 'yka', 'yle', 'yml', 'yon', 'yor', 'yrb', 'yre', 'yss', 'yuj', 'yut', 'yuw', 'yva', 'zaa', 'zab', 'zac', 'zad', 'zai', 'zaj', 'zam', 'zao', 'zap', 'zar', 'zas', 'zat', 'zav', 'zaw', 'zca', 'zga', 'zia', 'ziw', 'zlm', 'zos', 'zpc', 'zpl', 'zpm', 'zpo', 'zpq', 'zpu', 'zpv', 'zpz', 'zsr', 'ztq', 'zty', 'zyp']
_DESCRIPTION = "Bible Parallel Corpus"
_HOMEPAGE = 'https://github.com/BibleNLP/ebible-corpus'
_PAIR = 'all'
_CITATION = """\
@InProceedings{huggingface:dataset,
title = {A great new dataset},
author={huggingface, Inc.
},
year={2020}
}
"""
_LICENSE = 'Creative Commons and Public Domain, specified in the dataset'
_FILES = {'corpus':'corpus.json','vref':'vref.txt'}
class BiblenlpCorpusConfig(datasets.BuilderConfig):
def __init__(self, languages=[], pair='all', **kwargs):
'''
languages: list of languages to include
pair: 'all', 'range', or 'single' to specify whether verse ranges, single pairings, or all pairs are included
**kwargs: additional arguments to pass to the superclass'''
super(BiblenlpCorpusConfig, self).__init__(name=hashlib.md5(f'{"-".join([x for x in languages])}'.encode('UTF-8')).hexdigest(), **kwargs)
self.languages = languages
self.pair = pair
class BiblenlpCorpus(datasets.GeneratorBasedBuilder):
BUILDER_CONFIGS = [
BiblenlpCorpusConfig(
languages=_LANGUAGES,
pair=_PAIR,
description = f'Parallel Bible verses with {_PAIR} pairings of {"-".join([x for x in _LANGUAGES])} languages',
)
]
BUILDER_CONFIG_CLASS = BiblenlpCorpusConfig
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"translation": datasets.features.TranslationVariableLanguages(languages=_LANGUAGES),
"files": datasets.features.Sequence( {'lang':datasets.Value("string"), 'file':datasets.Value("string")} ),
"ref": datasets.features.Sequence( datasets.Value("string") ),
"licenses": datasets.features.Sequence( datasets.Value("string") ),
"copyrights": datasets.features.Sequence( datasets.Value("string") )
},
),
supervised_keys=None,
homepage=_HOMEPAGE,
citation=_CITATION,
license=_LICENSE,
version=_VERSION
) #
def _split_generators(self, dl_manager):
downloaded_files = dl_manager.download(_FILES)
def parse_json(json_filename, langs):
with open(json_filename, 'rb') as input_file:
# load json iteratively
parser = ijson.parse(input_file)
parsed_dict = {lang: [] for lang in langs}
idx = {lang: -1 for lang in langs}
for prefix, event, value in parser:
#print(f'prefix:{prefix}, event:{event}, value:{value}')
if any([prefix.startswith(f'{lang}.') for lang in langs]):
#print(f'prefix:{prefix}, event:{event}, value:{value}')
if event == 'start_map':
idx[prefix.split('.')[0]] += 1
tmpdict ={}
tmpdict['verses']=[]
if prefix.endswith('verses.item'):
tmpdict['verses'].append(value)
if prefix.endswith('copyright'):
tmpdict['copyright'] = value
if prefix.endswith('text'):
tmpdict['text'] = value
if prefix.endswith('file'):
tmpdict['file'] = value
if prefix.endswith('license'):
tmpdict['license'] = value
if event == 'end_map':
#write the dictionary
parsed_dict[prefix.split('.')[0]].append( tmpdict.copy() )
return(parsed_dict)
def define_splits(corpus_slice, langs):
verse2split = {}
langtexts = {}
textverses = {}
vindexes = {}
vgroups = []
versesets ={}
np.random.seed(42)
for lang in tqdm(langs):
langtexts[lang] = set()
textverses[lang]={}
vindexes[lang]={}
for idx,line in enumerate(corpus_slice[lang]):
langtexts[lang].add(line['file'])
for v in line['verses']:
if not textverses[lang].get(line['file']):
textverses[lang][line['file']] = set()
textverses[lang][line['file']].add(v)
if not vindexes[lang].get(v):
vindexes[lang][v] = [idx]
else:
vindexes[lang][v].append(idx)
#print(list(vindexes['eng'].keys())[0:10])
#for f in langtexts['eng']:
# print(len(textverses['eng'][f]))
for line in tqdm(corpus_slice[langs[0]]):
versesets = {line['file']:line['verses']}
if any([verse2split.get(z) for z in line['verses']]):
for verse in line['verses']:
if verse2split.get(verse):
prevsplit = verse2split.get(verse)
break
split = prevsplit
else:
split = np.random.choice(['train','test','dev'],p=[.9,.05,.05])
if not all([verse2split.get(z) for z in line['verses']]):
all_verses = set()
for v in line['verses']:
all_verses.add(v)
while True:
verses_added = False
idxes = {k:set() for k in langs}
#get indexes for verses
for v in all_verses:
for lang in langs:
if vindexes[lang].get(v):
for idx in vindexes[lang][v]:
idxes[lang].add(idx)
for lang in langs:
for compline in [corpus_slice[lang][x] for x in idxes[lang] if x != set()]:
if all(x in textverses[lang][compline['file']] for x in all_verses) and any([x in list(all_verses) for x in compline['verses']]):
if not versesets.get(compline['file']):
versesets[compline['file']] = compline['verses'].copy()
else:
versesets[compline['file']].extend(compline['verses'].copy())
for v in compline['verses']:
pre_size = len(all_verses)
all_verses.add(v)
if len(all_verses) > pre_size:
verses_added = True
if verses_added == False or all([set(versesets[q]) == all_verses for q in versesets.keys()]):
vgroups.append(all_verses)
for v in all_verses:
verse2split[v] = split
break
return(vgroups,vindexes, verse2split)
corpus_slice = parse_json(downloaded_files['corpus'], self.config.languages)
vgroups, vindexes, verse2split = define_splits(corpus_slice, self.config.languages)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
'langs': self.config.languages,
'corpus': corpus_slice,
'vgroups': vgroups,
'vindexes': vindexes,
'v2split': verse2split,
'split': 'train',
'vref': downloaded_files['vref'],
}
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
'langs': self.config.languages,
'corpus': corpus_slice,
'vgroups': vgroups,
'vindexes': vindexes,
'v2split': verse2split,
'split': 'dev',
'vref': downloaded_files['vref'],
}
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
'langs': self.config.languages,
'corpus': corpus_slice,
'vgroups': vgroups,
'vindexes': vindexes,
'v2split': verse2split,
'split': 'test',
'vref': downloaded_files['vref'],
}
),
]
def _generate_examples(self, vref, corpus, vgroups, vindexes, v2split, split, langs):
#print(f'Generating {split} examples...')
with open(vref, 'r') as txtfile:
#print('file opened')
lines = txtfile.readlines()
#print('lines read')
verse2index = {k.strip():v for v,k in enumerate(lines) if k.strip() != ''}
#print('v2i created')
def order_verses(verse_list):
lines_list = [int(verse2index[x]) for x in verse_list]
verse_order = np.argsort(lines_list)
return(verse_order)
trans_license = {}
trans_copyright = {}
id = -1
#print(f'beginning groups, starting with {list(vgroups)[0]}')
for group in vgroups:
#print(group)
if v2split.get(list(group)[0]) == split:
#print('correct split')
if len(group) > 1:
v_order = order_verses(group)
o_group = list(np.array(list(group))[v_order])
else:
o_group = list(group)
trans_dict={k:{} for k in langs}
trans_texts = {k:{} for k in langs}
used_idxes = {k:[] for k in langs}
for v in o_group:
#print(f'trying verse {v}')
single_texts = {k:{} for k in langs}
single_dict = {k:{} for k in langs}
for lang in langs:
if vindexes[lang].get(v):
try:
for i in range(0,len(list(vindexes[lang][v]))):
if list(vindexes[lang][v])[i] not in used_idxes[lang]:
used_idxes[lang].append(vindexes[lang][v])
line = corpus[lang][vindexes[lang][v][i]]
if not trans_texts.get(line['file']):
trans_texts[lang][line['file']]=line['text']
else:
trans_texts[lang][line['file']] += f' {line["text"]}'
if line.get('license'):
trans_license[line['file']]=line['license']
if line.get('copyright'):
trans_copyright[line['file']]=line['copyright']
if len(line['verses']) == 1:
single_texts[lang][line['file']] = line['text']
except:
print(lang,v)
raise
single_dict[lang]=list(single_texts[lang].values())
trans_dict[lang]=list(trans_texts[lang].values())
single_file = {x:list(single_texts[x].keys()) for x in langs}
sing_v_order = {x:np.argsort(list(single_texts[x].values())) for x in langs}
lang_order = np.argsort(langs)
single_lic_list =[]
single_copy_list = []
for lang in [langs[x] for x in lang_order]:
single_lic_list.extend([trans_license.get(single_file[lang][x],'') for x in sing_v_order[lang]])
single_copy_list.extend([trans_copyright.get(single_file[lang][x],'') for x in sing_v_order[lang]])
if all([single_dict.get(x) and single_dict.get(x) != [{}] and list(single_dict.get(x)) for x in langs]) and len(list(single_dict.keys())) == len(langs) and self.config.pair != 'range':
id = id + 1
sfile_list = []
for key in [langs[x] for x in lang_order]:
for value in [single_file.get(key)[x] for x in sing_v_order.get(key)]:
sfile_list.append({'lang':key,'file':value})
#print('outputting single example')
# print(id, single_dict, sfile_list, v, single_lic_list, single_copy_list)
try:
yield(id, {'translation': single_dict, 'files': sfile_list, 'ref':[v], 'licenses':single_lic_list, 'copyrights':single_copy_list})
except:
print(id, single_dict, sfile_list, v, single_lic_list, single_copy_list)
raise
file_list = {x:list(trans_texts[x].keys()) for x in langs}
trans_v_order = {x:np.argsort(list(trans_texts[x].values())) for x in langs}
lang_order = np.argsort(langs)
#license_list = [trans_license.get(x,'') for x in [y for y in file_list.values()]]
#copyright_list = [trans_copyright.get(x,'') for x in [y for y in file_list.values()]]
license_list = []
copyright_list = []
for lang in [langs[x] for x in lang_order]:
license_list.extend([trans_license.get(file_list[lang][x],'') for x in trans_v_order[lang]])
copyright_list .extend([trans_copyright.get(file_list[lang][x],'') for x in trans_v_order[lang]])
if len(o_group)>1 and all([trans_dict.get(x) and trans_dict.get(x) != [{}] and list(trans_dict.get(x)) for x in langs]) and len(list(trans_dict.keys())) == len(langs) and self.config.pair != 'single':
id = id + 1
ofile_list = []
for key in [langs[x] for x in lang_order]:
for value in [file_list.get(key)[x] for x in trans_v_order.get(key)]:
ofile_list.append({'lang':key,'file':value})
#print('outputting range example')
try:
yield(id, {'translation': trans_dict, 'files': ofile_list, 'ref':o_group, 'licenses':license_list, 'copyrights':copyright_list})
except:
print(id, trans_dict, ofile_list, o_group, license_list, copyright_list)
raise