Download pipeline01_text2gloss.py from SignerX/StableSigner: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/datasets/SignerX/StableSigner/resolve/main/pipeline01_text2gloss.py
- Command line
-
hf download hf://datasets/SignerX/StableSigner/pipeline01_text2gloss.py
-
curl -L -o pipeline01_text2gloss.py https://huggingface.co/datasets/SignerX/StableSigner/resolve/main/pipeline01_text2gloss.py
11 kB
| #!/usr/bin/env python3 | |
| """Constrained English text -> available gloss translation for StableSigner. | |
| This is the browser-panel fallback path: it only emits gloss tokens that exist | |
| in the local pose dictionary, so gloss2pose can render the result immediately. | |
| It is intentionally conservative and can later be replaced by a trained | |
| text-to-gloss model with the same public functions. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import re | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple | |
| BASE_DIR = Path(__file__).resolve().parent | |
| DEFAULT_POSE_DICT = BASE_DIR / "pose_dict" / "WLASL_train.json" | |
| STOP_WORDS = { | |
| "A", | |
| "AN", | |
| "THE", | |
| "AM", | |
| "ARE", | |
| "IS", | |
| "WAS", | |
| "WERE", | |
| "BE", | |
| "BEEN", | |
| "BEING", | |
| "DO", | |
| "DOES", | |
| "DID", | |
| "TO", | |
| "OF", | |
| "FOR", | |
| "WITH", | |
| "AND", | |
| "OR", | |
| "BUT", | |
| "THAT", | |
| "THIS", | |
| "THESE", | |
| "THOSE", | |
| "IT", | |
| "ITS", | |
| "JUST", | |
| "VERY", | |
| "REALLY", | |
| } | |
| LEMMA_OVERRIDES = { | |
| "ME": "I", | |
| "MINE": "MY", | |
| "MYSELF": "I", | |
| "YOURSELF": "YOU", | |
| "YOUR": "YOU", | |
| "YOURS": "YOU", | |
| "HIS": "HE", | |
| "HIM": "HE", | |
| "HER": "SHE", | |
| "HERS": "SHE", | |
| "THEIR": "THEY", | |
| "THEM": "THEY", | |
| "OUR": "WE", | |
| "US": "WE", | |
| "WENT": "GO", | |
| "GONE": "GO", | |
| "GOING": "GO", | |
| "CAME": "COME", | |
| "COMING": "COME", | |
| "MADE": "MAKE", | |
| "MAKING": "MAKE", | |
| "SAID": "SAY", | |
| "SAYING": "SAY", | |
| "SAW": "SEE", | |
| "SEEN": "SEE", | |
| "SEEING": "SEE", | |
| "LOOKING": "LOOK", | |
| "LIKED": "LIKE", | |
| "LIKES": "LIKE", | |
| "WANTED": "WANT", | |
| "WANTS": "WANT", | |
| "NEEDED": "NEED", | |
| "NEEDS": "NEED", | |
| "HELPED": "HELP", | |
| "HELPS": "HELP", | |
| "LEARNED": "LEARN", | |
| "LEARNING": "LEARN", | |
| "SIGNED": "SIGN", | |
| "SIGNING": "SIGN", | |
| "THANKS": "THANK", | |
| } | |
| PHRASE_MAP = { | |
| "GOOD MORNING": ["GOOD", "MORNING"], | |
| "GOOD AFTERNOON": ["GOOD", "AFTERNOON"], | |
| "GOOD NIGHT": ["GOOD", "NIGHT"], | |
| "THANK YOU": ["THANK", "YOU"], | |
| "SIGN LANGUAGE": ["SIGN", "LANGUAGE"], | |
| } | |
| SEMANTIC_PHRASE_MAP = { | |
| "HELP ME": ["HELP", "I"], | |
| "NEED HELP": ["NEED", "HELP"], | |
| "I NEED HELP": ["I", "NEED", "HELP"], | |
| "PLEASE HELP": ["PLEASE", "HELP"], | |
| "GO TO SCHOOL": ["GO", "SCHOOL"], | |
| "GO HOME": ["GO", "HOME"], | |
| "COME HERE": ["COME", "HERE"], | |
| "SEE YOU": ["SEE", "YOU"], | |
| "NICE TO MEET YOU": ["NICE", "MEET", "YOU"], | |
| "HOW ARE YOU": ["HOW", "YOU"], | |
| } | |
| SEMANTIC_TOKEN_MAP = { | |
| "ASSIST": "HELP", | |
| "AID": "HELP", | |
| "SUPPORT": "HELP", | |
| "SUPPORTING": "HELP", | |
| "REQUIRE": "NEED", | |
| "REQUIRES": "NEED", | |
| "REQUIRED": "NEED", | |
| "MUST": "NEED", | |
| "SHOULD": "NEED", | |
| "PURCHASE": "BUY", | |
| "PURCHASED": "BUY", | |
| "PURCHASING": "BUY", | |
| "GET": "BUY", | |
| "BOUGHT": "BUY", | |
| "OBTAIN": "BUY", | |
| "SPEAK": "TALK", | |
| "SPEAKING": "TALK", | |
| "TELL": "SAY", | |
| "TOLD": "SAY", | |
| "VIEW": "SEE", | |
| "WATCH": "SEE", | |
| "OBSERVE": "SEE", | |
| "UNDERSTOOD": "UNDERSTAND", | |
| "UNDERSTANDING": "UNDERSTAND", | |
| "CHILDREN": "CHILD", | |
| "KIDS": "CHILD", | |
| "KID": "CHILD", | |
| "ADULTS": "ADULT", | |
| "PEOPLE": "PERSON", | |
| "HUMAN": "PERSON", | |
| "PERSONS": "PERSON", | |
| "PHYSICIAN": "DOCTOR", | |
| "MEDICAL": "DOCTOR", | |
| "HOSPITAL": "DOCTOR", | |
| "INSTRUCTOR": "TEACHER", | |
| "EDUCATOR": "TEACHER", | |
| "PUPIL": "STUDENT", | |
| "LEARNER": "STUDENT", | |
| "AUTOMOBILE": "CAR", | |
| "VEHICLE": "CAR", | |
| "CELL": "PHONE", | |
| "MOBILE": "PHONE", | |
| "TELEPHONE": "PHONE", | |
| "RESIDENCE": "HOME", | |
| "HOUSE": "HOME", | |
| "WEATHER": "WEATHER", | |
| "RAINING": "RAIN", | |
| "SUNNY": "SUN", | |
| "COLD": "COLD", | |
| "HOT": "HOT", | |
| "BEAUTIFUL": "NICE", | |
| "GREAT": "GOOD", | |
| "EXCELLENT": "GOOD", | |
| "FINE": "GOOD", | |
| "HAPPY": "HAPPY", | |
| "SAD": "SAD", | |
| "AFRAID": "FEAR", | |
| "SCARED": "FEAR", | |
| "SOON": "LATER", | |
| "AFTER": "LATER", | |
| "CURRENTLY": "NOW", | |
| "IMMEDIATELY": "NOW", | |
| "YESTERDAY": "YESTERDAY", | |
| "TOMORROW": "TOMORROW", | |
| } | |
| AMBIGUOUS_SEMANTIC_BLOCKLIST = { | |
| "CAN", "MAY", "MIGHT", "LEFT", "RIGHT", "LIGHT", "WELL", "KIND", "MEAN", "PART", "SECOND" | |
| } | |
| class TextToGlossResult: | |
| gloss: str | |
| tokens: List[str] | |
| matched: List[Tuple[str, str]] | |
| dropped: List[str] | |
| semantic: List[Tuple[str, str]] | |
| def load_available_glosses(path: Path | str = DEFAULT_POSE_DICT) -> Set[str]: | |
| """Load uppercase gloss vocabulary from WLASL-style pose dictionary JSON.""" | |
| pose_path = Path(path) | |
| with pose_path.open("r", encoding="utf-8") as handle: | |
| data = json.load(handle) | |
| glosses = set() | |
| for item in data: | |
| gloss = str(item.get("gloss", "")).strip().upper() | |
| if gloss: | |
| glosses.add(gloss) | |
| return glosses | |
| def tokenize_english(text: str) -> List[str]: | |
| text = text.replace("'", "") | |
| return [token.upper() for token in re.findall(r"[A-Za-z0-9]+", text)] | |
| def _simple_lemma(token: str) -> List[str]: | |
| candidates = [token] | |
| if token in LEMMA_OVERRIDES: | |
| candidates.append(LEMMA_OVERRIDES[token]) | |
| if len(token) > 4 and token.endswith("IES"): | |
| candidates.append(token[:-3] + "Y") | |
| if len(token) > 4 and token.endswith("ING"): | |
| candidates.append(token[:-3]) | |
| if len(token) > 5: | |
| candidates.append(token[:-4]) | |
| if len(token) > 3 and token.endswith("ED"): | |
| candidates.append(token[:-2]) | |
| candidates.append(token[:-1]) | |
| if len(token) > 3 and token.endswith("ES"): | |
| candidates.append(token[:-2]) | |
| if len(token) > 2 and token.endswith("S"): | |
| candidates.append(token[:-1]) | |
| deduped = [] | |
| seen = set() | |
| for candidate in candidates: | |
| if candidate and candidate not in seen: | |
| deduped.append(candidate) | |
| seen.add(candidate) | |
| return deduped | |
| def _best_vocab_match(token: str, vocab: Set[str]) -> Optional[str]: | |
| for candidate in _simple_lemma(token): | |
| if candidate in vocab: | |
| return candidate | |
| return None | |
| def _best_semantic_match(token: str, vocab: Set[str]) -> Optional[str]: | |
| if token in AMBIGUOUS_SEMANTIC_BLOCKLIST: | |
| return None | |
| candidates = _simple_lemma(token) | |
| for candidate in candidates: | |
| mapped = SEMANTIC_TOKEN_MAP.get(candidate) | |
| if mapped and mapped in vocab: | |
| return mapped | |
| return None | |
| def _apply_semantic_phrase_map(tokens: Sequence[str], vocab: Set[str]) -> Tuple[List[str], List[Tuple[str, str]]]: | |
| output: List[str] = [] | |
| matched: List[Tuple[str, str]] = [] | |
| i = 0 | |
| phrases = sorted(SEMANTIC_PHRASE_MAP.items(), key=lambda item: len(item[0].split()), reverse=True) | |
| while i < len(tokens): | |
| consumed = False | |
| for phrase, gloss_tokens in phrases: | |
| phrase_tokens = phrase.split() | |
| if list(tokens[i : i + len(phrase_tokens)]) != phrase_tokens: | |
| continue | |
| available = [gloss for gloss in gloss_tokens if gloss in vocab] | |
| if available: | |
| output.extend(available) | |
| matched.append((phrase, " ".join(available))) | |
| i += len(phrase_tokens) | |
| consumed = True | |
| break | |
| if not consumed: | |
| output.append(tokens[i]) | |
| i += 1 | |
| return output, matched | |
| def _apply_phrase_map(tokens: Sequence[str], vocab: Set[str]) -> Tuple[List[str], List[Tuple[str, str]]]: | |
| output: List[str] = [] | |
| matched: List[Tuple[str, str]] = [] | |
| i = 0 | |
| while i < len(tokens): | |
| consumed = False | |
| for phrase, gloss_tokens in PHRASE_MAP.items(): | |
| phrase_tokens = phrase.split() | |
| if list(tokens[i : i + len(phrase_tokens)]) != phrase_tokens: | |
| continue | |
| available = [gloss for gloss in gloss_tokens if gloss in vocab] | |
| if available: | |
| output.extend(available) | |
| matched.append((phrase, " ".join(available))) | |
| i += len(phrase_tokens) | |
| consumed = True | |
| break | |
| if not consumed: | |
| output.append(tokens[i]) | |
| i += 1 | |
| return output, matched | |
| def translate_text_to_gloss( | |
| text: str, | |
| vocab: Optional[Iterable[str]] = None, | |
| max_tokens: int = 64, | |
| use_semantic: bool = False, | |
| ) -> TextToGlossResult: | |
| """Translate English text into a renderable uppercase gloss sequence.""" | |
| vocab_set = {item.upper() for item in vocab} if vocab is not None else load_available_glosses() | |
| raw_tokens = tokenize_english(text) | |
| phrase_tokens, phrase_matches = _apply_phrase_map(raw_tokens, vocab_set) | |
| semantic_matches: List[Tuple[str, str]] = [] | |
| if use_semantic: | |
| phrase_tokens, semantic_phrase_matches = _apply_semantic_phrase_map(phrase_tokens, vocab_set) | |
| semantic_matches.extend(semantic_phrase_matches) | |
| gloss_tokens: List[str] = [] | |
| matched: List[Tuple[str, str]] = list(phrase_matches) | |
| dropped: List[str] = [] | |
| for token in phrase_tokens: | |
| if len(gloss_tokens) >= max_tokens: | |
| break | |
| if token in STOP_WORDS: | |
| dropped.append(token) | |
| continue | |
| gloss = _best_vocab_match(token, vocab_set) | |
| if not gloss and use_semantic: | |
| gloss = _best_semantic_match(token, vocab_set) | |
| if gloss: | |
| semantic_matches.append((token, gloss)) | |
| if gloss: | |
| gloss_tokens.append(gloss) | |
| if token != gloss: | |
| matched.append((token, gloss)) | |
| else: | |
| dropped.append(token) | |
| return TextToGlossResult( | |
| gloss=" ".join(gloss_tokens), | |
| tokens=gloss_tokens, | |
| matched=matched, | |
| dropped=dropped, | |
| semantic=semantic_matches, | |
| ) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description="Constrained English text to StableSigner gloss.") | |
| parser.add_argument("text", help="English text to translate.") | |
| parser.add_argument("--pose-dict", default=str(DEFAULT_POSE_DICT), help="WLASL-style pose dictionary JSON.") | |
| parser.add_argument("--max-tokens", type=int, default=64) | |
| parser.add_argument("--semantic", action="store_true", help="Enable conservative semantic synonym fallback.") | |
| parser.add_argument("--json", action="store_true", help="Print structured JSON instead of only gloss.") | |
| args = parser.parse_args() | |
| vocab = load_available_glosses(args.pose_dict) | |
| result = translate_text_to_gloss(args.text, vocab=vocab, max_tokens=args.max_tokens, use_semantic=args.semantic) | |
| if args.json: | |
| print( | |
| json.dumps( | |
| { | |
| "gloss": result.gloss, | |
| "tokens": result.tokens, | |
| "matched": result.matched, | |
| "dropped": result.dropped, | |
| "semantic": result.semantic, | |
| }, | |
| ensure_ascii=True, | |
| indent=2, | |
| ) | |
| ) | |
| else: | |
| print(result.gloss) | |
| if __name__ == "__main__": | |
| main() | |