"""Pure-text pseudo-gloss extraction columns for the multilingual SLT dataset. No tokenizer involved: everything stays at the plain-text / word level, so the output is model-agnostic and can be tokenized later by any LLM's tokenizer. The POS filtering rules follow VTaMo (arXiv:2607.09126) and are expressed in universal UPOS tags. Backends (pluggable per language): - zh -> HanLP 2.x CTB9 tokenizer + CTB9 POS tagger, with a CTB -> UPOS mapping. Far better than jieba on domain terms (weather). Install: ``pip install hanlp[pt]`` (or ``hanlp`` + tensorflow); the model downloads itself on first use. - en / de -> spaCy (rule-based tokenization is already good for Latin scripts; separate ``en_spacy_model`` / ``de_spacy_model`` overrides can select larger models). Install: ``python -m spacy download en_core_web_sm`` etc. Column naming: columns are prefixed ``pseudo_gloss_*`` on purpose -- these are POS-filtered content-word sequences, NOT the sign-language gloss annotations shipped with SLT datasets (PHOENIX-2014T gloss etc.), so the prefix avoids any name collision. One function, one row:: from extract_gloss_columns import extract_gloss_columns row = extract_gloss_columns("雷暴和阵雨出现在午后。", lang="zh") returns a dict with: text raw sentence (stripped) lang language code used backend_model analyzer that produced the tokens (reproducibility) tokens full non-space token list (the raw material, surface form -- never lemmatized) token_offsets [start, end) char offsets, aligned with tokens content_mask 1/0 per token: kept by the default rule? pseudo_gloss_default VTaMo default: NOUN/VERB/ADJ/ADV/NUM/PRON/PROPN, lemmatized + lowercased (tense/plural stripped for en/de; zh has no lemmatizer, so it falls back to the lowercased surface form) pseudo_gloss_strict default minus PRON, lemmatized + lowercased pseudo_gloss_relaxed default plus AUX, lemmatized + lowercased pseudo_gloss_offsets [start, end) char offsets, aligned with the pseudo_gloss_default tokens All three pseudo_gloss_* variants are normalized the same way (lemma + lowercase), so they are consistently "clean" gloss (base word forms, no tense/number inflection, no case variation) and differ only in which POS tags they keep. The pseudo-gloss variants are space-joined plain text. For Chinese this inserts spaces between words; the char offsets remain exact and can be used to recover the unspaced form whenever needed. Usage from the build script (``build_ph14t_multilang_with_spacy.py``), one call on the whole assembled polars frame:: # in the build script, ensure this module is importable, e.g. # sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from extract_gloss_columns import add_gloss_columns df = add_gloss_columns(df, text_col="translation", lang_col="lang") df.write_parquet("ph14t_multilingual_train_with_pseudo_gloss.parquet") # If `df` also has a `translation_original` column (the German # translation kept aside by build_ph14t_multilang_with_spacy.py), it is # parsed too -- always as lang="de" -- and its 4 pseudo-gloss columns are # added with an `orig_` prefix (orig_pseudo_gloss_default, _strict, # _relaxed, _offsets). CLI demo:: python extract_gloss_columns.py "Der Mann gibt der Frau das Buch." --lang de """ import argparse import functools import time from typing import Dict, List, Optional, Sequence, Tuple # --------------------------------------------------------------------------- # POS rules (universal UPOS tags, VTaMo paper Sec. 3.1) # --------------------------------------------------------------------------- POS_DEFAULT = frozenset({"NOUN", "VERB", "ADJ", "ADV", "NUM", "PRON", "PROPN"}) POS_STRICT = POS_DEFAULT - {"PRON"} POS_RELAXED = POS_DEFAULT | {"AUX"} # --------------------------------------------------------------------------- # Backend: spaCy pipelines (en / de), loaded lazily and cached # --------------------------------------------------------------------------- _SPACY_MODELS = { "de": "de_core_news_md", "en": "en_core_web_sm", } @functools.lru_cache(maxsize=None) def _load_spacy(lang: str, model: Optional[str] = None): """Load (and cache) the spaCy pipeline for a Latin-script language.""" if lang not in _SPACY_MODELS: raise ValueError(f"unsupported language {lang!r}; supported: {sorted(_SPACY_MODELS)}") model_name = model or _SPACY_MODELS[lang] import spacy try: return spacy.load(model_name) except OSError as exc: # model not installed -> actionable message raise OSError( f"spaCy model {model_name!r} not found. Install it with:\n" f" python -m spacy download {model_name}" ) from exc # --------------------------------------------------------------------------- # Backend: HanLP 2.x tokenizer + POS tagger (zh), both trained on CTB9 # --------------------------------------------------------------------------- # CTB -> UPOS mapping (Universal Dependencies Chinese conventions). # Only tags that map into the filter sets actually matter, but the full # mapping is kept so any future rule can rely on it. _CTB_TO_UPOS = { # content words "NR": "PROPN", # 专有名词 "NN": "NOUN", # 普通名词 "NT": "NOUN", # 时间名词 (UD zh: NOUN) "M": "NOUN", # 量词 (UD zh: NOUN) "ON": "NOUN", # 拟声词 (UD zh: NOUN) "VV": "VERB", # 动词 "VC": "AUX", # 系动词"是" (UD Chinese: copular auxiliary) "VE": "VERB", # 动词"有" (存在/拥有) "VA": "ADJ", # 谓词性形容词 "JJ": "ADJ", # 定语形容词 "AD": "ADV", # 副词 "CD": "NUM", # 数词 "OD": "NUM", # 序数词 "PN": "PRON", # 代词 # function words / others "P": "ADP", # 介词 "LC": "ADP", # 方位词 (UD zh: ADP) "LB": "ADP", # 长"被"(被/给,被动标记) "CC": "CCONJ", # 并列连词 "CS": "SCONJ", # 从属连词 (虽然/因为...) "DT": "DET", # 限定词 "DEC": "PART", # 的 (补语/名词化) "DEG": "PART", # 的 (定语) "DER": "PART", # 得 "DEV": "PART", # 地 "AS": "PART", # 了/着/过 "MSP": "PART", # 其他结构助词 "SP": "PART", # 句末语气词 "ETC": "PART", # 等 "SB": "PART", # 短"被" "BA": "PART", # 把 "IJ": "INTJ", # 感叹词 "PU": "PUNCT", # 标点 "FW": "X", # 外语词 "X": "X", # 其他 "URL": "X", # 链接 } _HANLP_DEFAULT_TOKENIZER_MODEL = "CTB9_TOK_ELECTRA_SMALL" _HANLP_DEFAULT_POS_MODEL = "CTB9_POS_ELECTRA_SMALL" def _ensure_hanlp_transformers_compat() -> None: """Restore tokenizer convenience methods removed by Transformers 5. HanLP 2.1.3 still calls ``encode_plus`` and ``batch_encode_plus``. Their behavior is covered by the tokenizer's callable API in Transformers 5, so install forwarding methods only when the installed version lacks them. """ from transformers import PreTrainedTokenizerBase if not hasattr(PreTrainedTokenizerBase, "encode_plus"): def encode_plus(self, text, text_pair=None, **kwargs): return self(text=text, text_pair=text_pair, **kwargs) PreTrainedTokenizerBase.encode_plus = encode_plus if not hasattr(PreTrainedTokenizerBase, "batch_encode_plus"): def batch_encode_plus(self, batch_text_or_text_pairs, **kwargs): return self(text=batch_text_or_text_pairs, **kwargs) PreTrainedTokenizerBase.batch_encode_plus = batch_encode_plus @functools.lru_cache(maxsize=None) def _load_hanlp_tokenizer(model: str = _HANLP_DEFAULT_TOKENIZER_MODEL): """Load and cache a HanLP 2.x tokenizer. Official pretrained constant names are accepted for convenience; URLs and local model paths are passed directly to ``hanlp.load``. """ import hanlp try: _ensure_hanlp_transformers_compat() model_id = getattr(hanlp.pretrained.tok, model, model) return hanlp.load(model_id) except Exception as exc: raise RuntimeError( f"HanLP tokenizer {model!r} failed to load. Install HanLP 2.x with " f"`pip install hanlp[pt]` (or `hanlp` + tensorflow); the model " f"downloads itself on first use." ) from exc @functools.lru_cache(maxsize=None) def _load_hanlp_pos(model: str = _HANLP_DEFAULT_POS_MODEL): """Load and cache a HanLP 2.x POS tagger.""" import hanlp try: _ensure_hanlp_transformers_compat() model_id = getattr(hanlp.pretrained.pos, model, model) return hanlp.load(model_id) except Exception as exc: raise RuntimeError( f"HanLP POS tagger {model!r} failed to load. Install HanLP 2.x with " f"`pip install hanlp[pt]` (or `hanlp` + tensorflow); the model " f"downloads itself on first use." ) from exc # --------------------------------------------------------------------------- # Backend-agnostic analysis: return [(token, upos, start, end, lemma), ...] # --------------------------------------------------------------------------- def _analyze(sentence: str, lang: str, en_spacy_model: Optional[str], de_spacy_model: Optional[str], hanlp_tokenizer_model: str, hanlp_pos_model: str) -> List[Tuple[str, str, int, int, Optional[str]]]: """Tokenize + POS-tag one sentence, returning UPOS-labeled spans. Returns a list of ``(token_text, upos, start, end, lemma)`` tuples covering the non-space tokens of ``sentence`` in order; ``start``/``end`` are exact character offsets into the original string. ``lemma`` is ``None`` for the HanLP zh backend (the CTB9 POS model has no lemmatizer). """ text = sentence.strip() if not text: return [] if lang == "zh": # HanLP's standalone POS models consume an already-tokenized sentence. tokens = _load_hanlp_tokenizer(hanlp_tokenizer_model)(text) ctb_tags = _load_hanlp_pos(hanlp_pos_model)(tokens) if tokens else [] if len(tokens) != len(ctb_tags): raise RuntimeError( "HanLP tokenizer/POS output length mismatch: " f"{len(tokens)} tokens vs {len(ctb_tags)} tags" ) # Recover exact char offsets by scanning the original string with a # cursor (Chinese is unsegmented; HanLP preserves the surface forms). spans: List[Tuple[str, str, int, int, Optional[str]]] = [] cursor = 0 for word, ctb in zip(tokens, ctb_tags): start = text.find(word, cursor) if start == -1: # defensive: should never happen start = cursor end = start + len(word) cursor = end spans.append((word, _CTB_TO_UPOS.get(ctb, "X"), start, end, None)) return spans # ---- spaCy (en / de): rule-based tokenization + UPOS + lemma ---- spacy_model = en_spacy_model if lang == "en" else de_spacy_model nlp = _load_spacy(lang, spacy_model) doc = nlp(text) return [ (t.text, t.pos_, t.idx, t.idx + len(t.text), t.lemma_) for t in doc if not t.is_space ] # --------------------------------------------------------------------------- # Main function # --------------------------------------------------------------------------- def extract_gloss_columns( sentence: str, lang: str = "en", en_spacy_model: Optional[str] = None, de_spacy_model: Optional[str] = None, hanlp_tokenizer_model: str = _HANLP_DEFAULT_TOKENIZER_MODEL, hanlp_pos_model: str = _HANLP_DEFAULT_POS_MODEL, ) -> Dict: """Extract all pseudo-gloss text columns from one raw sentence. Args: sentence: Original sentence (plain text). Whitespace is stripped. lang: Language code, one of ``de`` / ``zh`` / ``en``. ``zh`` uses the HanLP 2.x backend, ``de``/``en`` use spaCy. en_spacy_model: Optional spaCy model override for English only. de_spacy_model: Optional spaCy model override for German only. hanlp_tokenizer_model: HanLP tokenizer name, URL or local path. hanlp_pos_model: HanLP POS tagger name, URL or local path. Returns: Dict with the keys documented in the module docstring. For an empty sentence every list/string column comes back empty (never None). """ spans = _analyze( sentence, lang, en_spacy_model, de_spacy_model, hanlp_tokenizer_model, hanlp_pos_model ) tokens = [s[0] for s in spans] upos = [s[1] for s in spans] lemmas = [s[4] for s in spans] offsets = [(s[2], s[3]) for s in spans] is_content = [p in POS_DEFAULT for p in upos] content_mask = [1 if c else 0 for c in is_content] def gloss(keep: Sequence[bool]) -> str: # Always lemmatized (tense/plural stripped) and lowercased for a # consistently "clean" gloss. zh (HanLP CTB9 POS) has no lemmatizer # -> falls back to the lowercased surface form. return " ".join( (lm if lm is not None else t).lower() for t, lm, k in zip(tokens, lemmas, keep) if k ) pseudo_gloss_offsets = [o for o, k in zip(offsets, is_content) if k] backend_model = ( f"tok={hanlp_tokenizer_model};pos={hanlp_pos_model}" if lang == "zh" else _load_spacy( lang, en_spacy_model if lang == "en" else de_spacy_model ).meta.get( "name", _SPACY_MODELS.get(lang, "") ) ) return { "text": sentence.strip(), "lang": lang, "backend_model": backend_model, "tokens": tokens, "token_offsets": offsets, "content_mask": content_mask, "pseudo_gloss_default": gloss(is_content), "pseudo_gloss_strict": gloss([p in POS_STRICT for p in upos]), "pseudo_gloss_relaxed": gloss([p in POS_RELAXED for p in upos]), "pseudo_gloss_offsets": pseudo_gloss_offsets, } # --------------------------------------------------------------------------- # Multiprocessing worker helpers (module-level so they pickle cleanly under # macOS/Linux "spawn" semantics) # --------------------------------------------------------------------------- def _extract_row_payload(payload: Tuple) -> Dict: """Extract one row from the serializable worker payload.""" (text, lang, en_spacy_model, de_spacy_model, hanlp_tokenizer_model, hanlp_pos_model) = payload return extract_gloss_columns( "" if text is None else text, lang="en" if lang is None else lang, en_spacy_model=en_spacy_model, de_spacy_model=de_spacy_model, hanlp_tokenizer_model=hanlp_tokenizer_model, hanlp_pos_model=hanlp_pos_model, ) def _init_worker_process() -> None: """Per-worker init: keep CPU pools from oversubscribing torch threads.""" try: import torch torch.set_num_threads(1) except Exception: # pragma: no cover - torch not installed pass # --------------------------------------------------------------------------- # Batch helper for the build script (polars frame in -> frame + gloss columns) # --------------------------------------------------------------------------- def add_gloss_columns( df, text_col: str = "translation", lang_col: str = "lang", en_spacy_model: Optional[str] = None, de_spacy_model: Optional[str] = None, hanlp_tokenizer_model: str = _HANLP_DEFAULT_TOKENIZER_MODEL, hanlp_pos_model: str = _HANLP_DEFAULT_POS_MODEL, workers: Optional[int] = None, ): """Append the pseudo-gloss columns to a polars frame, one row per sentence. Designed to be called from ``build_ph14t_multilang_with_spacy.py`` on the assembled table (one row per ``(name, lang)`` pair). Every new column is appended alongside the original ones, ready for ``write_parquet``. All existing columns, including the build script's split-specific ``id``, are preserved unchanged. Args: df: polars DataFrame with ``text_col`` / ``lang_col`` columns. text_col: Name of the column holding the raw sentence (``translation`` in the current build script). lang_col: Name of the column holding the language code (``de`` / ``zh`` / ``en``, as produced by ``build_assemble_df``). en_spacy_model: Optional spaCy model override for English rows only. de_spacy_model: Optional spaCy model override for German rows only. hanlp_tokenizer_model: HanLP tokenizer override for zh rows. hanlp_pos_model: HanLP POS tagger override for zh rows. workers: Number of worker processes for the per-row extraction. ``None``/``0`` -> auto (``min(cpu_count, 4)``); ``1`` -> run serially in-process (no pickling; use this in notebooks/REPL, where "spawn" multiprocessing cannot re-import the caller); ``>1`` -> ``ProcessPoolExecutor``. Multiprocessing is used because tokenization + POS tagging is CPU-bound (threads would be GIL-limited). Each worker lazily loads its own spaCy/HanLP models (memory cost ~ one extra model set per worker; prefer the ``hanlp[pt]`` backend, which is more multiprocessing-friendly than the tensorflow one). Returns: A new polars DataFrame = ``df`` plus the columns of ``extract_gloss_columns`` (tokens, token_offsets, content_mask, pseudo_gloss_default, pseudo_gloss_strict, pseudo_gloss_relaxed, pseudo_gloss_offsets, backend_model, lang). The three pseudo_gloss_* columns are lemmatized (tense/plural stripped for en/de). ``text`` is omitted to avoid duplicating ``text_col``; the original columns (including ``id``, when present) are untouched. If ``df`` also has a ``translation_original`` column (the German translation preserved by ``build_assemble_df`` before the join), it is parsed too -- always as ``lang="de"`` -- and its 4 pseudo-gloss columns are added with an ``orig_`` prefix: ``orig_pseudo_gloss_default``, ``orig_pseudo_gloss_strict``, ``orig_pseudo_gloss_relaxed``, ``orig_pseudo_gloss_offsets``. Notes: - ``polars`` is imported lazily so the pure-text function keeps zero heavy dependencies. - ``None`` translations are treated as empty sentences (empty pseudo-gloss columns), never as a crash. """ import os import polars as pl text_series = df[text_col] lang_series = df[lang_col] n_rows = len(text_series) orig_col = "translation_original" has_orig = orig_col in df.columns # tqdm is optional: progress bar + timing when installed, silent otherwise. try: from tqdm import tqdm except ImportError: # pragma: no cover tqdm = None # workers: None/0 -> auto; 1 -> serial; >1 -> process pool. if workers is None or workers <= 0: workers = min(os.cpu_count() or 1, 4) payloads = [ ("" if t is None else t, "en" if l is None else l, en_spacy_model, de_spacy_model, hanlp_tokenizer_model, hanlp_pos_model) for t, l in zip(text_series.to_list(), lang_series.to_list()) ] # translation_original is always German -- append its payloads after the # main ones so both can share a single pool / progress bar, then split # the results back apart below. if has_orig: payloads += [ ("" if t is None else t, "de", en_spacy_model, de_spacy_model, hanlp_tokenizer_model, hanlp_pos_model) for t in df[orig_col].to_list() ] n_payloads = len(payloads) start = time.perf_counter() if workers > 1: from concurrent.futures import ProcessPoolExecutor with ProcessPoolExecutor( max_workers=workers, initializer=_init_worker_process ) as executor: iterator = executor.map( _extract_row_payload, payloads, chunksize=16 ) if tqdm is not None: iterator = tqdm( iterator, total=n_payloads, desc="pseudo-gloss", unit="row", ncols=100, ) records = list(iterator) else: iterator = payloads if tqdm is not None: iterator = tqdm( iterator, total=n_payloads, desc="pseudo-gloss", unit="row", ncols=100, ) records = [_extract_row_payload(p) for p in iterator] elapsed = time.perf_counter() - start if tqdm is not None: print(f"Extracted {n_payloads} rows in {elapsed:.1f}s " f"({elapsed / max(n_payloads, 1):.3f} s/row, " f"workers={workers})") # First n_rows records are text_col/lang_col; if present, the trailing # n_rows records are translation_original (always parsed as German). main_records = records[:n_rows] orig_records = records[n_rows:n_rows * 2] if has_orig else [] # Expand the per-row dicts into one column per key (skip 'text' -- it # duplicates text_col; keep 'lang'/'backend_model' for provenance). new_columns = [] for key in ("lang", "backend_model", "tokens", "token_offsets", "content_mask", "pseudo_gloss_default", "pseudo_gloss_strict", "pseudo_gloss_relaxed", "pseudo_gloss_offsets"): values = [rec[key] for rec in main_records] new_columns.append(pl.Series(name=key, values=values)) if has_orig: for key in ("pseudo_gloss_default", "pseudo_gloss_strict", "pseudo_gloss_relaxed", "pseudo_gloss_offsets"): values = [rec[key] for rec in orig_records] new_columns.append(pl.Series(name=f"orig_{key}", values=values)) return df.with_columns(new_columns) # --------------------------------------------------------------------------- # CLI demo (mirrors the repo's argparse style) # --------------------------------------------------------------------------- def main() -> None: parser = argparse.ArgumentParser( description="Extract pseudo-gloss text columns from one sentence." ) parser.add_argument("sentence", help="Original sentence to process") parser.add_argument( "--lang", default="en", choices=("de", "zh", "en"), help="Language code (zh -> HanLP 2.x, de/en -> spaCy)", ) parser.add_argument( "--en-spacy-model", default=None, help="spaCy model override for English (default: en_core_web_sm)", ) parser.add_argument( "--de-spacy-model", default=None, help="spaCy model override for German (default: de_core_news_md)", ) parser.add_argument( "--hanlp-tokenizer-model", default=_HANLP_DEFAULT_TOKENIZER_MODEL, help=f"HanLP tokenizer for zh (default: " f"{_HANLP_DEFAULT_TOKENIZER_MODEL})", ) parser.add_argument( "--hanlp-pos-model", default=_HANLP_DEFAULT_POS_MODEL, help=f"HanLP POS tagger for zh (default: {_HANLP_DEFAULT_POS_MODEL})", ) args = parser.parse_args() row = extract_gloss_columns( args.sentence, lang=args.lang, en_spacy_model=args.en_spacy_model, de_spacy_model=args.de_spacy_model, hanlp_tokenizer_model=args.hanlp_tokenizer_model, hanlp_pos_model=args.hanlp_pos_model, ) for key, value in row.items(): print(f"{key}: {value}") if __name__ == "__main__": main()