diff --git a/scripts/translate.py b/scripts/translate.py index 2fdc18ca0..ede101e8f 100644 --- a/scripts/translate.py +++ b/scripts/translate.py @@ -1,8 +1,10 @@ import secrets import subprocess +from collections.abc import Iterable from functools import lru_cache +from os import sep as pathsep from pathlib import Path -from typing import Annotated, Iterable +from typing import Annotated import git import typer @@ -12,7 +14,7 @@ from pydantic_ai import Agent from rich import print non_translated_sections = ( - "reference/", + f"reference{pathsep}", "release-notes.md", "fastapi-people.md", "external-links.md", @@ -24,45 +26,647 @@ non_translated_sections = ( general_prompt = """ -For technical terms in English that don't have a common translation term use the original term in English. +### About literal text in this prompt -If you have instructions to translate specific terms or phrases in a specific way, please follow those instructions instead of keeping the old and outdated content. +1) In the following instructions (after I say: `The above rules are in effect now`) the two characters `«` and `»` will be used to surround LITERAL TEXT, which is text or characters you shall interpret literally. The `«` and the `»` are not part of the literal text, they are the meta characters denoting it. -For code snippets or fragments, surrounded by backticks (`), don't translate the content, keep the original in English. For example, `list`, `dict`, keep them as is. +2) Furthermore, text surrounded by `«««` and `»»»` is a BLOCK OF LITERAL TEXT which spans multiple lines. To get its content, dedent all lines of the block until the `«««` and `»»»` are at column zero, then remove the newline (`\n`) after the `«««` and the newline before the `»»»`. The `«««` and the `»»»` are not part of the literal text block, they are the meta characters denoting it. -The content is written in markdown, write the translation in markdown as well. Don't add triple backticks (`) around the generated translation content. +3) If you see backticks or any other quotes inside literal text – inside `«` and `»` – or inside blocks of literal text – inside `«««` and `»»»` – then interpret them as literal characters, do NOT interpret them as meta characters. -When there's an example of code, the console or a terminal, normally surrounded by triple backticks and a keyword like "console" or "bash" (e.g. ```console), do not translate the content, keep the original in English. +The above rules are in effect now. -The original content will be surrounded by triple percentage signs (%) and you should translate it to the target language. Do not include the triple percentage signs in the translation. + +### Definitions of terms used in this prompt + +"backtick" + + The character «`» + Unicode U+0060 (GRAVE ACCENT) + +"single backtick" + + A single backtick – «`» + +"triple backticks" + + Three backticks in a row – «```» + +"neutral double quote" + + The character «"» + Unicode U+0022 (QUOTATION MARK) + +"neutral single quote" + + The character «'» + Unicode U+0027 (APOSTROPHE) + +"English double typographic quotes" + + The characters «“» and «”» + Unicode U+201C (LEFT DOUBLE QUOTATION MARK) and Unicode U+201D (RIGHT DOUBLE QUOTATION MARK) + +"English single typographic quotes" + + The characters «‘» and «’» + Unicode U+2018 (LEFT SINGLE QUOTATION MARK) and Unicode U+2019 (RIGHT SINGLE QUOTATION MARK) + +"code snippet" + + Also called "inline code". Text in a Markdown document which is surrounded by single backticks. A paragraph in a Markdown document can have a more than one code snippet. + + Example: + + ««« + `i am a code snippet` + »»» + + Example: + + ««« + `first code snippet` `second code snippet` `third code snippet` + »»» + +"code block" + + Text in a Markdown document which is surrounded by triple backticks. Spreads multiple lines. + + Example: + + ««« + ``` + Hello + World + ``` + »»» + + Example: + + ««« + ```python + print("hello World") + ``` + »»» + +"HTML element" + + a HTML opening tag – e.g. «
text
» or «`text`» or «"text"», ignore that further markup when deciding if the text is an abbreviation), and if the description (the text inside the title attribute) contains the full phrase for this abbreviation, then append a dash («–») to the full phrase, followed by the translation of the full phrase.
+
+Conversion scheme:
+
+ Source (English):
+
+ {abbreviation}
+
+ Result:
+
+ {abbreviation}
+
+Examples:
+
+ Source (English):
+
+ «««
+ IoT
+ CPU
+ TL;DR:
+ »»»
+
+ Result (German):
+
+ «««
+ IoT
+ CPU
+ TL;DR:
+ »»»
+
+1.1) If the language to which you translate mostly uses the letters of the ASCII char set (for example Spanish, French, German, but not Russian, Chinese) and if the translation of the full phrase is identical to, or starts with the same letters as the original full phrase, then only give the translation of the full phrase.
+
+Conversion scheme:
+
+ Source (English):
+
+ {abbreviation}
+
+ Result:
+
+ {abbreviation}
+
+Examples:
+
+ Source (English):
+
+ «««
+ JWT
+ Enum
+ ASGI
+ »»»
+
+ Result (German):
+
+ «««
+ JWT
+ Enum
+ ASGI
+ »»»
+
+2) If the description is not a full phrase for an abbreviation which the abbr element surrounds, but some other information, then just translate the description.
+
+Conversion scheme:
+
+ Source (English):
+
+ {text}
+
+ Result:
+
+ {translation of text}
+
+Examples:
+
+ Source (English):
+
+ «««
+ path
+ linter
+ parsing
+ 0.95.0
+ at the time of writing this
+ »»»
+
+ Result (German):
+
+ «««
+ Pfad
+ Linter
+ Parsen
+ 0.95.0
+ zum Zeitpunkt als das hier geschrieben wurde
+ »»»
+
+
+3) If the text surrounded by the abbr element is an abbreviation and the description contains both the full phrase for that abbreviation, and other information, separated by a colon («:»), then append a dash («–») and the translation of the full phrase to the original full phrase and translate the other information.
+
+Conversion scheme:
+
+ Source (English):
+
+ {abbreviation}
+
+ Result:
+
+ {abbreviation}
+
+Examples:
+
+ Source (English):
+
+ «««
+ I/O
+ CDN
+ IDE
+ »»»
+
+ Result (German):
+
+ «««
+ I/O
+ CDN
+ IDE
+ »»»
+
+3.1) Like in rule 2.1, you can leave the original full phrase away, if the translated full phrase is identical or starts with the same letters as the original full phrase.
+
+Conversion scheme:
+
+ Source (English):
+
+ {abbreviation}
+
+ Result:
+
+ {abbreviation}
+
+Example:
+
+ Source (English):
+
+ «««
+ ORM
+ »»»
+
+ Result (German):
+
+ «««
+ ORM
+ »»»
+
+4) If there is an existing translation, and it has ADDITIONAL abbr elements in a sentence, and these additional abbr elements do not exist in the related sentence in the English text, then KEEP those additional abbr elements in the translation. Do not remove them. Except when you remove the whole sentence from the translation, because the whole sentence was removed from the English text, then also remove the abbr element. The reasoning for this rule is, that such additional abbr elements are manually added by the human editor of the translation, in order to translate or explain an English word to the human readers of the translation. These additional abbr elements would not make sense in the English text, but they do make sense in the translation. So keep them in the translation, even though they are not part of the English text. This rule only applies to abbr elements.
+
+5) Apply above rules also when there is an existing translation! Make sure that all title attributes in abbr elements get properly translated or updated, using the schemes given above. However, leave the ADDITIONAL abbr's from rule 4 alone. Do not change their formatting or content.
-/// details | Vista previa
"""
app = typer.Typer()
@@ -70,7 +674,7 @@ app = typer.Typer()
@lru_cache
def get_langs() -> dict[str, str]:
- return yaml.safe_load(Path("docs/language_names.yml").read_text())
+ return yaml.safe_load(Path("docs/language_names.yml").read_text(encoding="utf-8"))
def generate_lang_path(*, lang: str, path: Path) -> Path:
@@ -99,13 +703,16 @@ def translate_page(
language: Annotated[str, typer.Option(envvar="LANGUAGE")],
en_path: Annotated[Path, typer.Option(envvar="EN_PATH")],
) -> None:
+ assert language != "en", (
+ "`en` is the source language, choose another language as translation target"
+ )
langs = get_langs()
language_name = langs[language]
lang_path = Path(f"docs/{language}")
lang_path.mkdir(exist_ok=True)
lang_prompt_path = lang_path / "llm-prompt.md"
assert lang_prompt_path.exists(), f"Prompt file not found: {lang_prompt_path}"
- lang_prompt_content = lang_prompt_path.read_text()
+ lang_prompt_content = lang_prompt_path.read_text(encoding="utf-8")
en_docs_path = Path("docs/en/docs")
assert str(en_path).startswith(str(en_docs_path)), (
@@ -113,13 +720,13 @@ def translate_page(
)
out_path = generate_lang_path(lang=language, path=en_path)
out_path.parent.mkdir(parents=True, exist_ok=True)
- original_content = en_path.read_text()
+ original_content = en_path.read_text(encoding="utf-8")
old_translation: str | None = None
if out_path.exists():
print(f"Found existing translation: {out_path}")
- old_translation = out_path.read_text()
+ old_translation = out_path.read_text(encoding="utf-8")
print(f"Translating {en_path} to {language} ({language_name})")
- agent = Agent("openai:gpt-4o")
+ agent = Agent("openai:gpt-5")
prompt_segments = [
general_prompt,
@@ -128,16 +735,19 @@ def translate_page(
if old_translation:
prompt_segments.extend(
[
- "There's an existing previous translation for this content that is probably outdated with old content or old instructions.",
+ "There is an existing previous translation for the original English content, that may be outdated.",
"Update the translation only where necessary:",
- "- If the original English content has changed, reflect that in the translation.",
+ "- If the original English content has added parts, also add these parts to the translation.",
+ "- If the original English content has removed parts, also remove them from the translation, unless you were instructed earlier to not do that in specific cases.",
+ "- If parts of the original English content have changed, also change those parts in the translation.",
"- If the previous translation violates current instructions, update it.",
- "- Otherwise, preserve the original translation **line-by-line** as-is.",
+ "- Otherwise, preserve the original translation LINE-BY-LINE, AS-IS.",
"Do not:",
- "- Rephrase or rewrite correct lines just to improve the style.",
- "- Add or remove line breaks unless the English source changed.",
- "- Change formatting or whitespace unless absolutely required.",
- "Only change what must be changed. The goal is to minimize diffs for easier review.",
+ "- rephrase or rewrite correct lines just to improve the style.",
+ "- add or remove line breaks, unless the original English content changed.",
+ "- change formatting or whitespace unless absolutely required.",
+ "Only change what must be changed. The goal is to minimize diffs for easier human review.",
+ "UNLESS you were instructed earlier to behave different, there MUST NOT be whole sentences or partial sentences in the updated translation, which are not in the original English content, and there MUST NOT be whole sentences or partial sentences in the original English content, which are not in the updated translation. Remember: the updated translation shall be IN SYNC with the original English content.",
"Previous translation:",
f"%%%\n{old_translation}%%%",
]
@@ -152,9 +762,9 @@ def translate_page(
prompt = "\n\n".join(prompt_segments)
print(f"Running agent for {out_path}")
result = agent.run_sync(prompt)
- out_content = f"{result.data.strip()}\n"
+ out_content = f"{result.output.strip()}\n"
print(f"Saving translation to {out_path}")
- out_path.write_text(out_content)
+ out_path.write_text(out_content, encoding="utf-8", newline="\n")
def iter_all_en_paths() -> Iterable[Path]:
@@ -182,10 +792,11 @@ def iter_all_en_paths() -> Iterable[Path]:
def iter_en_paths_to_translate() -> Iterable[Path]:
+ en_docs_root = Path("docs/en/docs/")
for path in iter_all_en_paths():
- if str(path).replace("docs/en/docs/", "").startswith(non_translated_sections):
- continue
- yield path
+ relpath = path.relative_to(en_docs_root)
+ if not str(relpath).startswith(non_translated_sections):
+ yield path
@app.command()