stevhliu's picture
stevhliu HF Staff
Protect HTML literal contents during translation retries
470d44a verified
Raw
History Blame Contribute Delete
33.1 kB
"""CLI for local gates, GPU translation, and generated-tree synchronization."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable
from .cache import TranslationCache, segment_cache_key
from .config import TranslationConfig, load_config
from .github import GitHubPublisher, PullRequestSpec, build_pr_body
from .markdown import MarkdownPage, ToCFile, iter_markdown_files, markdown_paths, non_markdown_paths, parse_markdown, parse_toc
from .protect import (
ProtectionError,
join_sentinel_chunks,
protect_text,
protected_values,
remap_sentinels,
split_protected_text,
split_sentinel_chunks,
)
from .translate import ContinuousBatchTranslator, IdentityTranslator, _load_runtime_dependencies
from .validate import ValidationError, validate_path_parity, validate_segment, validate_scope, validate_structure, validate_toc_paths
class SyncError(RuntimeError):
"""Raised when a synchronization precondition or blocking check fails."""
def _git(checkout: Path, *args: str) -> str:
completed = subprocess.run(["git", *args], cwd=checkout, check=True, text=True, capture_output=True)
return completed.stdout.strip()
def _sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _inventory(root: Path) -> tuple[set[Path], dict[str, str]]:
paths = markdown_paths(root)
hashes = {path.as_posix(): _sha256_file(root / path) for path in sorted(paths)}
return paths, hashes
def _tree_hash(hashes: dict[str, str]) -> str:
payload = "\n".join(f"{path}\0{hashes[path]}" for path in sorted(hashes))
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def _clone_source(repository: str) -> str:
"""Normalize a GitHub repository slug only at the clone boundary."""
if (
repository.count("/") == 1
and "://" not in repository
and not repository.startswith(("git@", "/", "./", "../"))
):
return f"https://github.com/{repository}.git"
return repository
def _resolve_checkout(args: argparse.Namespace) -> tuple[Path, tempfile.TemporaryDirectory[str] | None]:
if args.checkout:
checkout = Path(args.checkout).resolve()
if not (checkout / ".git").exists():
raise SyncError(f"checkout is not a Git repository: {checkout}")
return checkout, None
temporary = tempfile.TemporaryDirectory(prefix="transformers-ja-sync-")
checkout = Path(temporary.name) / "transformers"
clone_source = _clone_source(args.repository)
try:
subprocess.run(
["git", "clone", "--depth", "1", "--branch", args.base_ref, clone_source, str(checkout)],
check=True,
text=True,
)
except Exception:
temporary.cleanup()
raise
return checkout, temporary
def _verify_base_ref(checkout: Path, base_ref: str) -> str:
try:
resolved = _git(checkout, "rev-parse", "--verify", f"{base_ref}^{{commit}}")
head = _git(checkout, "rev-parse", "HEAD")
except subprocess.CalledProcessError as exc:
raise SyncError(f"could not resolve base ref {base_ref!r}") from exc
if resolved != head:
raise SyncError(
f"checkout HEAD {head} does not match requested base ref {base_ref} ({resolved}); "
"check out the exact validated base without mutating it in the runner"
)
return head
def _install_transformers_dependencies(checkout: Path) -> None:
"""Install the exact checkout and its declared runtime dependencies."""
try:
subprocess.run(
[
sys.executable,
"-m",
"pip",
"install",
"--disable-pip-version-check",
"--no-cache-dir",
"--no-build-isolation",
"--editable",
str(checkout),
],
check=True,
text=True,
)
except subprocess.CalledProcessError as exc:
raise SyncError(f"could not install Transformers runtime dependencies from {checkout}") from exc
def _ensure_clean(checkout: Path) -> None:
status = _git(checkout, "status", "--porcelain")
if status:
raise SyncError("publication requires a clean Transformers checkout; status was:\n" + status)
def _parse_source(source_root: Path, config: TranslationConfig) -> tuple[list[MarkdownPage], ToCFile | None]:
pages = [parse_markdown(relative, text, config.glossary) for relative, text in iter_markdown_files(source_root)]
toc_path = source_root / "_toctree.yml"
toc = parse_toc(Path("_toctree.yml"), toc_path.read_text(encoding="utf-8"), config.glossary) if toc_path.exists() else None
return pages, toc
def _write_staged_tree(
stage_root: Path,
pages: Iterable[MarkdownPage],
toc: ToCFile | None,
translations: dict[str, str],
) -> None:
for page in pages:
destination = stage_root / page.path
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(page.render(translations), encoding="utf-8")
if toc is not None:
destination = stage_root / toc.path
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(toc.render(translations), encoding="utf-8")
def _validate_generated_tree(
source_root: Path,
stage_root: Path,
pages: Iterable[MarkdownPage],
toc: ToCFile | None,
source_texts: dict[Path, str],
) -> dict[str, Any]:
parity = validate_path_parity(source_root, stage_root)
if parity["missing"] or parity["target_only"]:
raise ValidationError(f"staged Markdown path parity failed: {parity}")
for page in pages:
output = (stage_root / page.path).read_text(encoding="utf-8")
validate_structure(source_texts[page.path], output)
if toc is not None:
validate_toc_paths(toc.local_paths, source_root)
return {
"path_parity": "passed",
"missing_paths": [],
"target_only_paths": [],
"validation": "passed",
}
def _replace_markdown_tree(checkout: Path, target_root: Path, stage_root: Path) -> None:
"""Replace only Markdown and ToC files; leave non-Markdown assets untouched."""
target_root.mkdir(parents=True, exist_ok=True)
for existing in list(target_root.rglob("*.md")):
existing.unlink()
existing_toc = target_root / "_toctree.yml"
if existing_toc.exists():
existing_toc.unlink()
for source in stage_root.rglob("*"):
if not source.is_file():
continue
relative = source.relative_to(stage_root)
destination = target_root / relative
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, destination)
def _run_doc_checks(checkout: Path, target_root: Path, config: TranslationConfig) -> dict[str, str]:
try:
target_argument = str(target_root.relative_to(checkout))
except ValueError:
target_argument = str(target_root)
commands = [
["python3", "utils/check_doc_toc.py"],
["git", "diff", "--check"],
["doc-builder", "check-links", target_argument],
[
"doc-builder",
"build",
"transformers",
target_argument,
"--html",
"--html_page_cache",
str(config.doc_builder.get("html_cache", "")),
"--build_dir",
"/tmp/transformers-ja-doc-build",
],
]
results: dict[str, str] = {}
for command in commands:
try:
subprocess.run(command, cwd=checkout, check=True, text=True, capture_output=True)
except FileNotFoundError as exc:
raise SyncError(f"required documentation command is unavailable: {command[0]}") from exc
except subprocess.CalledProcessError as exc:
raise SyncError(f"documentation check failed: {' '.join(command)}\n{exc.stderr[-4000:]}") from exc
results[command[0] + " " + command[1]] = "passed"
return results
def _sentence_parts(source: str) -> list[str]:
"""Split only at legal prose boundaries for the one allowed retry."""
if len(source) < 2:
return [source]
boundaries = [
match.end()
for match in re.finditer(r"(?<=[.!?。!?])\s+", source)
if match.end() < len(source)
]
if not boundaries:
return [source]
midpoint = len(source) // 2
boundary = min(boundaries, key=lambda value: abs(value - midpoint))
return [source[:boundary], source[boundary:]]
def _translate_without_sentinels(
protected_pieces,
translator,
config: TranslationConfig,
) -> list[str]:
"""Translate prose only and reconstruct protected templates deterministically."""
templates = []
pending_bodies = []
pending_slots = []
for piece_index, protected in enumerate(protected_pieces):
chunks, sentinels = split_sentinel_chunks(protected.text)
translated_chunks = list(chunks)
templates.append((translated_chunks, sentinels))
for chunk_index, chunk in enumerate(chunks):
if not chunk.strip():
continue
leading_length = len(chunk) - len(chunk.lstrip())
trailing_length = len(chunk) - len(chunk.rstrip())
body_end = len(chunk) - trailing_length if trailing_length else len(chunk)
body = chunk[leading_length:body_end]
pending_bodies.append(body)
pending_slots.append(
(
piece_index,
chunk_index,
chunk[:leading_length],
chunk[body_end:],
)
)
batch_size = int(config.continuous_batching.get("max_requests_per_batch", 32))
translated_bodies = []
for batch_start in range(0, len(pending_bodies), batch_size):
translated_bodies.extend(
translator.translate_many(pending_bodies[batch_start : batch_start + batch_size])
)
if len(translated_bodies) != len(pending_slots):
raise ValidationError(
"sentinel-safe retry returned an unexpected number of prose chunks: "
f"expected {len(pending_slots)}, received {len(translated_bodies)}"
)
for (piece_index, chunk_index, prefix, suffix), translated in zip(
pending_slots,
translated_bodies,
):
templates[piece_index][0][chunk_index] = prefix + translated + suffix
responses = []
for protected, (chunks, sentinels) in zip(protected_pieces, templates):
response = join_sentinel_chunks(chunks, sentinels)
validate_segment(protected.source, response, protected, config)
responses.append(response)
return responses
def _translate_segment_with_retry(
segment,
translator,
config: TranslationConfig,
metrics: dict[str, int],
initial_error: Exception | None = None,
) -> str:
first_error = initial_error
if first_error is None:
try:
response = translator.translate_many([segment.protected.text])[0]
validate_segment(segment.source, response, segment.protected, config)
return response
except Exception as error:
first_error = error
metrics["retries"] = metrics.get("retries", 0) + 1
metrics["sentinel_safe_retries"] = metrics.get("sentinel_safe_retries", 0) + 1
pieces = _sentence_parts(segment.source)
if len(pieces) == 1:
original_protected_pieces = (segment.protected.text,)
else:
try:
original_protected_pieces = split_protected_text(segment.protected, len(pieces[0]))
except ProtectionError:
pieces = [segment.source]
original_protected_pieces = (segment.protected.text,)
original_value_by_sentinel = dict(zip(segment.protected.sentinels, segment.protected.values))
retry_protected_pieces = []
original_piece_sentinels = []
for piece, original_protected_piece in zip(pieces, original_protected_pieces):
original_sentinels = protected_values(original_protected_piece)
original_values = tuple(original_value_by_sentinel[sentinel] for sentinel in original_sentinels)
retry_protected = protect_text(piece, config.glossary)
if retry_protected.values != original_values:
raise ProtectionError(f"{segment.key}: retry protection values differ from the original segment")
retry_protected_pieces.append(retry_protected)
original_piece_sentinels.append(original_sentinels)
try:
responses = _translate_without_sentinels(retry_protected_pieces, translator, config)
remapped_responses = [
remap_sentinels(response, retry_protected.sentinels, original_sentinels)
for retry_protected, original_sentinels, response in zip(
retry_protected_pieces,
original_piece_sentinels,
responses,
)
]
response = "".join(remapped_responses)
validate_segment(segment.source, response, segment.protected, config)
return response
except Exception as retry_error:
raise ValidationError(
f"{segment.key}: sentinel-safe retry failed after {type(first_error).__name__}: {retry_error}"
) from retry_error
def _validated_cached_translation(record, segment, config: TranslationConfig) -> str | None:
"""Return a cache hit only when it matches the current protection scheme."""
if record is None:
return None
translated = record.get("translated")
if not isinstance(translated, str):
return None
try:
validate_segment(segment.source, translated, segment.protected, config)
except (TypeError, ValueError):
return None
return translated
def _manifest_base(config: TranslationConfig, source_sha: str, runner_revision: str, doc_builder_revision: str) -> dict[str, Any]:
return {
"runner_revision": runner_revision,
"model_id": config.model_id,
"model_revision": config.model_revision,
"doc_builder_revision": doc_builder_revision,
"transformers_source_sha": source_sha,
"config_hash": config.config_hash,
"prompt_hash": config.prompt_hash,
"glossary_hash": config.glossary_hash,
"segmenter_version": config.segmenter_version,
"source_language": config.source_language,
"target_language": config.target_language,
}
def _publish_generated_pr(
checkout: Path,
config: TranslationConfig,
environment: dict[str, Any],
source_sha: str,
manifest: dict[str, Any],
) -> dict[str, Any]:
bot_branch = str(environment["bot_branch"])
head_repository = str(environment["bot_repository"])
base_repository = str(environment["base_repository"])
base_branch = str(environment["base_ref"])
_git(checkout, "switch", "-C", bot_branch)
publisher = GitHubPublisher(checkout)
commit_sha = publisher.commit_generated_tree(source_sha)
bot_remote = os.environ.get("BOT_REMOTE", f"https://github.com/{head_repository}.git")
publisher.push_with_lease(bot_remote, bot_branch, bot_branch)
short_sha = source_sha[:12]
title_prefix = "[i18n-ja][staging]" if base_repository == "stevhliu/transformers" else "[i18n-ja]"
spec = PullRequestSpec(
base_repository=base_repository,
base_branch=base_branch,
head_repository=head_repository,
head_branch=bot_branch,
title=f"{title_prefix} Backfill Japanese docs from English at {short_sha}",
body=build_pr_body(manifest),
draft=base_repository == "stevhliu/transformers",
)
pr = publisher.create_or_update_pr(spec)
return {"commit_sha": commit_sha, "base": f"{base_repository}:{base_branch}", "head": f"{head_repository}:{bot_branch}", "pull_request": pr}
def run_sync(args: argparse.Namespace) -> dict[str, Any]:
config = load_config(args.config)
environment = config.environment(args.environment)
args.repository = args.repository or environment.get("repository")
checkout, temporary = _resolve_checkout(args)
try:
source_sha = _verify_base_ref(checkout, args.base_ref)
if not args.check_only:
config.require_immutable_revisions()
_ensure_clean(checkout)
_install_transformers_dependencies(checkout)
source_root = checkout / args.source
target_root = checkout / args.target
if not source_root.exists():
raise SyncError(f"English source tree does not exist: {source_root}")
pages, toc = _parse_source(source_root, config)
source_texts = {page.path: (source_root / page.path).read_text(encoding="utf-8") for page in pages}
source_paths, source_hashes = _inventory(source_root)
target_paths, _ = _inventory(target_root)
parity_before = {
"missing": sorted(path.as_posix() for path in source_paths - target_paths),
"target_only": sorted(path.as_posix() for path in target_paths - source_paths),
}
runner_revision = args.runner_revision or os.environ.get("RUNNER_REVISION", "local-unpinned")
if not args.check_only and not re.fullmatch(r"[0-9a-f]{40}", runner_revision):
raise SyncError(
"runner revision must be a 40-character immutable revision for a translation run; "
f"got {runner_revision!r}"
)
doc_builder_revision = str(config.doc_builder.get("revision", ""))
manifest = _manifest_base(config, source_sha, runner_revision, doc_builder_revision)
manifest["job_id"] = args.job_id or os.environ.get("JOB_ID") or datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
manifest["environment"] = args.environment
manifest["repository"] = args.repository or environment.get("repository")
manifest["base_ref"] = args.base_ref
manifest["english_tree_hash"] = _tree_hash(source_hashes)
manifest["inventory"] = {
"english_count": len(source_paths),
"japanese_count_before": len(target_paths),
"shared_count": len(source_paths & target_paths),
"missing_count": len(source_paths - target_paths),
"target_only_count": len(target_paths - source_paths),
"missing_paths": parity_before["missing"],
"target_only_paths": parity_before["target_only"],
}
manifest["unexpected_target_assets"] = sorted(path.as_posix() for path in non_markdown_paths(target_root))
translator = IdentityTranslator() if args.check_only else ContinuousBatchTranslator(
config=config,
transformers_src=str(checkout / "src"),
model_path=args.model_path,
)
cache = TranslationCache(Path(args.cache_dir), config, write=not args.check_only)
state_before = cache.read_state(args.environment)
if (
not args.check_only
and not args.no_publish
and state_before.get("open_pr_number")
and (os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN"))
):
publisher = GitHubPublisher(checkout)
pr_state = publisher.read_pr(str(environment["base_repository"]), int(state_before["open_pr_number"]))
state_before["open_pr_state"] = pr_state.get("state")
if pr_state.get("state") == "MERGED":
state_before["merged_source_sha"] = state_before.get("open_pr_source_sha")
state_before["open_pr_source_sha"] = None
state_before["latest_open_pr_source_sha"] = None
state_before["open_pr_number"] = None
cache.write_state(args.environment, state_before)
if (
not args.check_only
and not args.force_backfill
and state_before.get("latest_english_tree_hash") == manifest["english_tree_hash"]
and state_before.get("latest_open_pr_source_sha") in (None, source_sha)
):
manifest["metrics"] = {
"cache_hits": 0,
"cache_misses": 0,
"cache_rejections": 0,
"retries": 0,
"sentinel_safe_retries": 0,
"translation": {},
}
manifest["checks"] = {"drift": "none", "model_loading": "skipped", "publication": "not needed"}
manifest["state"] = state_before
cache.write_run(args.environment, source_sha, manifest["job_id"], manifest)
return manifest
translations: dict[str, str] = {}
cache_hits = 0
cache_misses = 0
cache_rejections = 0
retry_metrics: dict[str, int] = {}
all_segments = [segment for page in pages for segment in page.segments]
if toc is not None:
all_segments.extend(toc.segments)
try:
pending = []
pending_keys = []
for segment in all_segments:
key = segment_cache_key(segment.source, config)
record = None if args.check_only else cache.get(key)
cached_translation = _validated_cached_translation(record, segment, config)
if cached_translation is not None:
translations[segment.key] = cached_translation
cache_hits += 1
else:
if record is not None:
cache_rejections += 1
cache_misses += 1
pending.append(segment)
pending_keys.append(key)
if args.check_only:
translations.update({segment.key: segment.protected.text for segment in pending})
else:
# Submit cache misses in bounded batches while keeping the
# manager alive across the whole run. Start with the longest
# segment so the persistent manager is sized for the full
# workload rather than for whichever page happens to sort first.
pending_with_keys = sorted(zip(pending, pending_keys), key=lambda item: len(item[0].protected.text), reverse=True)
batch_size = int(config.continuous_batching.get("max_requests_per_batch", 32))
for batch_start in range(0, len(pending_with_keys), batch_size):
batch = pending_with_keys[batch_start : batch_start + batch_size]
batch_segments = [item[0] for item in batch]
batch_error = None
try:
batch_responses = translator.translate_many([segment.protected.text for segment in batch_segments])
except Exception as error:
batch_error = error
batch_responses = [None] * len(batch_segments)
for (segment, key), batch_response in zip(batch, batch_responses):
response = batch_response
if response is None:
response = _translate_segment_with_retry(
segment,
translator,
config,
retry_metrics,
initial_error=batch_error,
)
else:
try:
validate_segment(segment.source, response, segment.protected, config)
except ValidationError as error:
response = _translate_segment_with_retry(
segment,
translator,
config,
retry_metrics,
initial_error=error,
)
validation = validate_segment(segment.source, response, segment.protected, config)
translations[segment.key] = response
cache.put(
key,
{
"source_hash": key,
"source": segment.source,
"translated": response,
"model_id": config.model_id,
"model_revision": config.model_revision,
"validation": {k: v for k, v in validation.items() if k != "text"},
},
)
with tempfile.TemporaryDirectory(prefix="transformers-ja-stage-") as stage_name:
stage_root = Path(stage_name)
_write_staged_tree(stage_root, pages, toc, translations)
checks = _validate_generated_tree(source_root, stage_root, pages, toc, source_texts)
first_render = {
relative.as_posix(): path.read_text(encoding="utf-8")
for relative in markdown_paths(stage_root)
for path in [stage_root / relative]
}
_write_staged_tree(stage_root, pages, toc, translations)
second_render = {
relative.as_posix(): path.read_text(encoding="utf-8")
for relative in markdown_paths(stage_root)
for path in [stage_root / relative]
}
if first_render != second_render:
raise SyncError("same-input rerun did not produce an identical staged tree")
if not args.check_only and not args.no_publish:
_replace_markdown_tree(checkout, target_root, stage_root)
changed = _git(checkout, "diff", "--name-only").splitlines()
validate_scope(changed, args.target.rstrip("/") + "/")
checks["doc_build"] = "not run" if args.skip_doc_build else "pending"
if not args.skip_doc_build:
checks.update(_run_doc_checks(checkout, target_root, config))
checks["doc_build"] = "passed"
metrics = getattr(translator, "metrics", None)
manifest["metrics"] = {
"cache_hits": cache_hits,
"cache_misses": cache_misses,
"cache_rejections": cache_rejections,
"retries": retry_metrics.get("retries", 0),
"sentinel_safe_retries": retry_metrics.get("sentinel_safe_retries", 0),
"translation": metrics.as_dict() if metrics is not None else {},
}
manifest["checks"] = checks
if args.check_only:
manifest["checks"]["publication"] = "not run"
else:
manifest["checks"].setdefault("publication", "not requested" if args.no_publish else "generated tree replaced")
if not args.check_only and not args.no_publish:
manifest["run_record"] = str(cache.run_path(args.environment, source_sha, manifest["job_id"]))
manifest["github"] = _publish_generated_pr(checkout, config, environment, source_sha, manifest)
manifest["checks"]["publication"] = "passed"
manifest["state"] = {
"merged_source_sha": state_before.get("merged_source_sha"),
"open_pr_source_sha": source_sha if not args.no_publish else None,
"open_pr_state": "OPEN" if not args.no_publish else None,
"open_pr_number": manifest.get("github", {}).get("pull_request", {}).get("number"),
}
cache.write_run(args.environment, source_sha, manifest["job_id"], manifest)
if not args.check_only:
cache.write_state(
args.environment,
{
**cache.read_state(args.environment),
"environment": args.environment,
"open_pr_source_sha": source_sha if not args.no_publish else None,
"latest_open_pr_source_sha": source_sha if not args.no_publish else None,
"latest_english_tree_hash": manifest["english_tree_hash"],
"open_pr_state": "OPEN" if not args.no_publish else None,
"open_pr_number": manifest.get("github", {}).get("pull_request", {}).get("number"),
"last_run_id": manifest["job_id"],
},
)
return manifest
finally:
translator.close()
finally:
if temporary is not None:
temporary.cleanup()
def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
config = load_config(args.config)
config.require_immutable_revisions()
args.repository = args.repository or config.environment(args.environment).get("repository")
checkout, temporary = _resolve_checkout(args)
try:
source_sha = _verify_base_ref(checkout, args.base_ref)
_install_transformers_dependencies(checkout)
translator = ContinuousBatchTranslator(config, transformers_src=str(checkout / "src"), model_path=args.model_path)
try:
result = translator.smoke_test()
return {
"transformers_source_sha": source_sha,
"model_id": config.model_id,
"model_revision": config.model_revision,
"metrics": translator.metrics.as_dict(),
**result,
}
finally:
translator.close()
finally:
if temporary is not None:
temporary.cleanup()
def run_preflight(args: argparse.Namespace) -> dict[str, Any]:
"""Validate the pinned checkout and runtime imports without loading the model."""
config = load_config(args.config)
config.require_immutable_revisions()
args.repository = args.repository or config.environment(args.environment).get("repository")
checkout, temporary = _resolve_checkout(args)
try:
source_sha = _verify_base_ref(checkout, args.base_ref)
_install_transformers_dependencies(checkout)
torch, *_ = _load_runtime_dependencies(str(checkout / "src"))
import transformers
return {
"passed": True,
"transformers_source_sha": source_sha,
"transformers_version": getattr(transformers, "__version__", "unknown"),
"transformers_path": str(getattr(transformers, "__file__", "unknown")),
"torch_version": getattr(torch, "__version__", "unknown"),
"cuda_available": bool(torch.cuda.is_available()),
"model_id": config.model_id,
"model_revision": config.model_revision,
}
finally:
if temporary is not None:
temporary.cleanup()
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", nargs="?", choices=("sync", "smoke-batching", "preflight"), default="sync")
parser.add_argument("--config", default="transformers-ja")
parser.add_argument("--repository", default=None)
parser.add_argument("--base-ref", default="main")
parser.add_argument("--environment", default="staging")
parser.add_argument("--source", default="docs/source/en")
parser.add_argument("--target", default="docs/source/ja")
parser.add_argument("--checkout", default=None)
parser.add_argument("--cache-dir", default=os.environ.get("TRANSLATION_CACHE_ROOT", "/translation-cache"))
parser.add_argument("--model-path", default="/model")
parser.add_argument("--runner-revision", default=None)
parser.add_argument("--job-id", default=None)
parser.add_argument("--force-backfill", action="store_true")
parser.add_argument("--check-only", action="store_true")
parser.add_argument("--no-publish", action="store_true")
parser.add_argument("--skip-doc-build", action="store_true")
return parser
def main(argv: list[str] | None = None) -> int:
args = _parser().parse_args(argv)
try:
if args.command == "smoke-batching":
result = run_smoke(args)
elif args.command == "preflight":
result = run_preflight(args)
else:
result = run_sync(args)
except (SyncError, ValidationError, ValueError, RuntimeError) as exc:
print(f"ERROR: {exc}")
return 1
print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
return 0
if __name__ == "__main__": # pragma: no cover
raise SystemExit(main())