stevhliu HF Staff commited on
Commit
470d44a
·
verified ·
1 Parent(s): 7c939e1

Protect HTML literal contents during translation retries

Browse files

Treat HTML code-like elements as atomic protected values and revalidate cached translations against the current protection scheme.

src/hf_doc_translation/protect.py CHANGED
@@ -14,6 +14,10 @@ class ProtectionError(ValueError):
14
 
15
  _SENTINEL_RE = re.compile(r"\ue000HFDT(?P<index>\d{4})(?P<digest>[0-9a-f]{8})\ue001")
16
  _INLINE_CODE_RE = re.compile(r"(?P<ticks>`+)(?P<body>[^\n]*?)(?P=ticks)")
 
 
 
 
17
  _LINK_TARGET_RE = re.compile(r"\]\((?P<target>[^)\n]+)\)")
18
  _HTML_TAG_RE = re.compile(r"</?[A-Za-z][^>\n]*>|<!--[\s\S]*?-->")
19
  _DIRECTIVE_RE = re.compile(r"\[\[[^\n\]]+\]\]")
@@ -84,6 +88,11 @@ def protect_text(text: str, glossary: Iterable[str] = (), sentinel_offset: int =
84
  # Protect larger syntax spans first. Otherwise a glossary term inside an
85
  # inline-code span would create nested sentinels that the model could not
86
  # reproduce as a legal sequence.
 
 
 
 
 
87
  protected = _replace_matches(protected, _INLINE_CODE_RE, add)
88
  # Keep link labels available for translation while protecting only their targets.
89
  protected = _replace_matches(protected, _LINK_TARGET_RE, add, group="target")
 
14
 
15
  _SENTINEL_RE = re.compile(r"\ue000HFDT(?P<index>\d{4})(?P<digest>[0-9a-f]{8})\ue001")
16
  _INLINE_CODE_RE = re.compile(r"(?P<ticks>`+)(?P<body>[^\n]*?)(?P=ticks)")
17
+ _HTML_LITERAL_RE = re.compile(
18
+ r"<(?P<tag>code|kbd|samp|var)\b[^>]*>[\s\S]*?</(?P=tag)\s*>",
19
+ re.IGNORECASE,
20
+ )
21
  _LINK_TARGET_RE = re.compile(r"\]\((?P<target>[^)\n]+)\)")
22
  _HTML_TAG_RE = re.compile(r"</?[A-Za-z][^>\n]*>|<!--[\s\S]*?-->")
23
  _DIRECTIVE_RE = re.compile(r"\[\[[^\n\]]+\]\]")
 
88
  # Protect larger syntax spans first. Otherwise a glossary term inside an
89
  # inline-code span would create nested sentinels that the model could not
90
  # reproduce as a legal sequence.
91
+ # HTML literal elements are equivalent to Markdown inline code: protect
92
+ # both their tags and contents as one atomic value. Protecting only the
93
+ # tags would expose identifiers such as ``flash_attention_3`` as prose
94
+ # during sentinel-free retries.
95
+ protected = _replace_matches(protected, _HTML_LITERAL_RE, add)
96
  protected = _replace_matches(protected, _INLINE_CODE_RE, add)
97
  # Keep link labels available for translation while protecting only their targets.
98
  protected = _replace_matches(protected, _LINK_TARGET_RE, add, group="target")
src/hf_doc_translation/sync.py CHANGED
@@ -364,6 +364,21 @@ def _translate_segment_with_retry(
364
  ) from retry_error
365
 
366
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
  def _manifest_base(config: TranslationConfig, source_sha: str, runner_revision: str, doc_builder_revision: str) -> dict[str, Any]:
368
  return {
369
  "runner_revision": runner_revision,
@@ -489,6 +504,7 @@ def run_sync(args: argparse.Namespace) -> dict[str, Any]:
489
  manifest["metrics"] = {
490
  "cache_hits": 0,
491
  "cache_misses": 0,
 
492
  "retries": 0,
493
  "sentinel_safe_retries": 0,
494
  "translation": {},
@@ -500,6 +516,7 @@ def run_sync(args: argparse.Namespace) -> dict[str, Any]:
500
  translations: dict[str, str] = {}
501
  cache_hits = 0
502
  cache_misses = 0
 
503
  retry_metrics: dict[str, int] = {}
504
  all_segments = [segment for page in pages for segment in page.segments]
505
  if toc is not None:
@@ -510,10 +527,13 @@ def run_sync(args: argparse.Namespace) -> dict[str, Any]:
510
  for segment in all_segments:
511
  key = segment_cache_key(segment.source, config)
512
  record = None if args.check_only else cache.get(key)
513
- if record is not None:
514
- translations[segment.key] = record["translated"]
 
515
  cache_hits += 1
516
  else:
 
 
517
  cache_misses += 1
518
  pending.append(segment)
519
  pending_keys.append(key)
@@ -598,6 +618,7 @@ def run_sync(args: argparse.Namespace) -> dict[str, Any]:
598
  manifest["metrics"] = {
599
  "cache_hits": cache_hits,
600
  "cache_misses": cache_misses,
 
601
  "retries": retry_metrics.get("retries", 0),
602
  "sentinel_safe_retries": retry_metrics.get("sentinel_safe_retries", 0),
603
  "translation": metrics.as_dict() if metrics is not None else {},
 
364
  ) from retry_error
365
 
366
 
367
+ def _validated_cached_translation(record, segment, config: TranslationConfig) -> str | None:
368
+ """Return a cache hit only when it matches the current protection scheme."""
369
+
370
+ if record is None:
371
+ return None
372
+ translated = record.get("translated")
373
+ if not isinstance(translated, str):
374
+ return None
375
+ try:
376
+ validate_segment(segment.source, translated, segment.protected, config)
377
+ except (TypeError, ValueError):
378
+ return None
379
+ return translated
380
+
381
+
382
  def _manifest_base(config: TranslationConfig, source_sha: str, runner_revision: str, doc_builder_revision: str) -> dict[str, Any]:
383
  return {
384
  "runner_revision": runner_revision,
 
504
  manifest["metrics"] = {
505
  "cache_hits": 0,
506
  "cache_misses": 0,
507
+ "cache_rejections": 0,
508
  "retries": 0,
509
  "sentinel_safe_retries": 0,
510
  "translation": {},
 
516
  translations: dict[str, str] = {}
517
  cache_hits = 0
518
  cache_misses = 0
519
+ cache_rejections = 0
520
  retry_metrics: dict[str, int] = {}
521
  all_segments = [segment for page in pages for segment in page.segments]
522
  if toc is not None:
 
527
  for segment in all_segments:
528
  key = segment_cache_key(segment.source, config)
529
  record = None if args.check_only else cache.get(key)
530
+ cached_translation = _validated_cached_translation(record, segment, config)
531
+ if cached_translation is not None:
532
+ translations[segment.key] = cached_translation
533
  cache_hits += 1
534
  else:
535
+ if record is not None:
536
+ cache_rejections += 1
537
  cache_misses += 1
538
  pending.append(segment)
539
  pending_keys.append(key)
 
618
  manifest["metrics"] = {
619
  "cache_hits": cache_hits,
620
  "cache_misses": cache_misses,
621
+ "cache_rejections": cache_rejections,
622
  "retries": retry_metrics.get("retries", 0),
623
  "sentinel_safe_retries": retry_metrics.get("sentinel_safe_retries", 0),
624
  "translation": metrics.as_dict() if metrics is not None else {},
tests/test_protection.py CHANGED
@@ -43,6 +43,19 @@ class ProtectionTest(unittest.TestCase):
43
  self.assertEqual(rebuilt, protected.text)
44
  self.assertEqual(protected.restore(rebuilt), source)
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
  if __name__ == "__main__":
48
  unittest.main()
 
43
  self.assertEqual(rebuilt, protected.text)
44
  self.assertEqual(protected.restore(rebuilt), source)
45
 
46
+ def test_html_literal_elements_are_atomic_protected_values(self):
47
+ source = (
48
+ '<tr><td><code>"flash_attention_3"</code></td>'
49
+ '<td>Improves FlashAttention-2.</td></tr>\n'
50
+ )
51
+
52
+ protected = protect_text(source)
53
+ chunks, _ = split_sentinel_chunks(protected.text)
54
+
55
+ self.assertIn('<code>"flash_attention_3"</code>', protected.values)
56
+ self.assertFalse(any("flash_attention_3" in chunk for chunk in chunks))
57
+ self.assertEqual(protected.restore(protected.text), source)
58
+
59
 
60
  if __name__ == "__main__":
61
  unittest.main()
tests/test_sync.py CHANGED
@@ -14,6 +14,7 @@ from hf_doc_translation.sync import (
14
  _resolve_checkout,
15
  _sentence_parts,
16
  _translate_segment_with_retry,
 
17
  run_sync,
18
  )
19
  from hf_doc_translation.translate import ContinuousBatchTranslator, _causal_lm_load_spec
@@ -131,6 +132,74 @@ class SyncTest(unittest.TestCase):
131
  restored = segment.protected.restore(response)
132
  self.assertTrue(all(value in restored for value in segment.protected.values))
133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  def test_initial_rollout_disables_graph_and_async_warmup(self):
135
  root = Path(__file__).parents[1]
136
  for config_name in ("transformers-ja.yml", "transformers-ja-job.yml"):
 
14
  _resolve_checkout,
15
  _sentence_parts,
16
  _translate_segment_with_retry,
17
+ _validated_cached_translation,
18
  run_sync,
19
  )
20
  from hf_doc_translation.translate import ContinuousBatchTranslator, _causal_lm_load_spec
 
132
  restored = segment.protected.restore(response)
133
  self.assertTrue(all(value in restored for value in segment.protected.values))
134
 
135
+ def test_sentinel_free_retry_never_translates_html_code_contents(self):
136
+ config = SimpleNamespace(
137
+ glossary=(),
138
+ validation={
139
+ "min_japanese_characters": 1,
140
+ "max_untranslated_english_ratio": 1.0,
141
+ "min_length_ratio": 0.1,
142
+ "max_length_ratio": 4.0,
143
+ },
144
+ continuous_batching={"max_requests_per_batch": 32},
145
+ )
146
+ page = parse_markdown(
147
+ Path("attention_interface.md"),
148
+ (
149
+ '<tr><td><code>"flash_attention_3"</code></td>'
150
+ '<td>Improves FlashAttention-2.</td></tr>\n'
151
+ ),
152
+ )
153
+ segment = page.segments[0]
154
+
155
+ class Translator:
156
+ def __init__(self):
157
+ self.calls = []
158
+
159
+ def translate_many(self, texts):
160
+ self.calls.append(list(texts))
161
+ return ["改善します。" for _ in texts]
162
+
163
+ translator = Translator()
164
+ response = _translate_segment_with_retry(
165
+ segment,
166
+ translator,
167
+ config,
168
+ {},
169
+ initial_error=ValueError("model changed literal tokens"),
170
+ )
171
+
172
+ requests = [text for call in translator.calls for text in call]
173
+ self.assertFalse(any("flash_attention_3" in text for text in requests))
174
+ self.assertIn(
175
+ '<code>"flash_attention_3"</code>',
176
+ segment.protected.restore(response),
177
+ )
178
+
179
+ def test_cache_hit_must_match_current_protection_scheme(self):
180
+ config = SimpleNamespace(
181
+ validation={
182
+ "min_japanese_characters": 1,
183
+ "max_untranslated_english_ratio": 1.0,
184
+ "min_length_ratio": 0.1,
185
+ "max_length_ratio": 4.0,
186
+ },
187
+ )
188
+ segment = parse_markdown(
189
+ Path("page.md"),
190
+ '<code>"flash_attention_3"</code> backend.\n',
191
+ ).segments[0]
192
+ valid = segment.protected.text.replace(" backend", " バックエンド")
193
+ stale = valid.replace(segment.protected.sentinels[0], "", 1)
194
+
195
+ self.assertEqual(
196
+ _validated_cached_translation({"translated": valid}, segment, config),
197
+ valid,
198
+ )
199
+ self.assertIsNone(
200
+ _validated_cached_translation({"translated": stale}, segment, config)
201
+ )
202
+
203
  def test_initial_rollout_disables_graph_and_async_warmup(self):
204
  root = Path(__file__).parents[1]
205
  for config_name in ("transformers-ja.yml", "transformers-ja-job.yml"):