File size: 21,884 Bytes
4c8394a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 |
# 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 |