luxfer / runtime /datasets /focus_corpus.py
mdxss's picture
Publish Luxfer early beta with runnable weights and language metadata
7b6f2cc verified
Raw History Blame Contribute Delete
6.07 kB
"""Pinned, token-bounded OPUS/Tatoeba corpus for the five priority languages."""
import argparse,hashlib,io,json,re,shutil,zipfile
from pathlib import Path
from datasets.prepare import normalized
from training.streaming.data import read_partitions,coverage,PRIMARY,direction
from training.train import encode
from inference.run import import_local
ROOT=Path(__file__).resolve().parents[1]
RELEASE='v2026-07-08'
ARCHIVES={
'fr':('datasets/raw/focus/en-fr.zip','en-fr','fr','aa84650ff529e8debe094596eba6437af28d087605a5aa97c2e2a5c33bf18698'),
'pt':('datasets/raw/portuguese/tatoeba-en-pt.zip','en-pt','pt','90b673f477dc654e5d31824478b8a3af8f2f67fc7638fe130413dcb2bf7bf09b'),
'ar':('datasets/raw/focus/ar-en.zip','ar-en','ar','f0fbb5f4c7991ddec7e92209550e4d987b7ea1471e97d446720a2d3b3dc1ad07'),
'fa':('datasets/raw/focus/en-pes.zip','en-pes','pes','a69f6c3fba454b21ff05e904754dd51c47bbde6856cf34b4eb34637d83852853')}
def digest(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def build(output,pairs_per_language=12000):
output=Path(output)
if output.exists():raise ValueError('Refusing to replace an existing dataset')
stage=output.with_name(output.name+'.preparing');stage.mkdir(parents=True,exist_ok=False)
blocked=set()
exclusions=[*(ROOT/'evaluation').glob('*.jsonl'),*(ROOT/'datasets/portuguese_pilot').glob('*.jsonl')]
for name in ['curriculum-v3','curriculum-overnight','curriculum-corpus']:
for split in ['validation','test']:exclusions.append(ROOT/'experiments/portuguese'/name/(split+'.jsonl'))
for p in exclusions:
if not p.exists():continue
for line in p.read_text().splitlines():
row=json.loads(line)
for key in ['source','target','reference']:
if isinstance(row.get(key),str):blocked.add(normalized(row[key]))
tokenizer=import_local(ROOT.parent/'tokenization_plamo.py','focus_data_tokenizer').Plamo3Tokenizer.from_pretrained(str(ROOT.parent),local_files_only=True)
pairs=[];sources={}
for lang,(relative,pair,external,expected) in ARCHIVES.items():
archive=ROOT/relative
if digest(archive)!=expected:raise ValueError('Archive checksum mismatch: '+relative)
seen_en=set();seen_other=set();candidates=[]
with zipfile.ZipFile(archive) as z:
for name in ['README','LICENSE']:(stage/(lang+'_'+name)).write_bytes(z.read(name))
english=io.TextIOWrapper(z.open('Tatoeba.'+pair+'.en'),encoding='utf-8')
other=io.TextIOWrapper(z.open('Tatoeba.'+pair+'.'+external),encoding='utf-8')
from itertools import zip_longest
for i,(en,text) in enumerate(zip_longest(english,other)):
if en is None or text is None:raise ValueError('Unaligned archive')
en,text=en.strip(),text.strip();a,b=normalized(en),normalized(text)
if a in seen_en or b in seen_other or a in blocked or b in blocked or a==b:continue
if not 3<=len(en.split())<=18 or not 2<=len(text.split())<=24 or max(len(en),len(text))>150:continue
if not .3<=len(text)/len(en)<=3.2 or any(t in en+text for t in ['<|','>>','\x00','http://','https://']):continue
if sorted(re.findall(r'\d+',en))!=sorted(re.findall(r'\d+',text)):continue
seen_en.add(a);seen_other.add(b)
candidates.append((hashlib.sha256((lang+str(i)).encode()).digest(),i+1,en,text))
count=0
for _,line,en,text in sorted(candidates):
rows=[dict(source=en,target=text,source_lang='en',target_lang=lang),dict(source=text,target=en,source_lang=lang,target_lang='en')]
if any(encode(tokenizer,r,128) is None for r in rows):continue
pairs.append((lang,line,en,text));count+=1
if count>=pairs_per_language:break
sources[lang]=dict(url=f'https://object.pouta.csc.fi/OPUS-Tatoeba/{RELEASE}/moses/{pair}.txt.zip',sha256=expected,filtered_pairs=len(candidates),selected_pairs=count,upstream_language_code=external)
print(json.dumps(dict(language=lang,**sources[lang])),flush=True)
# Connect both sides, across languages as well: no sentence can cross partitions.
parent={}
def find(x):
parent.setdefault(x,x)
if parent[x]!=x:parent[x]=find(parent[x])
return parent[x]
def key(text):return hashlib.sha256(normalized(text).encode()).hexdigest()
for _,_,en,text in pairs:
a,b=find(key(en)),find(key(text))
if a!=b:parent[max(a,b)]=min(a,b)
parts={s:[] for s in ['train','validation','test']}
for lang,line,en,text in pairs:
bucket=int(find(key(en))[:8],16)%100;split='test' if bucket<5 else 'validation' if bucket<10 else 'train'
for sl,tl,source,target in [('en',lang,en,text),(lang,'en',text,en)]:
parts[split].append(dict(id=f'tatoeba-{lang}-{line}-{sl}-{tl}',document_id=f'tatoeba-{lang}-{line}',source=source,target=target,reference=target,source_lang=sl,target_lang=tl,license='CC BY 2.0 FR; see '+lang+'_LICENSE',provenance='Tatoeba contributors via OPUS',revision=RELEASE,source_url=sources[lang]['url'],corpus_line=line,attribution='Tatoeba contributors; OPUS, J. Tiedemann (2012); upstream notices retained',human_reviewed=False,usage='evaluation_only' if split=='test' else split))
for split,rows in parts.items():
(stage/(split+'.jsonl')).write_text(''.join(json.dumps(r,ensure_ascii=False)+'\n' for r in rows))
checked=read_partitions(stage);scope=coverage(checked,PRIMARY)
counts={s:{p:sum(direction(r)==p for r in rows) for p in scope['directions'][s]} for s,rows in parts.items()}
manifest=dict(format='luxfer-focus-corpus-v1',sources=sources,max_encoded_length=128,tokenizer_sha256=digest(ROOT.parent/'tokenizer.jsonl'),counts=counts,sha256={s:digest(stage/(s+'.jsonl')) for s in parts},split_method='Connected normalized sentences, deterministic hash 90/5/5; both directions grouped',quality='Filtered external parallel translations; not individually reviewed; mixed Portuguese varieties; near duplicates may remain')
(stage/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n');stage.rename(output);return manifest
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--output',type=Path,default=ROOT/'datasets/processed/focus');p.add_argument('--pairs-per-language',type=int,default=12000);a=p.parse_args();print(json.dumps(build(a.output,a.pairs_per_language),indent=2))