File size: 11,009 Bytes
98cf86d a16e5a2 98cf86d a16e5a2 98cf86d a16e5a2 98cf86d a16e5a2 98cf86d a16e5a2 98cf86d a16e5a2 98cf86d a16e5a2 98cf86d a16e5a2 98cf86d a16e5a2 98cf86d a16e5a2 98cf86d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 | #!/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"
}
@dataclass
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()
|