Download scripts/build_dataset.py from bjorndev/efik-text-corpus: direct link, hf CLI and curl.
- Browser
- Download file 17.7 kB
-
https://huggingface.co/datasets/bjorndev/efik-text-corpus/resolve/main/scripts/build_dataset.py
- Command line
-
hf download hf://datasets/bjorndev/efik-text-corpus/scripts/build_dataset.py
-
curl -L -o build_dataset.py https://huggingface.co/datasets/bjorndev/efik-text-corpus/resolve/main/scripts/build_dataset.py
17.7 kB
| #!/usr/bin/env python3 | |
| """Extract the supplied local Efik collections without executing archived code. | |
| Run from any directory: python3 scripts/build_dataset.py | |
| Python standard library only; no network access or package installation required. | |
| """ | |
| import ast | |
| import collections | |
| import csv | |
| import hashlib | |
| import html | |
| from html.parser import HTMLParser | |
| import io | |
| import json | |
| from pathlib import Path | |
| import re | |
| import unicodedata | |
| import xml.etree.ElementTree as ET | |
| import zipfile | |
| ROOT = Path(__file__).resolve().parents[1] | |
| OUT = ROOT / 'dataset' | |
| records = {} | |
| inventory = [] | |
| rejected = [] | |
| def clean(s, multiline=True): | |
| s = unicodedata.normalize('NFC', s.replace('\ufeff', '').replace('\r', '')) | |
| if not multiline: | |
| return re.sub(r'\s+', ' ', s).strip() | |
| s = '\n'.join(re.sub(r'[^\S\n]+', ' ', line).strip() for line in s.splitlines()) | |
| return re.sub(r'\n{3,}', '\n\n', s).strip() | |
| def add(text, source, locator, kind, english='', title='', english_title='', notes='', flags=(), raw=None): | |
| text, english = clean(text), clean(english) | |
| if not text: | |
| return | |
| # Exact normalized pairs only: spelling variants remain separate records. | |
| key = (text, english) | |
| origin = {'file': source, 'locator': str(locator), 'type': kind} | |
| if raw is not None: | |
| origin['raw'] = raw | |
| if key in records: | |
| r = records[key] | |
| if origin not in r['sources']: | |
| r['sources'].append(origin) | |
| r['quality_flags'] = sorted(set(r['quality_flags']) | set(flags)) | |
| return | |
| records[key] = { | |
| 'id': 'efi_' + hashlib.sha256((text + '\0' + english).encode()).hexdigest()[:16], | |
| 'efik_text': text, 'english_text': english, | |
| 'translation_status': 'source_provided' if english else 'not_available', | |
| 'type': kind, 'title': clean(title), 'english_title': clean(english_title), | |
| 'notes': notes, 'quality_flags': sorted(set(flags)), 'sources': [origin], | |
| } | |
| class Blocks(HTMLParser): | |
| """Read visible paragraph/heading content; exclude navigation and scripts.""" | |
| def __init__(self, tags=('p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6')): | |
| super().__init__(convert_charrefs=True) | |
| self.tags = tags | |
| self.blocks = [] | |
| self.current = None | |
| self.parts = [] | |
| self.skip = 0 | |
| def flush(self): | |
| if self.current: | |
| text = clean(''.join(self.parts), False) | |
| if text: | |
| self.blocks.append((self.current, text)) | |
| self.current, self.parts = None, [] | |
| def handle_starttag(self, tag, attrs): | |
| if tag in ('script', 'style', 'button', 'a'): | |
| self.skip += 1 | |
| if self.skip: | |
| return | |
| if tag in self.tags: | |
| self.flush() | |
| self.current = tag | |
| elif tag == 'br': | |
| self.parts.append('\n') | |
| def handle_endtag(self, tag): | |
| if tag in ('script', 'style', 'button', 'a'): | |
| self.skip = max(0, self.skip - 1) | |
| if tag in self.tags: | |
| self.flush() | |
| def handle_data(self, data): | |
| if self.current and not self.skip: | |
| self.parts.append(data) | |
| # Safe parser for the literal TypeScript hymn array. Never eval source code. | |
| TOKEN = re.compile(r'\s+|//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'|[A-Za-z_$][\w$]*|-?\d+(?:\.\d+)?|[\[\]{},:]', re.S) | |
| def literal_array(s): | |
| s = s[s.index('= [') + 2:s.rindex(']') + 1] | |
| tokens = [] | |
| pos = 0 | |
| for m in TOKEN.finditer(s): | |
| assert m.start() == pos, f'Unexpected TypeScript at {pos}' | |
| pos = m.end() | |
| t = m.group() | |
| if not t.isspace() and not t.startswith(('//', '/*')): | |
| tokens.append(t) | |
| assert pos == len(s) | |
| i = 0 | |
| def value(): | |
| nonlocal i | |
| t = tokens[i] | |
| i += 1 | |
| if t == '[': | |
| result = [] | |
| while tokens[i] != ']': | |
| result.append(value()) | |
| if tokens[i] == ',': | |
| i += 1 | |
| else: | |
| assert tokens[i] == ']' | |
| i += 1 | |
| return result | |
| if t == '{': | |
| result = {} | |
| while tokens[i] != '}': | |
| k = tokens[i] | |
| i += 1 | |
| if k.startswith(('"', "'")): | |
| k = ast.literal_eval(k) | |
| assert tokens[i] == ':' | |
| i += 1 | |
| result[k] = value() | |
| if tokens[i] == ',': | |
| i += 1 | |
| else: | |
| assert tokens[i] == '}' | |
| i += 1 | |
| return result | |
| if t.startswith(('"', "'")): | |
| return ast.literal_eval(t) | |
| if re.fullmatch(r'-?\d+', t): | |
| return int(t) | |
| raise ValueError(f'Unsupported literal {t}') | |
| result = value() | |
| assert i == len(tokens) | |
| return result | |
| STRING = r'"(?:\\.|[^"\\])*"|\x27(?:\\.|[^\x27\\])*\x27' | |
| def strings(s): | |
| return ''.join(ast.literal_eval(m.group()) for m in re.finditer(STRING, s)) | |
| def dictionary(s, source): | |
| for line, cells in enumerate(csv.reader(io.StringIO(s)), 1): | |
| if line == 1: | |
| continue | |
| raw = dict(zip(('English', 'Efik', 'Usage Examples'), cells)) | |
| a, b, c = (cells + ['', '', ''])[:3] | |
| flags = [] | |
| strip_missing = lambda x: re.sub(r'\b(?:None|nan)\b', '', x).strip() | |
| a, b, c = map(strip_missing, (a, b, c)) | |
| if any(re.search(r'\b(?:None|nan)\b', x) for x in cells): | |
| flags.append('source_missing_value_artifacts') | |
| if "Dictionaryof Efik" in a: | |
| rejected.append({'file': source, 'row': line, 'reason': 'dictionary page header', 'raw': raw}) | |
| continue | |
| # In these damaged rows the headword and Efik term share column 1. | |
| if b in ('n', 'vt', 'vi', 'adj', 'adv', 't') or re.match(r'^(?:vt|vi|adj|adv|n)\s', b): | |
| if ' ' not in a: | |
| add(a, source, f'csv row {line}', 'dictionary', notes='English headword missing in source; not inferred.', flags=['source_ocr_noise', 'missing_english_headword'], raw=raw) | |
| continue | |
| a, term = a.split(' ', 1) | |
| c = ' '.join(x for x in [b, c] if x) | |
| b = term | |
| flags.append('recovered_shifted_columns') | |
| # Two badly split headwords are retained verbatim for review. | |
| if a == 'abandonmen': | |
| flags.append('truncated_english_headword') | |
| # Remove an unambiguous part-of-speech marker misplaced in the term. | |
| m = re.search(r'\s+(n|vt|vi|adj|adv)$', b) | |
| if m: | |
| c = m.group(1) + ' ' + c | |
| b = b[:m.start()] | |
| flags.append('recovered_shifted_columns') | |
| add(b, source, f'csv row {line}', 'dictionary', a, notes=c, | |
| flags=['source_ocr_noise', *flags], raw=raw) | |
| # One row embeds a second entry with its own repeated headword. | |
| if a == 'abjuretion' and 'abjuretion ' in c: | |
| term = c.split('abjuretion ', 1)[1] | |
| term = re.sub(r'\s+n$', '', term) | |
| add(term, source, f'csv row {line}: embedded entry', 'dictionary', a, | |
| flags=['source_ocr_noise', 'recovered_shifted_columns'], raw=raw) | |
| # Extract only simple explicit example alignments; ambiguous colon chains | |
| # remain verbatim in notes rather than becoming misleading parallel data. | |
| ex = re.sub(r'^(?:(?:vt|vi|adv|adj|n|det)(?:\s*&\s*(?:i|adj))?\s+)', '', c) | |
| ex = re.sub(r'^\([^)]*\)\s*', '', ex) | |
| if a == 'a' and 'A plate:' in ex: | |
| for en, ef in [('A plate', 'usan kiet'), ('A person', 'owo kiet')]: | |
| add(ef, source, f'csv row {line}: {en}', 'dictionary_example', en, | |
| flags=['source_ocr_noise', 'example_alignment_needs_review'], raw=raw) | |
| if ex.count(':') == 1: | |
| en, ef = map(str.strip, ex.split(':', 1)) | |
| if en and ef: | |
| add(ef, source, f'csv row {line}: usage example', 'dictionary_example', en, | |
| flags=['source_ocr_noise', 'example_alignment_needs_review'], raw=raw) | |
| def extract(source, data): | |
| name = source.split('::')[-1] | |
| suffix = Path(name).suffix.lower() | |
| if suffix not in ('.txt', '.csv', '.java', '.xml', '.tsx', '.ts', '.dart', '.html', '.vue'): | |
| return 'non-content asset or project metadata' | |
| s = data.decode('utf-8-sig').replace('\r\n', '\n').replace('\r', '\n') | |
| if name in ('1.txt', 'Latest Cleaned Efik Text part 111.txt'): | |
| if name == '1.txt': | |
| add(s, source, 'whole file', 'hymn') | |
| else: | |
| for m in re.finditer(r'\S[\s\S]*?(?=\n\s*\n|\Z)', s): | |
| start = s.count('\n', 0, m.start()) + 1 | |
| end = start + m.group().count('\n') | |
| add(clean(m.group(), False), source, f'lines {start}-{end}', 'prose', | |
| flags=['source_ocr_noise'], raw=m.group()) | |
| return 'extracted local text' | |
| if name.endswith('efik2English_dictionary_cards.csv'): | |
| dictionary(s, source) | |
| return 'extracted dictionary and explicit examples; damaged rows flagged' | |
| if name.endswith('NumbersActivity.java') or name.endswith('PhrasesActivity.java'): | |
| for i, m in enumerate(re.finditer(r'new Word\(\s*("(?:\\.|[^"\\])*")\s*,\s*("(?:\\.|[^"\\])*")\s*\)', s), 1): | |
| en, ef = ast.literal_eval(m[1]).strip(), ast.literal_eval(m[2]).strip() | |
| flags, notes = [], '' | |
| raw = {'English': en, 'Efik': ef} | |
| if ef.startswith('see '): | |
| en, ef = en + ' see', ef[4:] | |
| flags.append('recovered_shifted_columns') | |
| if "I'm from" in ef: | |
| notes = 'Source labels this as the response to Oto mmoñ.' | |
| en, ef = "I'm from ...", ef.split("I'm from ...", 1)[1].strip() | |
| flags.append('recovered_shifted_columns') | |
| if '(' in ef: | |
| notes += ' Source greeting/reply labels: ' + ef | |
| ef = re.sub(r'\([^)]*\)', '', ef).strip() | |
| flags.append('english_annotations_moved_to_notes') | |
| add(ef, source, f'word {i}', 'vocabulary' if 'Numbers' in name else 'phrase', en, notes=notes, flags=flags, raw=raw) | |
| return 'extracted explicitly paired vocabulary' | |
| if name.endswith('EfikHymnBook-master/app/src/main/res/values/strings.xml'): | |
| root = ET.fromstring(s) | |
| titles = {el.attrib['name'][6:]: ''.join(el.itertext()) for el in root if el.attrib.get('name', '').startswith('button')} | |
| for el in root: | |
| k = el.attrib.get('name', '') | |
| if k.startswith('hymn') or k.startswith('button'): | |
| t = ''.join(el.itertext()).replace('\\n', '\n').replace('\\t', '\t').replace("\\'", "'").replace('\\"', '"') | |
| if k.startswith('hymn'): | |
| # Resource files contain both real line breaks and escaped breaks. | |
| t = re.sub(r'\n[ \t]*\n', '\n', t) | |
| t = re.sub(r'^\s*\d+[aAbB]?\s*\n', '', t) | |
| add(t, source, f'string @{k}', 'hymn' if k.startswith('hymn') else 'hymn_title', title=titles.get(k[4:], '')) | |
| return 'extracted hymn lyrics and title resources' | |
| if re.search(r'/src/hymns/\d+\w*\.tsx$', name): | |
| p = Blocks(); p.feed(s); p.flush() | |
| add('\n'.join(t for _, t in p.blocks), source, f'hymn {Path(name).stem}', 'hymn') | |
| return 'extracted JSX hymn paragraphs and stanza markers' | |
| if name.endswith('/src/data/hymns.ts'): | |
| for hymn in literal_array(s): | |
| verses = ['\n'.join([str(v['number']), *v['lines']]) for v in hymn['verses']] | |
| if hymn.get('chorus'): | |
| verses.append('\n'.join(['Chorus', *hymn['chorus']])) | |
| add('\n\n'.join(verses), source, f"hymn id {hymn['id']}", 'hymn', title=hymn['title'], | |
| english_title=hymn.get('alternateTitle', ''), flags=['unverified_app_content'], | |
| notes='English alternateTitle is source metadata, not a full lyric translation. App content has not been linguistically verified.') | |
| add(hymn['title'], source, f"hymn id {hymn['id']}: title", 'hymn_title', | |
| english_title=hymn.get('alternateTitle', ''), flags=['unverified_app_content']) | |
| return 'extracted literal hymn array, choruses and title metadata' | |
| if re.search(r'/lib/hymns/h\w+\.dart$', name): | |
| # Strip commented-out lines, then concatenate Dart's adjacent literals. | |
| active = re.sub(r'^\s*//.*$', '', s, flags=re.M) | |
| chunks = [strings(m[1]) for m in re.finditer(r'Text\(\s*((?:(?:' + STRING + r')\s*)+),', active)] | |
| assert len(chunks) >= 6, name | |
| for i, t in enumerate(chunks): | |
| if len(t) > 180: | |
| add(t, source, f'Text widget {i + 1}: lyrics', 'hymn') | |
| elif i == 3: | |
| add(t, source, f'Text widget {i + 1}: epigraph', 'scripture_excerpt', flags=['mixed_language_reference']) | |
| return 'extracted Dart lyrics and Efik scripture epigraphs' | |
| if suffix == '.dart' and '/lib/screens/' in name: | |
| # Index pages include Efik hymn incipits, including incomplete commented | |
| # index lists. Preserve those separately and flag their context. | |
| found = 0 | |
| for m in re.finditer(r'(?:text\s*:\s*|^\s*//\s*)("(?:\\.|[^"\\])*")', s, re.M): | |
| t = ast.literal_eval(m[1]) | |
| if re.search(r'\(\d+\)', t): | |
| add(t, source, f'line {s.count(chr(10), 0, m.start()) + 1}: index title', 'hymn_title', flags=['index_or_commented_source']) | |
| found += 1 | |
| return 'extracted hymn index titles' if found else 'application code; no additional corpus text' | |
| if suffix == '.html' and ('station-of-the-cross' in source or 'efik-man-master' in source): | |
| p = Blocks(); p.feed(s); p.flush() | |
| for i, (tag, t) in enumerate(p.blocks, 1): | |
| if t.startswith('Gospel '): | |
| continue | |
| flags = ['mixed_language_reference'] if ('[' in t or 'Oh lord' in t) else [] | |
| add(t, source, f'{tag} block {i}', 'prayer_heading' if tag.startswith('h') else 'prayer', flags=flags) | |
| return 'extracted prayer text and Efik headings; navigation omitted' | |
| if 'nwed-nyin-web-master' in source and suffix in ('.vue', '.ts'): | |
| found = 0 | |
| for m in re.finditer(r'Ñwed Nn(?:yịn|yìn)|Ñwed Nyịn|ufọk', s): | |
| add(m.group(), source, f'line {s.count(chr(10), 0, m.start()) + 1}', 'ui_text', flags=['ui_or_test_fixture']) | |
| found += 1 | |
| return 'extracted Efik site names/test fixture; dictionary content fetched remotely, absent locally' if found else 'application code; no local corpus data' | |
| return 'application code or project metadata; no additional corpus text' | |
| def write_jsonl(path, rows): | |
| with path.open('w', encoding='utf-8') as f: | |
| for row in rows: | |
| f.write(json.dumps(row, ensure_ascii=False) + '\n') | |
| def main(): | |
| OUT.mkdir(exist_ok=True) | |
| sources = [] | |
| for p in sorted(ROOT.iterdir()): | |
| if p.suffix == '.zip': | |
| with zipfile.ZipFile(p) as z: | |
| for n in sorted(z.namelist()): | |
| if not n.endswith('/'): | |
| sources.append((p.name + '::' + n, z.read(n))) | |
| elif p.suffix == '.txt': | |
| sources.append((p.name, p.read_bytes())) | |
| elif p.is_dir() and p.name.endswith('.zip_1'): | |
| for f in sorted(p.rglob('*')): | |
| if f.is_file(): | |
| sources.append((str(f.relative_to(ROOT)), f.read_bytes())) | |
| for source, data in sources: | |
| status = extract(source, data) | |
| inventory.append({'file': source, 'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest(), 'status': status}) | |
| rows = sorted(records.values(), key=lambda r: (r['sources'][0]['file'], r['sources'][0]['locator'])) | |
| paired = [r for r in rows if r['english_text']] | |
| write_jsonl(OUT / 'efik_dataset.jsonl', rows) | |
| write_jsonl(OUT / 'efik_english_pairs.jsonl', paired) | |
| write_jsonl(OUT / 'source_inventory.jsonl', inventory) | |
| write_jsonl(OUT / 'excluded_dictionary_rows.jsonl', rejected) | |
| fields = ['id', 'efik_text', 'english_text', 'translation_status', 'type', 'title', 'english_title', 'notes', 'quality_flags', 'sources'] | |
| for filename, subset in [('efik_dataset.csv', rows), ('efik_english_pairs.csv', paired)]: | |
| with (OUT / filename).open('w', encoding='utf-8-sig', newline='') as f: | |
| w = csv.DictWriter(f, fieldnames=fields) | |
| w.writeheader() | |
| for r in subset: | |
| w.writerow({**r, 'quality_flags': json.dumps(r['quality_flags'], ensure_ascii=False), 'sources': json.dumps(r['sources'], ensure_ascii=False)}) | |
| stats = { | |
| 'records': len(rows), 'records_with_english': len(paired), | |
| 'records_without_english': len(rows) - len(paired), | |
| 'records_with_english_title_metadata': sum(bool(r['english_title']) for r in rows), | |
| 'by_type': dict(collections.Counter(r['type'] for r in rows)), | |
| 'source_files_scanned_including_archive_members': len(inventory), | |
| 'source_files_with_extracted_text': len({s['file'] for r in rows for s in r['sources']}), | |
| 'source_occurrences': sum(len(r['sources']) for r in rows), | |
| 'excluded_dictionary_rows': len(rejected), | |
| 'efik_word_count_approximate': sum(len(r['efik_text'].split()) for r in rows), | |
| 'quality_flags': dict(collections.Counter(f for r in rows for f in r['quality_flags'])), | |
| } | |
| (OUT / 'summary.json').write_text(json.dumps(stats, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') | |
| print(json.dumps(stats, indent=2)) | |
| if __name__ == '__main__': | |
| main() | |