AstheralDataset / build_dataset.py
SEE7's picture
Publish 5000 real globally deduplicated translation pairs with provenance and checksums
bc24c8c verified
Raw History Blame Contribute Delete
6.24 kB
import json,hashlib,re,unicodedata,collections,time
from pathlib import Path
from datasets import load_dataset,Dataset
from huggingface_hub import HfApi
api=HfApi();source='Helsinki-NLP/opus-100';revision=api.dataset_info(source).sha
out=Path('/tmp/AstheralDataset');(out/'data').mkdir(parents=True,exist_ok=True)
langs={'de':'German','fr':'French','es':'Spanish','it':'Italian','pt':'Portuguese'}
seen_values=set();ids=set();splits={'train':[],'validation':[],'test':[]};rejected=collections.Counter()
def normalize(s):
s=unicodedata.normalize('NFKC',s).casefold()
return ' '.join(''.join(c if c.isalnum() else ' ' for c in s).split())
for split,n in [('test',50),('validation',50),('train',900)]:
for lang,name in langs.items():
config='-'.join(sorted(['en',lang]));ds=load_dataset(source,config,split=split,revision=revision).shuffle(seed=20261113)
added=0
for index,row in enumerate(ds):
a=row['translation']['en'].strip();b=row['translation'][lang].strip()
if not(20<=len(a)<=500 and 12<=len(b)<=600) or len(a.split())<4 or len(b.split())<3:
rejected['length']+=1;continue
if any(re.search(r'lorem ipsum|placeholder|\bTODO\b|https?://|<[^>]+>|\{\{|\ufffd',s,re.I) for s in [a,b]):
rejected['non_sentence_content']+=1;continue
x,y=normalize(a),normalize(b)
if x==y or x in seen_values or y in seen_values:
rejected['duplicate_or_identical_text']+=1;continue
uid=hashlib.sha256((lang+'\\0'+x+'\\0'+y).encode()).hexdigest()
assert uid not in ids
ids.add(uid);seen_values.update([x,y])
record={'id':uid,'source_language':'en','target_language':lang,'source_text':a,'target_text':b,'instruction':'Translate from English to '+name+'. Return only the translation.','source_dataset':source,'source_config':config,'source_split':split,'source_revision':revision,'source_row_index':int(ds._indices.column(0)[index].as_py()) if ds._indices is not None else index}
splits[split].append(record);added+=1
if added==n:break
assert added==n,(lang,split,added)
print('COLLECTED',split,lang,added,flush=True)
for split,rows in splits.items():
Dataset.from_list(rows).shuffle(seed=42).to_parquet(str(out/'data'/f'{split}.parquet'))
total=sum(map(len,splits.values()));assert total==5000 and len(ids)==5000 and len(seen_values)==10000
counter={split:dict(collections.Counter(r['target_language'] for r in rows)) for split,rows in splits.items()}
manifest={'name':'AstheralDataset','version':'1.0','total_examples':total,'unique_example_ids':len(ids),'unique_normalized_text_values':len(seen_values),'split_counts':{k:len(v) for k,v in splits.items()},'language_counts':counter,'source_dataset':source,'source_revision':revision,'normalization':'Unicode NFKC, casefold, punctuation removed, whitespace collapsed','deduplication':'Global source/target text uniqueness across all languages and splits; identical source-target pairs excluded','rejected':dict(rejected),'file_sha256':{p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in (out/'data').glob('*.parquet')}}
(out/'manifest.json').write_text(json.dumps(manifest,indent=2))
(out/'build_dataset.py').write_text(Path(__file__).read_text())
readme='''---
pretty_name: AstheralDataset
language:
- en
- de
- fr
- es
- it
- pt
task_categories:
- translation
size_categories:
- 1K<n<10K
license: other
license_name: source-corpus-terms
license_link: https://huggingface.co/datasets/Helsinki-NLP/opus-100
configs:
- config_name: default
data_files:
- split: train
path: data/train.parquet
- split: validation
path: data/validation.parquet
- split: test
path: data/test.parquet
---
# AstheralDataset
**5,000 real English translation pairs**, curated by SEE7 for German, French, Spanish, Italian and Portuguese.
## Contents
| Target | Train | Validation | Test | Total |
| --- | ---: | ---: | ---: | ---: |
| German | 900 | 50 | 50 | 1,000 |
| French | 900 | 50 | 50 | 1,000 |
| Spanish | 900 | 50 | 50 | 1,000 |
| Italian | 900 | 50 | 50 | 1,000 |
| Portuguese | 900 | 50 | 50 | 1,000 |
| **Total** | **4,500** | **250** | **250** | **5,000** |
## Record fields
Each row contains a unique SHA-256 ID, English source text, translated target text, source and target language codes, a translation instruction, and the original dataset/config/split/revision/row index.
## Curation
Text is drawn from real parallel sentences in [OPUS-100](https://huggingface.co/datasets/Helsinki-NLP/opus-100). Selection preserves the original train, validation and test split membership. All 10,000 text values are globally unique after Unicode normalization, case folding, punctuation removal and whitespace normalization. Source-target identity, short fragments, markup and placeholder patterns are filtered. No model-generated translations are included.
The complete build script, exact source revision, split counts, rejection counts and Parquet checksums are published alongside the data.
## Load
```python
from datasets import load_dataset
dataset = load_dataset("SEE7/AstheralDataset")
example = dataset["train"][0]
print(example["source_text"])
print(example["target_text"])
```
## Provenance and attribution
Source: Helsinki-NLP/opus-100, revision '''+revision+'''.
OPUS-100: Zhang et al. (2020), “Improving Massively Multilingual Neural Machine Translation and Zero-Shot Translation.” Original parallel text comes from the OPUS collection. The original source corpus terms remain applicable.
Curated dataset repository: SEE7/AstheralDataset.
'''
(out/'README.md').write_text(readme)
api.upload_folder(repo_id='SEE7/AstheralDataset',repo_type='dataset',folder_path=str(out),commit_message='Publish 5000 real globally deduplicated translation pairs with provenance and checksums')
# Download the published splits through the public dataset interface and validate the real release.
published=load_dataset('SEE7/AstheralDataset')
assert {k:len(v) for k,v in published.items()}=={'train':4500,'validation':250,'test':250}
values=[];row_ids=[]
for split in published:
for row in published[split]:
values.extend([normalize(row['source_text']),normalize(row['target_text'])]);row_ids.append(row['id'])
assert len(set(values))==10000 and len(set(row_ids))==5000
print('PUBLISHED_VERIFIED',json.dumps(manifest),flush=True)