Download runtime/datasets/readout_week.py from hscr/luxfer: direct link, hf CLI and curl.
- Browser
- Download file 8.41 kB
-
https://huggingface.co/hscr/luxfer/resolve/main/runtime/datasets/readout_week.py
- Command line
-
hf download hf://hscr/luxfer/runtime/datasets/readout_week.py
-
curl -L -o readout_week.py https://huggingface.co/hscr/luxfer/resolve/main/runtime/datasets/readout_week.py
8.41 kB
| """Build a checksummed, indexed English–Portuguese corpus from pinned OPUS archives.""" | |
| import argparse | |
| from collections import Counter | |
| from html import unescape | |
| import io | |
| import json | |
| from pathlib import Path | |
| import random | |
| import re | |
| import sqlite3 | |
| import struct | |
| import unicodedata | |
| import zipfile | |
| from inference.run import import_local | |
| from language_adapters.native_portuguese import PortuguesePromptTokenizer | |
| from training.train import encode | |
| from weights.identity import file_sha256 | |
| SOURCES = ( | |
| ('Tatoeba', 'v2026-07-08', 100_000, 'CC BY 2.0 FR', 'https://tatoeba.org/'), | |
| ('GlobalVoices', 'v2018q4', 25_000, 'Global Voices publisher attribution policy', | |
| 'https://globalvoices.org/about/global-voices-attribution-policy/'), | |
| ('Europarl', 'v8', 95_000, 'Europarl corpus terms of use', | |
| 'https://www.statmt.org/europarl/'), | |
| ) | |
| TATOEBA_SHA256 = '90b673f477dc654e5d31824478b8a3af8f2f67fc7638fe130413dcb2bf7bf09b' | |
| LANGUAGES = ('en', 'pt') | |
| DIGITS = re.compile(r'\d+') | |
| MARKUP = re.compile(r'<[^>]+>|(?:https?://|www\.)\S+') | |
| ENCODE_LIMIT = 128 | |
| def normalize(text): | |
| value = unicodedata.normalize('NFKC', text).casefold() | |
| return ' '.join(''.join(char if char.isalnum() else ' ' for char in value).split()) | |
| def cleanup(text): | |
| return ' '.join(unicodedata.normalize('NFC', unescape(text)).split()) | |
| def acceptable(en, pt): | |
| for value in (en, pt): | |
| if not 8 <= len(value) <= 410 or not 3 <= len(value.split()) <= 62 or MARKUP.search(value): | |
| return False | |
| if any(ord(char) < 32 or char == '\ufffd' for char in value): | |
| return False | |
| return (min(len(en), len(pt)) * 2.4 >= max(len(en), len(pt)) | |
| and Counter(DIGITS.findall(en)) == Counter(DIGITS.findall(pt))) | |
| def input_reservoir(archive, name, maximum, seed): | |
| rng = random.Random(seed) | |
| chosen = [] | |
| candidates = raw = 0 | |
| with zipfile.ZipFile(archive) as zipped: | |
| members = {lang: next(item for item in zipped.namelist() if item.endswith(f'.en-pt.{lang}')) | |
| for lang in LANGUAGES} | |
| with (io.TextIOWrapper(zipped.open(members['en']), encoding='utf-8') as english, | |
| io.TextIOWrapper(zipped.open(members['pt']), encoding='utf-8') as portuguese): | |
| for raw, (en, pt) in enumerate(zip(english, portuguese, strict=True), 1): | |
| en, pt = cleanup(en), cleanup(pt) | |
| if not acceptable(en, pt): | |
| continue | |
| candidates += 1 | |
| value = (raw, en, pt) | |
| if len(chosen) < maximum: | |
| chosen.append(value) | |
| else: | |
| index = rng.randrange(candidates) | |
| if index < maximum: | |
| chosen[index] = value | |
| rng.shuffle(chosen) | |
| return chosen, {'raw_pairs': raw, 'length_and_digit_filter_passed': candidates, 'corpus': name} | |
| def blocked_texts(focus, evaluation): | |
| blocked = {lang: set() for lang in LANGUAGES} | |
| def absorb(row): | |
| for role, keys in (('source', ('source',)), ('target', ('reference', 'target'))): | |
| lang = row.get(f'{role}_lang') | |
| text = next((row[key] for key in keys if row.get(key)), None) | |
| if lang in blocked and text: | |
| blocked[lang].add(normalize(text)) | |
| for split in ('train', 'validation', 'test'): | |
| with (focus / f'{split}.jsonl').open() as stream: | |
| for line in stream: | |
| row = json.loads(line) | |
| if split != 'train' or {row.get('source_lang'), row.get('target_lang')} == set(LANGUAGES): | |
| absorb(row) | |
| for row in json.loads(evaluation.read_text()): | |
| absorb(row) | |
| return blocked | |
| def pack_encoding(encoded): | |
| ids, labels = encoded | |
| tokens = ids[0].tolist() | |
| prefix = next(i for i, label in enumerate(labels[0].tolist()) if label != -100) | |
| return struct.pack(f'<H{len(tokens)}I', prefix, *tokens) | |
| def encode_pair(tokenizer, en, pt): | |
| forward = encode(tokenizer, dict(source=en, target=pt, source_lang='en', target_lang='pt'), ENCODE_LIMIT) | |
| if forward is None: | |
| return None | |
| reverse = encode(tokenizer, dict(source=pt, target=en, source_lang='pt', target_lang='en'), ENCODE_LIMIT) | |
| if reverse is None: | |
| return None | |
| return pack_encoding(forward), pack_encoding(reverse) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| for path in ('model', 'raw', 'focus', 'evaluation', 'output'): | |
| parser.add_argument(f'--{path}', type=Path, required=True) | |
| args = parser.parse_args() | |
| output = args.output | |
| if output.exists(): | |
| raise FileExistsError(output) | |
| stage = output.with_name(output.name + '.building') | |
| stage.mkdir() | |
| vocab = json.loads((args.model / 'config.json').read_text())['vocab_size'] | |
| base = import_local(args.model / 'tokenization_plamo.py', 'local_tokenization') | |
| tokenizer = PortuguesePromptTokenizer( | |
| base.Plamo3Tokenizer.from_pretrained(str(args.model), local_files_only=True), vocab, | |
| ) | |
| seen = blocked_texts(args.focus, args.evaluation) | |
| validation = [] | |
| total = 0 | |
| info = [] | |
| database = stage / 'pairs.sqlite3' | |
| with sqlite3.connect(database) as db: | |
| db.execute('CREATE TABLE pairs (id INTEGER PRIMARY KEY, example_id TEXT NOT NULL UNIQUE, ' | |
| 'en TEXT NOT NULL, pt TEXT NOT NULL, en_pt BLOB NOT NULL, pt_en BLOB NOT NULL)') | |
| for index, (source, release, quota, terms, url) in enumerate(SOURCES): | |
| archive = args.raw / f'{source}.zip' | |
| digest = file_sha256(archive) | |
| if source == 'Tatoeba' and digest != TATOEBA_SHA256: | |
| raise ValueError('Tatoeba archive differs from the previously pinned release') | |
| candidates, stats = input_reservoir(archive, source, quota * 3, 5892 + index) | |
| accepted = reserved = 0 | |
| for line, en, pt in candidates: | |
| en_key, pt_key = normalize(en), normalize(pt) | |
| if en_key == pt_key or en_key in seen['en'] or pt_key in seen['pt']: | |
| continue | |
| packed = encode_pair(tokenizer, en, pt) | |
| if packed is None: | |
| continue | |
| identifier = f'{source}-{release}-{line}' | |
| seen['en'].add(en_key) | |
| seen['pt'].add(pt_key) | |
| if reserved < 20: | |
| validation.append(dict(id=identifier, corpus=source, en=en, pt=pt)) | |
| reserved += 1 | |
| continue | |
| total += 1 | |
| db.execute('INSERT INTO pairs VALUES (?, ?, ?, ?, ?, ?)', | |
| (total, identifier, en, pt, *packed)) | |
| accepted += 1 | |
| if accepted >= quota: | |
| break | |
| db.commit() | |
| entry = dict(stats, archive_sha256=digest, revision=release, terms=terms, | |
| source_page=url, url=f'https://object.pouta.csc.fi/OPUS-{source}/{release}/moses/en-pt.txt.zip', | |
| train_pairs=accepted, validation_pairs=reserved) | |
| info.append(entry) | |
| print(json.dumps(entry), flush=True) | |
| if total < 150_000 or any(item['validation_pairs'] < 20 for item in info): | |
| raise ValueError(f'Filtered corpus is too small: {total} training pairs') | |
| validation_path = stage / 'validation.json' | |
| validation_path.write_text(json.dumps(validation, ensure_ascii=False, indent=2) + '\n') | |
| manifest = dict(format='luxfer-indexed-bitext-v1', pairs=total, directions=list(LANGUAGES), | |
| max_tokens=ENCODE_LIMIT, train_sha256=file_sha256(database), | |
| validation_sha256=file_sha256(validation_path), sources=info, | |
| tokenizer_sha256=file_sha256(args.model / 'tokenizer.jsonl'), | |
| heldout_panel_sha256=file_sha256(args.evaluation), | |
| prior_splits_sha256={key: file_sha256(args.focus / f'{key}.jsonl') | |
| for key in ('train', 'validation', 'test')}) | |
| (stage / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n') | |
| stage.rename(output) | |
| print(json.dumps({'ready': True, 'pairs': total, 'sqlite_bytes': database.stat().st_size | |
| if database.exists() else (output / database.name).stat().st_size}), flush=True) | |
| if __name__ == '__main__': | |
| main() | |