diff --git a/pontoon/machinery/composed_refine.py b/pontoon/machinery/composed_refine.py
new file mode 100644
index 0000000000..76eb7a40f5
--- /dev/null
+++ b/pontoon/machinery/composed_refine.py
@@ -0,0 +1,134 @@
+"""Pairing an entity's source leaves with the leaves of a composed translation.
+
+A composed suggestion is assembled leaf by leaf, so refining it means refining
+each leaf against the English that leaf came from.
+"""
+
+from __future__ import annotations
+
+from collections import Counter
+from collections.abc import Iterator
+from dataclasses import dataclass
+
+from moz.l10n.formats import Format
+from moz.l10n.model import (
+ CatchallKey,
+ Message,
+ Pattern,
+ PatternMessage,
+ SelectMessage,
+)
+
+from pontoon.pretranslation.pretranslate import pattern_as_context
+
+
+@dataclass
+class Leaf:
+ """`target` is live, so refining a leaf is an assignment to `target[:]`."""
+
+ id: str
+ source: Pattern
+ target: Pattern
+
+
+def _variant_key_label(keys: tuple[str | CatchallKey, ...]) -> str:
+ return ", ".join(
+ key.value or "*" if isinstance(key, CatchallKey) else key for key in keys
+ )
+
+
+def _source_variant(
+ source: SelectMessage, keys: tuple[str | CatchallKey, ...]
+) -> Pattern:
+ """`Pretranslation.message()` fans the source's catchall out to every plural
+ category the target locale declares, so a target key often has no counterpart
+ in the source: `many` in Polish comes from en-US's `other`.
+ """
+ exact = source.variants.get(keys)
+ if exact is not None:
+ return exact
+
+ for src_keys, pattern in source.variants.items():
+ if len(src_keys) == len(keys) and all(
+ isinstance(src_key, CatchallKey) or src_key == key
+ for src_key, key in zip(src_keys, keys)
+ ):
+ return pattern
+
+ return list(source.variants.values())[-1]
+
+
+def _message_leaves(leaf_id: str, source: Message, target: Message) -> Iterator[Leaf]:
+ if isinstance(target, PatternMessage):
+ source_pattern = (
+ source.pattern
+ if isinstance(source, PatternMessage)
+ else list(source.variants.values())[-1]
+ )
+ yield Leaf(leaf_id, source_pattern, target.pattern)
+ else:
+ for keys, pattern in target.variants.items():
+ source_pattern = (
+ source.pattern
+ if isinstance(source, PatternMessage)
+ else _source_variant(source, keys)
+ )
+ yield Leaf(
+ f"{leaf_id}[{_variant_key_label(keys)}]", source_pattern, pattern
+ )
+
+
+def is_accesskey(key: str) -> bool:
+ """Accesskeys are derived from their label, so they are never refined directly."""
+ return key.lower().endswith("accesskey")
+
+
+def iter_leaves(
+ source_value: Message,
+ source_properties: dict[str, Message],
+ target_value: Message,
+ target_properties: dict[str, Message],
+) -> Iterator[Leaf]:
+ """Yield every refinable leaf of a composed translation, paired with its source.
+
+ Properties absent from the source are skipped: without English to refine
+ against, the LLM would be guessing.
+ """
+ if target_value is not None and source_value is not None:
+ yield from _message_leaves("value", source_value, target_value)
+
+ for key, target in target_properties.items():
+ source = source_properties.get(key)
+ if source is None or is_accesskey(key):
+ continue
+ yield from _message_leaves(f".{key}", source, target)
+
+
+def has_translatable_text(pattern: Pattern) -> bool:
+ """A pattern of nothing but placeholders has no words to refine."""
+ return any(isinstance(el, str) and el.strip() for el in pattern)
+
+
+def placeables_survived(
+ refined: Pattern, current: Pattern, format: Format | None
+) -> bool:
+ """Whether a refined leaf still carries the placeables it was given.
+
+ Parsing says the reply is well-formed, not that it kept the variables:
+ `Zdravo { $name }` refined to `Pozdravljeni` parses cleanly and has silently
+ lost `$name`. Order is free, because languages reorder.
+
+ Placeables are compared as the text the format writes them as, which draws
+ the line in the right place on its own: the function in `{ NUMBER($n) }`,
+ its options, and a term's arguments all have to match, while the `number`
+ annotation Fluent infers for a plural selector and never writes does not.
+ """
+
+ def placeables(pattern: Pattern) -> Counter:
+ return Counter(
+ pattern_as_context([el], format)
+ for el in pattern
+ if not isinstance(el, str)
+ )
+
+ return placeables(refined) == placeables(current)
diff --git a/pontoon/machinery/openai_service.py b/pontoon/machinery/openai_service.py
index f6fa53b97e..6d805c1b72 100644
--- a/pontoon/machinery/openai_service.py
+++ b/pontoon/machinery/openai_service.py
@@ -1,3 +1,4 @@
+import json
import textwrap
from dataclasses import dataclass
@@ -28,12 +29,152 @@ class OpenAITranslation:
completion_tokens: int | None = None
+@dataclass
+class OpenAIComposedTranslation:
+ """Ids the model failed to return are absent from `leaves`, so the caller can
+ leave those leaves unrefined instead of failing the whole entry."""
+
+ leaves: dict[str, str]
+ cache_hit: bool
+ prompt_tokens: int | None = None
+ completion_tokens: int | None = None
+
+
+def _style_goal(characteristic, locale) -> str:
+ style_goals = {
+ "informal": f"Use simple, everyday {locale.name} ({locale.code}) — avoid jargon, technical terms, and formal constructions.",
+ "formal": f"Use formal {locale.name} ({locale.code}) throughout; maintain a consistent register and do not mix formal and informal modes.",
+ "rephrased": f"Provide an alternative wording that preserves the original meaning; adapt idioms and culturally marked expressions for {locale.name} ({locale.code}); you may restructure sentences but must not introduce new information or omit essential meaning.",
+ }
+ style_goal = style_goals.get(characteristic)
+ if style_goal is None:
+ raise ValueError(f"Unrecognized characteristic: '{characteristic}'")
+ return style_goal
+
+
+def _context_data(
+ entity_key, entity_comment, group_comment, resource_comment, pinned_comments, terms
+) -> list[str]:
+ """Kept separate from the instructions that explain them
+ (`_context_instructions`), so injected text cannot masquerade as one."""
+ parts = []
+ if entity_key:
+ parts.append(f"STRING ID:\n{entity_key}")
+ if resource_comment:
+ parts.append(f"RESOURCE COMMENT:\n{resource_comment}")
+ if group_comment:
+ parts.append(f"GROUP COMMENT:\n{group_comment}")
+ if entity_comment:
+ parts.append(f"STRING COMMENT:\n{entity_comment}")
+ if pinned_comments:
+ pinned_block = "\n".join(f"- {c}" for c in pinned_comments)
+ parts.append(f"PINNED COMMENTS:\n{pinned_block}")
+ if terms:
+ term_lines = []
+ for term in terms:
+ text = term.get("text", "")
+ pos = term.get("part_of_speech", "")
+ translation = term.get("translation", "")
+ term_parts = [f'"{text}"']
+ if pos:
+ term_parts.append(f"({pos})")
+ if translation:
+ term_parts.append(f'→ "{translation}"')
+ term_lines.append(" ".join(term_parts))
+ terms_block = "\n".join(f"- {line}" for line in term_lines)
+ parts.append(
+ f"TERMINOLOGY:\nThese are terminology matches in the source text that you should consider:\n{terms_block}"
+ )
+ return parts
+
+
+def _context_instructions(
+ entity_key, entity_comment, group_comment, resource_comment, pinned_comments, terms
+) -> str:
+ """Paired with `_context_data`; "" when there is no context."""
+ instructions = []
+ if entity_key:
+ instructions.append(
+ "STRING ID: infer the UI context (e.g. button, menu item, title, tooltip) and adapt length and phrasing accordingly."
+ )
+ if resource_comment:
+ instructions.append("RESOURCE COMMENT: background context about the file.")
+ if group_comment:
+ instructions.append(
+ "GROUP COMMENT: background context about the group of strings this one belongs to."
+ )
+ if entity_comment:
+ instructions.append(
+ "STRING COMMENT: authoritative translator notes (e.g. placeholders or terms to preserve) — takes precedence over stylistic choices."
+ )
+ if pinned_comments:
+ instructions.append(
+ "PINNED COMMENTS: high-priority guidance from the localization team's project manager."
+ )
+ if terms:
+ instructions.append(
+ "TERMINOLOGY: use the given translations consistently, unless incorrect for this context."
+ )
+ return "\n".join(instructions) + "\n\n" if instructions else ""
+
+
+def _system_rules(style_goal, output_instruction, extra_rules=()) -> str:
+ rules = [
+ "Match the English source's ending punctuation exactly (including having none), using correct target-language conventions (e.g. Spanish ¿¡, French non-breaking space before ?!:).",
+ "Preserve all HTML tags and attributes exactly as in the source; translate only text content and translatable attributes (e.g. alt, title).",
+ style_goal,
+ *extra_rules,
+ ]
+ numbered = "\n".join(f"{i}) {rule}" for i, rule in enumerate(rules, 1))
+ return (
+ f"Rules, in priority order if they conflict:\n{numbered}\n\n"
+ f"{output_instruction}"
+ )
+
+
+COMPOSED_SCHEMA = {
+ "type": "object",
+ "properties": {
+ "leaves": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {"type": "string"},
+ "text": {"type": "string"},
+ },
+ "required": ["id", "text"],
+ "additionalProperties": False,
+ },
+ }
+ },
+ "required": ["leaves"],
+ "additionalProperties": False,
+}
+
+
class OpenAIService:
def __init__(self):
if not settings.OPENAI_API_KEY:
raise ValueError("Missing OpenAI API key")
self.client = OpenAI()
+ def _complete(self, system_message, user_prompt, response_format=None):
+ kwargs = {}
+ if response_format is not None:
+ kwargs["response_format"] = response_format
+ return self.client.chat.completions.create(
+ model=settings.OPENAI_MODEL,
+ messages=[
+ {"role": "system", "content": system_message},
+ {"role": "user", "content": user_prompt},
+ ],
+ temperature=0, # Set temperature to 0 for deterministic output
+ top_p=1, # Set top_p to 1 to consider the full distribution
+ reasoning_effort="none", # Disable reasoning for faster responses
+ **kwargs,
+ )
+
def get_translation(
self,
english_text,
@@ -53,46 +194,17 @@ def get_translation(
presented. May be empty, in which case the model translates from the
English source alone.
"""
- style_goals = {
- "informal": f"Use simple, everyday {locale.name} ({locale.code}) — avoid jargon, technical terms, and formal constructions.",
- "formal": f"Use formal {locale.name} ({locale.code}) throughout; maintain a consistent register and do not mix formal and informal modes.",
- "rephrased": f"Provide an alternative wording that preserves the original meaning; adapt idioms and culturally marked expressions for {locale.name} ({locale.code}); you may restructure sentences but must not introduce new information or omit essential meaning.",
- }
+ style_goal = _style_goal(characteristic, locale)
+ context_args = (
+ entity_key,
+ entity_comment,
+ group_comment,
+ resource_comment,
+ pinned_comments,
+ terms,
+ )
- style_goal = style_goals.get(characteristic)
- if style_goal is None:
- raise ValueError(f"Unrecognized characteristic: '{characteristic}'")
-
- # Separate the instruction from the data.
- # It makes it hard for injected text to masquerade as instructions.
- context_parts = []
- if entity_key:
- context_parts.append(f"STRING ID:\n{entity_key}")
- if resource_comment:
- context_parts.append(f"RESOURCE COMMENT:\n{resource_comment}")
- if group_comment:
- context_parts.append(f"GROUP COMMENT:\n{group_comment}")
- if entity_comment:
- context_parts.append(f"STRING COMMENT:\n{entity_comment}")
- if pinned_comments:
- pinned_block = "\n".join(f"- {c}" for c in pinned_comments)
- context_parts.append(f"PINNED COMMENTS:\n{pinned_block}")
- if terms:
- term_lines = []
- for term in terms:
- text = term.get("text", "")
- pos = term.get("part_of_speech", "")
- translation = term.get("translation", "")
- parts = [f'"{text}"']
- if pos:
- parts.append(f"({pos})")
- if translation:
- parts.append(f'→ "{translation}"')
- term_lines.append(" ".join(parts))
- terms_block = "\n".join(f"- {line}" for line in term_lines)
- context_parts.append(
- f"TERMINOLOGY:\nThese are terminology matches in the source text that you should consider:\n{terms_block}"
- )
+ context_parts = _context_data(*context_args)
context_parts.append(f"ENGLISH SOURCE:\n{english_text}")
# Flattened, because a source may contribute more than one text and the
# prompt presents them as a flat list.
@@ -132,47 +244,14 @@ def get_translation(
+ reference_instruction
)
- context_instructions = []
- if entity_key:
- context_instructions.append(
- "STRING ID: infer the UI context (e.g. button, menu item, title, tooltip) and adapt length and phrasing accordingly."
- )
- if resource_comment:
- context_instructions.append(
- "RESOURCE COMMENT: background context about the file."
- )
- if group_comment:
- context_instructions.append(
- "GROUP COMMENT: background context about the group of strings this one belongs to."
+ system_message = (
+ system_header
+ + _context_instructions(*context_args)
+ + _system_rules(
+ style_goal, "Output only the translation, with no explanation."
)
- if entity_comment:
- context_instructions.append(
- "STRING COMMENT: authoritative translator notes (e.g. placeholders or terms to preserve) — takes precedence over stylistic choices."
- )
- if pinned_comments:
- context_instructions.append(
- "PINNED COMMENTS: high-priority guidance from the localization team's project manager."
- )
- if terms:
- context_instructions.append(
- "TERMINOLOGY: use the given translations consistently, unless incorrect for this context."
- )
- context_block = (
- "\n".join(context_instructions) + "\n\n" if context_instructions else ""
- )
-
- system_rules = textwrap.dedent(
- f"""\
- Rules, in priority order if they conflict:
- 1) Match the English source's ending punctuation exactly (including having none), using correct target-language conventions (e.g. Spanish ¿¡, French non-breaking space before ?!:).
- 2) Preserve all HTML tags and attributes exactly as in the source; translate only text content and translatable attributes (e.g. alt, title).
- 3) {style_goal}
-
- Output only the translation, with no explanation."""
)
- system_message = system_header + context_block + system_rules
-
cache_key = get_machinery_service_cache_key(
"openai_chatgpt",
settings.OPENAI_MODEL,
@@ -183,17 +262,7 @@ def get_translation(
if cached is not None:
return OpenAITranslation(text=cached, cache_hit=True)
- # Call the OpenAI API with the constructed prompt
- response = self.client.chat.completions.create(
- model=settings.OPENAI_MODEL,
- messages=[
- {"role": "system", "content": system_message},
- {"role": "user", "content": user_prompt},
- ],
- temperature=0, # Set temperature to 0 for deterministic output
- top_p=1, # Set top_p to 1 to consider the full distribution
- reasoning_effort="none", # Disable reasoning for faster responses
- )
+ response = self._complete(system_message, user_prompt)
result = response.choices[0].message.content.strip()
set_machinery_service_cache_key(cache_key, result)
@@ -204,3 +273,102 @@ def get_translation(
prompt_tokens=getattr(usage, "prompt_tokens", None),
completion_tokens=getattr(usage, "completion_tokens", None),
)
+
+ def get_composed_translation(
+ self,
+ leaves,
+ characteristic,
+ locale,
+ entity_key=None,
+ entity_comment=None,
+ group_comment=None,
+ resource_comment=None,
+ pinned_comments=None,
+ terms=None,
+ ) -> OpenAIComposedTranslation:
+ """Refine every part of a multi-part string in one request.
+
+ One call rather than one per part, so the shared context is sent once and
+ the model keeps one register across parts the user sees side by side.
+
+ :param leaves: ``[{"id": …, "source": …, "current": …}, …]``, each text
+ in the resource format's own syntax.
+ """
+ style_goal = _style_goal(characteristic, locale)
+ context_args = (
+ entity_key,
+ entity_comment,
+ group_comment,
+ resource_comment,
+ pinned_comments,
+ terms,
+ )
+
+ context_parts = _context_data(*context_args)
+ context_parts.append(
+ "PARTS (JSON):\n" + json.dumps(list(leaves), ensure_ascii=False, indent=2)
+ )
+ user_prompt = "\n\n".join(context_parts)
+
+ system_header = textwrap.dedent(
+ f"""\
+ You are an expert {locale.name} ({locale.code}) localization specialist.
+
+ Your task: produce a {characteristic} {locale.name} ({locale.code}) translation of every part of a multi-part UI string.
+ Each part has an `id`, its English `source`, and a `current` machine-assembled translation.
+ Use each `current` translation as a guide, but rewrite freely if it can be improved.
+ """
+ )
+
+ system_message = (
+ system_header
+ + _context_instructions(*context_args)
+ + _system_rules(
+ style_goal,
+ "Return one entry for every `id` you were given, and no others. Output only the translations, with no explanation.",
+ extra_rules=[
+ "Reproduce any placeable, such as { $count }, exactly as it appears; never translate or drop one.",
+ "Keep register, terminology and phrasing consistent across all parts — the user sees them together, so they must read as one string.",
+ ],
+ )
+ )
+
+ cache_key = get_machinery_service_cache_key(
+ "openai_chatgpt_composed",
+ settings.OPENAI_MODEL,
+ system_message,
+ user_prompt,
+ )
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return OpenAIComposedTranslation(leaves=json.loads(cached), cache_hit=True)
+
+ response = self._complete(
+ system_message,
+ user_prompt,
+ response_format={
+ "type": "json_schema",
+ "json_schema": {
+ "name": "composed_translation",
+ "strict": True,
+ "schema": COMPOSED_SCHEMA,
+ },
+ },
+ )
+
+ requested = {leaf["id"] for leaf in leaves}
+ parsed = json.loads(response.choices[0].message.content)
+ result = {
+ leaf["id"]: leaf["text"]
+ for leaf in parsed["leaves"]
+ if leaf["id"] in requested
+ }
+
+ set_machinery_service_cache_key(cache_key, json.dumps(result))
+ usage = getattr(response, "usage", None)
+ return OpenAIComposedTranslation(
+ leaves=result,
+ cache_hit=False,
+ prompt_tokens=getattr(usage, "prompt_tokens", None),
+ completion_tokens=getattr(usage, "completion_tokens", None),
+ )
diff --git a/pontoon/machinery/tests/test_composed_refine.py b/pontoon/machinery/tests/test_composed_refine.py
new file mode 100644
index 0000000000..7a038622c1
--- /dev/null
+++ b/pontoon/machinery/tests/test_composed_refine.py
@@ -0,0 +1,762 @@
+import json
+
+from textwrap import dedent
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from django.core.cache import cache
+from django.urls import reverse
+
+from pontoon.machinery.views import MAX_COMPOSED_LEAVES
+from pontoon.test.factories import (
+ EntityFactory,
+ LocaleFactory,
+ ResourceFactory,
+ TermFactory,
+ TranslationMemoryFactory,
+)
+
+
+@pytest.fixture
+def fluent_resource(project_a):
+ return ResourceFactory(project=project_a, path="resource.ftl", format="fluent")
+
+
+def gpt_response(leaves):
+ """A mocked structured-output completion returning `{id: text}` as JSON."""
+ response = MagicMock()
+ response.choices[0].message.content = json.dumps(
+ {"leaves": [{"id": key, "text": text} for key, text in leaves.items()]}
+ )
+ return response
+
+
+def refine(client, entity, locale, composed, **kwargs):
+ params = {
+ "entity_pk": str(entity.pk),
+ "locale": locale.code,
+ "characteristic": "formal",
+ "value": json.dumps(composed.get("value", [])),
+ "properties": json.dumps(composed.get("properties", {})),
+ **kwargs,
+ }
+ return client.post(reverse("pontoon.openai_chatgpt_composed"), params)
+
+
+@pytest.mark.django_db
+def test_refine_not_logged_in(client, fluent_resource, locale_a, openai_api_key):
+ entity = EntityFactory(resource=fluent_resource, string="key = Hello\n")
+ response = refine(client, entity, locale_a, {"value": ["Zdravo"]})
+ # `login_required(login_url="/403")` redirects rather than returning 403.
+ assert response.status_code == 302
+
+
+@pytest.mark.django_db
+def test_refine_bad_request(member, fluent_resource, locale_a, openai_api_key):
+ entity = EntityFactory(resource=fluent_resource, string="key = Hello\n")
+ url = reverse("pontoon.openai_chatgpt_composed")
+
+ response = member.client.post(
+ url, {"locale": locale_a.code, "characteristic": "formal", "value": "[]"}
+ )
+ assert response.status_code == 400
+
+ response = member.client.post(
+ url,
+ {
+ "entity_pk": str(entity.pk),
+ "locale": locale_a.code,
+ "characteristic": "formal",
+ "value": "not json",
+ },
+ )
+ assert response.status_code == 400
+
+
+@pytest.mark.django_db
+def test_refine_label_and_accesskey(member, fluent_resource, locale_a, openai_api_key):
+ """Every text leaf is refined in one call; the accesskey follows the label."""
+ cache.clear()
+ fluent_string = dedent(
+ """\
+ button =
+ .label = Save file
+ .accesskey = S
+ .title = Saves the current file
+ """
+ )
+ entity = EntityFactory(resource=fluent_resource, string=fluent_string)
+
+ composed = {
+ "value": [],
+ "properties": {
+ "label": ["Shrani datoteko"],
+ "accesskey": ["S"],
+ "title": ["Shrani trenutno datoteko"],
+ },
+ }
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response(
+ {".label": "Shranite datoteko", ".title": "Shranite trenutno datoteko"}
+ )
+ response = refine(member.client, entity, locale_a, composed)
+
+ assert response.status_code == 200
+ assert create.call_count == 1
+
+ body = json.loads(response.content)
+ assert body["properties"]["label"] == ["Shranite datoteko"]
+ assert body["properties"]["title"] == ["Shranite trenutno datoteko"]
+ # Derived from the refined label, not carried over from the input.
+ assert body["properties"]["accesskey"] == ["S"]
+
+ # The accesskey leaf is never sent to the model.
+ parts = json.loads(
+ create.call_args.kwargs["messages"][1]["content"].split("PARTS (JSON):\n")[1]
+ )
+ assert {part["id"] for part in parts} == {".label", ".title"}
+
+
+@pytest.mark.django_db
+def test_refine_pairs_each_part_with_its_english(
+ member, fluent_resource, locale_a, openai_api_key
+):
+ """Each part carries the English of that part, not of the whole entry."""
+ cache.clear()
+ fluent_string = dedent(
+ """\
+ button = Click Me
+ .title = Tooltip text
+ """
+ )
+ entity = EntityFactory(resource=fluent_resource, string=fluent_string)
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response({"value": "A", ".title": "B"})
+ refine(
+ member.client,
+ entity,
+ locale_a,
+ {"value": ["Kliknite"], "properties": {"title": ["Namig"]}},
+ )
+
+ parts = json.loads(
+ create.call_args.kwargs["messages"][1]["content"].split("PARTS (JSON):\n")[1]
+ )
+ assert parts == [
+ {"id": "value", "source": "Click Me", "current": "Kliknite"},
+ {"id": ".title", "source": "Tooltip text", "current": "Namig"},
+ ]
+
+
+@pytest.mark.django_db
+def test_refine_plural_variants_pair_with_source_catchall(
+ member, fluent_resource, openai_api_key
+):
+ """Target categories the source lacks pair with the source's catchall."""
+ cache.clear()
+ locale = LocaleFactory(code="sl-test", name="Plural", cldr_plurals="1,2,3,5")
+ fluent_string = dedent(
+ """\
+ popup =
+ { $count ->
+ *[other] { $count } popups.
+ }
+ """
+ )
+ entity = EntityFactory(resource=fluent_resource, string=fluent_string)
+
+ composed = {
+ "value": {
+ "decl": {"count": {"$": "count", "fn": "number"}},
+ "sel": ["count"],
+ "alt": [
+ {"keys": ["one"], "pat": [{"$": "count"}, " pojavnih oken."]},
+ {"keys": ["two"], "pat": [{"$": "count"}, " pojavnih oken."]},
+ {"keys": ["few"], "pat": [{"$": "count"}, " pojavnih oken."]},
+ {"keys": [{"*": "other"}], "pat": [{"$": "count"}, " pojavnih oken."]},
+ ],
+ },
+ "properties": {},
+ }
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response(
+ {
+ "value[one]": "{ $count } pojavno okno.",
+ "value[two]": "{ $count } pojavni okni.",
+ "value[few]": "{ $count } pojavna okna.",
+ "value[other]": "{ $count } pojavnih oken.",
+ }
+ )
+ response = refine(member.client, entity, locale, composed)
+
+ assert response.status_code == 200
+ assert create.call_count == 1
+
+ parts = json.loads(
+ create.call_args.kwargs["messages"][1]["content"].split("PARTS (JSON):\n")[1]
+ )
+ # All four target categories are sent, each against the source catchall.
+ assert [part["id"] for part in parts] == [
+ "value[one]",
+ "value[two]",
+ "value[few]",
+ "value[other]",
+ ]
+ assert {part["source"] for part in parts} == {"{ $count } popups."}
+
+ # Placeables come back as structured elements, not as literal text.
+ body = json.loads(response.content)
+ assert body["value"]["alt"][0]["pat"] == [{"$": "count"}, " pojavno okno."]
+ assert body["value"]["alt"][3]["pat"] == [{"$": "count"}, " pojavnih oken."]
+
+
+@pytest.mark.django_db
+def test_refine_omitted_leaf_stays_unrefined(
+ member, fluent_resource, locale_a, openai_api_key
+):
+ """A partial answer refines what it can rather than failing the entry."""
+ cache.clear()
+ fluent_string = dedent(
+ """\
+ button = Click Me
+ .title = Tooltip text
+ """
+ )
+ entity = EntityFactory(resource=fluent_resource, string=fluent_string)
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ # `title` omitted, plus an id that was never requested.
+ create.return_value = gpt_response({"value": "Kliknite tukaj", "bogus": "X"})
+ response = refine(
+ member.client,
+ entity,
+ locale_a,
+ {"value": ["Kliknite"], "properties": {"title": ["Namig"]}},
+ )
+
+ assert response.status_code == 200
+ body = json.loads(response.content)
+ assert body["value"] == ["Kliknite tukaj"]
+ assert body["properties"] == {"title": ["Namig"]}
+
+
+@pytest.mark.django_db
+def test_refine_nothing_to_refine(member, fluent_resource, locale_a, openai_api_key):
+ """A suggestion with no translatable text costs no API call."""
+ cache.clear()
+ entity = EntityFactory(resource=fluent_resource, string="key = { $var }\n")
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ response = refine(member.client, entity, locale_a, {"value": [{"$": "var"}]})
+
+ assert response.status_code == 200
+ assert json.loads(response.content) == {}
+ assert create.call_count == 0
+
+
+@pytest.mark.django_db
+def test_refine_cache(member, fluent_resource, locale_a, openai_api_key):
+ cache.clear()
+ entity = EntityFactory(
+ resource=fluent_resource, string="button = Click Me\n .title = Tooltip\n"
+ )
+ composed = {"value": ["Kliknite"], "properties": {"title": ["Namig"]}}
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response({"value": "A", ".title": "B"})
+
+ first = refine(member.client, entity, locale_a, composed)
+ assert create.call_count == 1
+
+ second = refine(member.client, entity, locale_a, composed)
+ assert create.call_count == 1
+
+ assert json.loads(first.content) == json.loads(second.content)
+
+
+@pytest.mark.django_db
+def test_refine_auto_requires_enabled_locale(
+ member, fluent_resource, locale_a, openai_api_key, settings
+):
+ cache.clear()
+ settings.OPENAI_AUTO_SUGGESTION_LOCALES = ["other-locale"]
+ entity = EntityFactory(resource=fluent_resource, string="key = Hello\n")
+
+ response = refine(
+ member.client, entity, locale_a, {"value": ["Zdravo"]}, trigger="auto"
+ )
+ assert response.status_code == 403
+
+ settings.OPENAI_AUTO_SUGGESTION_LOCALES = [locale_a.code]
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ MockOpenAI.return_value.chat.completions.create.return_value = gpt_response(
+ {"value": "Pozdravljeni"}
+ )
+ response = refine(
+ member.client, entity, locale_a, {"value": ["Zdravo"]}, trigger="auto"
+ )
+ assert response.status_code == 200
+
+
+@pytest.mark.django_db
+def test_refine_invalid_trigger(member, fluent_resource, locale_a, openai_api_key):
+ entity = EntityFactory(resource=fluent_resource, string="key = Hello\n")
+ response = refine(
+ member.client, entity, locale_a, {"value": ["Zdravo"]}, trigger="bogus"
+ )
+ assert response.status_code == 400
+
+
+@pytest.mark.django_db
+def test_refine_consumes_machinery_composed_output(
+ member, fluent_resource, entity_a, locale_a, openai_api_key
+):
+ """The two are separate requests joined only by the client, so their
+ `(value, properties)` shapes have to agree with no massaging in between."""
+ cache.clear()
+ fluent_string = dedent(
+ """\
+ button = Click Me
+ .title = Tooltip text
+ """
+ )
+ entity = EntityFactory(resource=fluent_resource, string=fluent_string)
+
+ TranslationMemoryFactory.create(
+ entity=entity_a, source="Click Me", target="Kliknite", locale=locale_a
+ )
+ TranslationMemoryFactory.create(
+ entity=entity_a, source="Tooltip text", target="Namig", locale=locale_a
+ )
+
+ composed = json.loads(
+ member.client.get(
+ reverse("pontoon.machinery_composed"),
+ {
+ "entity": str(entity.pk),
+ "locale": locale_a.code,
+ "service": "translation-memory",
+ },
+ ).content
+ )
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response(
+ {"value": "Kliknite tukaj", ".title": "Namig za gumb"}
+ )
+ response = member.client.post(
+ reverse("pontoon.openai_chatgpt_composed"),
+ {
+ "entity_pk": str(entity.pk),
+ "locale": locale_a.code,
+ "characteristic": "formal",
+ "value": json.dumps(composed["value"]),
+ "properties": json.dumps(composed["properties"]),
+ },
+ )
+
+ assert response.status_code == 200
+ assert json.loads(response.content) == {
+ "value": ["Kliknite tukaj"],
+ "properties": {"title": ["Namig za gumb"]},
+ }
+
+
+def sent_parts(create):
+ """The PARTS block of the prompt the model was given."""
+ return json.loads(
+ create.call_args.kwargs["messages"][1]["content"].split("PARTS (JSON):\n")[1]
+ )
+
+
+@pytest.mark.django_db
+def test_refine_value_and_value_attribute_do_not_collide(
+ member, fluent_resource, locale_a, openai_api_key
+):
+ """A Fluent entry can have both a value and a `.value` attribute."""
+ cache.clear()
+ fluent_string = dedent(
+ """\
+ sync-header = Sync your data
+ .value = Sync
+ """
+ )
+ entity = EntityFactory(resource=fluent_resource, string=fluent_string)
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response(
+ {"value": "Sinhronizirajte podatke", ".value": "Sinhronizacija"}
+ )
+ response = refine(
+ member.client,
+ entity,
+ locale_a,
+ {"value": ["Sinhroniziraj"], "properties": {"value": ["Sinh"]}},
+ )
+
+ assert [part["id"] for part in sent_parts(create)] == ["value", ".value"]
+ assert json.loads(response.content) == {
+ "value": ["Sinhronizirajte podatke"],
+ "properties": {"value": ["Sinhronizacija"]},
+ }
+
+
+@pytest.mark.django_db
+def test_refine_skips_a_multi_line_leaf(
+ member, fluent_resource, locale_a, openai_api_key
+):
+ """Fluent's inline form cannot express a line break, so it is not sent."""
+ cache.clear()
+ entity = EntityFactory(
+ resource=fluent_resource,
+ string="intro = First line\n Second line\n .title = Intro\n",
+ )
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response({".title": "Uvod v program"})
+ response = refine(
+ member.client,
+ entity,
+ locale_a,
+ {"value": ["Ena\nDve"], "properties": {"title": ["Uvod"]}},
+ )
+
+ assert [part["id"] for part in sent_parts(create)] == [".title"]
+ body = json.loads(response.content)
+ assert body["value"] == ["Ena\nDve"]
+ assert body["properties"]["title"] == ["Uvod v program"]
+
+
+@pytest.mark.django_db
+def test_refine_skips_a_reply_with_a_line_break(
+ member, fluent_resource, locale_a, openai_api_key
+):
+ cache.clear()
+ entity = EntityFactory(
+ resource=fluent_resource, string="button = Click Me\n .title = Tip\n"
+ )
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response(
+ {"value": "Kliknite\n* tukaj", ".title": "Namig"}
+ )
+ response = refine(
+ member.client,
+ entity,
+ locale_a,
+ {"value": ["Klikni"], "properties": {"title": ["Nasvet"]}},
+ )
+
+ body = json.loads(response.content)
+ assert body["value"] == ["Klikni"]
+ assert body["properties"]["title"] == ["Namig"]
+
+
+@pytest.mark.django_db
+def test_refine_rejects_an_implausible_number_of_parts(
+ member, fluent_resource, locale_a, openai_api_key
+):
+ """One prompt holds every part, so a client cannot inflate it without bound.
+
+ Variants are the lever: a target selector yields one leaf per variant even
+ when the source has a single pattern.
+ """
+ cache.clear()
+ entity = EntityFactory(resource=fluent_resource, string="key = Value\n")
+ value = {
+ "decl": {"n": {"$": "n", "fn": "number"}},
+ "sel": ["n"],
+ "alt": [
+ {"keys": [f"k{i}"], "pat": [f"Vrednost {i}"]}
+ for i in range(MAX_COMPOSED_LEAVES + 1)
+ ],
+ }
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ response = member.client.post(
+ reverse("pontoon.openai_chatgpt_composed"),
+ {
+ "entity_pk": str(entity.pk),
+ "locale": locale_a.code,
+ "characteristic": "formal",
+ "value": json.dumps(value),
+ "properties": "{}",
+ },
+ )
+
+ assert response.status_code == 400
+ assert create.call_count == 0
+
+
+@pytest.mark.django_db
+def test_refine_matches_terminology_against_the_leaf_text(
+ member, fluent_resource, locale_a, openai_api_key
+):
+ """Not against `entity.string`, whose serialization includes the id and keys."""
+ cache.clear()
+ TermFactory.create(text="header", definition="a header")
+ TermFactory.create(text="Sync", definition="to synchronise")
+ entity = EntityFactory(
+ resource=fluent_resource,
+ string="sync-header = Sync your data\n .title = Open settings\n",
+ )
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response({"value": "A", ".title": "B"})
+ refine(
+ member.client,
+ entity,
+ locale_a,
+ {"value": ["Sinhroniziraj"], "properties": {"title": ["Nastavitve"]}},
+ )
+
+ prompt = create.call_args.kwargs["messages"][1]["content"]
+ assert '"Sync"' in prompt
+ # `header` only appears in the message id, which is not translated text.
+ assert '"header"' not in prompt
+
+
+@pytest.mark.django_db
+def test_refine_sends_and_reads_back_real_syntax(
+ member, fluent_resource, locale_a, openai_api_key
+):
+ """Placeables go to the model as Fluent, and the reply is parsed like a TM match."""
+ cache.clear()
+ entity = EntityFactory(
+ resource=fluent_resource,
+ string="progress = { $count } of { $total }\n .title = Progress\n",
+ )
+ composed = {
+ "value": [{"$": "count"}, " od ", {"$": "total"}],
+ "properties": {"title": ["Napredek"]},
+ }
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response({"value": "{ $count } izmed { $total }"})
+ response = refine(member.client, entity, locale_a, composed)
+
+ value_part = next(p for p in sent_parts(create) if p["id"] == "value")
+ assert value_part["source"] == "{ $count } of { $total }"
+ assert value_part["current"] == "{ $count } od { $total }"
+
+ assert json.loads(response.content)["value"] == [
+ {"$": "count"},
+ " izmed ",
+ {"$": "total"},
+ ]
+
+
+@pytest.mark.django_db
+def test_refine_keeps_a_leaf_whose_reply_does_not_parse(
+ member, fluent_resource, locale_a, openai_api_key
+):
+ cache.clear()
+ entity = EntityFactory(
+ resource=fluent_resource,
+ string="greet = Hello { $name }\n .title = Greeting\n",
+ )
+ composed = {
+ "value": ["Zdravo ", {"$": "name"}],
+ "properties": {"title": ["Pozdrav"]},
+ }
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response(
+ {"value": "Pozdravljeni { $name", ".title": "Pozdravi"}
+ )
+ response = refine(member.client, entity, locale_a, composed)
+
+ body = json.loads(response.content)
+ assert body["value"] == ["Zdravo ", {"$": "name"}]
+ assert body["properties"]["title"] == ["Pozdravi"]
+
+
+@pytest.mark.django_db
+def test_refine_a_non_fluent_leaf_whose_english_has_placeholders(
+ member, project_a, locale_a, openai_api_key
+):
+ """The English is only shown, so its placeholders need no round trip.
+
+ A webext source parses `$NAME$` into a placeholder while its Translation
+ Memory match is plain text, which used to skip the leaf entirely.
+ """
+ cache.clear()
+ resource = ResourceFactory(project=project_a, path="messages.json", format="webext")
+ entity = EntityFactory(
+ resource=resource,
+ string="Hello $NAME$",
+ key=["greet"],
+ )
+ entity.value = ["Hello ", {"$": "NAME", "attr": {"source": "$NAME$"}}]
+ entity.properties = {"title": ["Greeting"]}
+ entity.save()
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response({"value": "Pozdravljeni $NAME$"})
+ response = refine(
+ member.client,
+ entity,
+ locale_a,
+ {"value": ["Zdravo $NAME$"], "properties": {"title": ["Pozdrav"]}},
+ )
+
+ value_part = next(p for p in sent_parts(create) if p["id"] == "value")
+ assert value_part["source"] == "Hello $NAME$"
+ assert json.loads(response.content)["value"] == ["Pozdravljeni $NAME$"]
+
+
+@pytest.mark.django_db
+@pytest.mark.parametrize(
+ "reply",
+ [
+ "Pozdravljeni", # dropped
+ "{ $name }, { $name }!", # repeated
+ "Pozdravljeni { $ime }", # renamed
+ "Pozdravljeni { $name } { $count }", # invented
+ ],
+)
+def test_refine_rejects_a_reply_that_loses_a_placeable(
+ member, fluent_resource, locale_a, openai_api_key, reply
+):
+ """Parsing says the reply is well-formed, not that it kept the variables."""
+ cache.clear()
+ entity = EntityFactory(
+ resource=fluent_resource,
+ string="greet = Hello { $name }\n .title = Greeting\n",
+ )
+ composed = {
+ "value": ["Zdravo ", {"$": "name"}],
+ "properties": {"title": ["Pozdrav"]},
+ }
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response({"value": reply, ".title": "Pozdravilo"})
+ response = refine(member.client, entity, locale_a, composed)
+
+ body = json.loads(response.content)
+ assert body["value"] == ["Zdravo ", {"$": "name"}]
+ # The leaf that kept its placeables is still refined.
+ assert body["properties"]["title"] == ["Pozdravilo"]
+
+
+@pytest.mark.django_db
+def test_refine_allows_reordered_placeables(
+ member, fluent_resource, locale_a, openai_api_key
+):
+ """Languages reorder variables, so only the multiset has to match."""
+ cache.clear()
+ entity = EntityFactory(
+ resource=fluent_resource,
+ string="progress = { $count } of { $total }\n .title = Progress\n",
+ )
+ composed = {
+ "value": [{"$": "count"}, " od ", {"$": "total"}],
+ "properties": {"title": ["Napredek"]},
+ }
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response({"value": "{ $total } za { $count }"})
+ response = refine(member.client, entity, locale_a, composed)
+
+ assert json.loads(response.content)["value"] == [
+ {"$": "total"},
+ " za ",
+ {"$": "count"},
+ ]
+
+
+def test_placeables_survived_ignores_detail_the_syntax_drops():
+ """A number-annotated variable serializes to plain `{ $count }`."""
+ from moz.l10n.formats import Format
+ from moz.l10n.message import message_from_json
+
+ from pontoon.machinery.composed_refine import placeables_survived
+
+ current = message_from_json([{"$": "count", "fn": "number"}, " oken"]).pattern
+ refined = message_from_json([{"$": "count"}, " okno"]).pattern
+ assert placeables_survived(refined, current, Format.fluent)
+
+
+@pytest.mark.django_db
+@pytest.mark.parametrize(
+ "reply",
+ [
+ "{ $count } oken", # NUMBER() removed
+ "{ DATETIME($count) } oken", # function changed
+ "{ NUMBER($count, minimumFractionDigits: 2) } oken", # options added
+ ],
+)
+def test_refine_rejects_a_reply_that_changes_a_function(
+ member, fluent_resource, locale_a, openai_api_key, reply
+):
+ """`{ NUMBER($count) }` and `{ $count }` are not the same placeable."""
+ cache.clear()
+ entity = EntityFactory(
+ resource=fluent_resource,
+ string="popups = { NUMBER($count) } popups\n .title = Popups\n",
+ )
+ composed = {
+ "value": [
+ {"$": "count", "fn": "number", "attr": {"fluent-fn": "NUMBER"}},
+ " oken",
+ ],
+ "properties": {"title": ["Pojavna okna"]},
+ }
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response({"value": reply, ".title": "Okna"})
+ response = refine(member.client, entity, locale_a, composed)
+
+ body = json.loads(response.content)
+ assert body["value"] == [
+ {"$": "count", "fn": "number", "attr": {"fluent-fn": "NUMBER"}},
+ " oken",
+ ]
+ assert body["properties"]["title"] == ["Okna"]
+
+
+@pytest.mark.django_db
+def test_refine_rejects_a_reply_that_changes_a_term_option(
+ member, fluent_resource, locale_a, openai_api_key
+):
+ cache.clear()
+ entity = EntityFactory(
+ resource=fluent_resource,
+ string='install = Install { -brand(case: "acc") }\n .title = Install\n',
+ )
+ term = {"_": "-brand", "fn": "message", "opt": {"case": "acc"}}
+ composed = {
+ "value": ["Namesti ", term],
+ "properties": {"title": ["Namesti"]},
+ }
+
+ with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
+ create = MockOpenAI.return_value.chat.completions.create
+ create.return_value = gpt_response(
+ {"value": 'Namestite { -brand(case: "nom") }'}
+ )
+ response = refine(member.client, entity, locale_a, composed)
+
+ assert json.loads(response.content)["value"] == ["Namesti ", term]
diff --git a/pontoon/machinery/urls.py b/pontoon/machinery/urls.py
index 841eda082b..30dde69ab4 100644
--- a/pontoon/machinery/urls.py
+++ b/pontoon/machinery/urls.py
@@ -26,6 +26,11 @@
views.openai_chatgpt,
name="pontoon.openai_chatgpt",
),
+ path(
+ "openai-chatgpt-composed/",
+ views.openai_chatgpt_composed,
+ name="pontoon.openai_chatgpt_composed",
+ ),
path(
"microsoft-translator/",
views.microsoft_translator,
diff --git a/pontoon/machinery/utils.py b/pontoon/machinery/utils.py
index 563fdafd45..fe823d10d1 100644
--- a/pontoon/machinery/utils.py
+++ b/pontoon/machinery/utils.py
@@ -23,8 +23,10 @@
from django.core.exceptions import ImproperlyConfigured
from django.db.models import Q
from django.db.models.functions import JSONObject
+from django.utils.html import strip_tags
from pontoon.base.models import (
+ Comment,
Entity,
Locale,
Project,
@@ -33,6 +35,7 @@
)
from pontoon.base.placeables import get_placeables
from pontoon.base.utils import get_search_phrases
+from pontoon.terminology.models import Term
log = logging.getLogger(__name__)
@@ -65,6 +68,42 @@ def get_llm_string_id(entity: Entity) -> str | None:
return ".".join(key) or None
+def get_llm_entity_context(entity: Entity, locale: Locale, source_text: str) -> dict:
+ """
+ Context passed to the LLM alongside the text to translate.
+
+ Values are `None` rather than empty when absent, because `OpenAIService` omits
+ a section from the prompt entirely unless it has something to say.
+
+ :param source_text: The English text terminology is matched against.
+ """
+ pinned = [
+ stripped
+ for content in Comment.objects.filter(entity=entity, pinned=True).values_list(
+ "content", flat=True
+ )
+ if (stripped := strip_tags(content).strip())
+ ]
+
+ terms = [
+ {
+ "text": term.text,
+ "part_of_speech": term.part_of_speech,
+ "translation": term.translation(locale),
+ }
+ for term in Term.objects.for_string(source_text)
+ ]
+
+ return {
+ "entity_key": get_llm_string_id(entity),
+ "entity_comment": entity.comment or None,
+ "group_comment": (entity.section.comment if entity.section else None) or None,
+ "resource_comment": entity.resource.comment or None,
+ "pinned_comments": pinned or None,
+ "terms": terms or None,
+ }
+
+
def get_google_translate_data(text, locale, format="text", preserve_placeables=False):
translation = (
get_google_automl_translation(text, locale, format, preserve_placeables)
diff --git a/pontoon/machinery/views.py b/pontoon/machinery/views.py
index 09735e79c6..e4e1dbd66a 100644
--- a/pontoon/machinery/views.py
+++ b/pontoon/machinery/views.py
@@ -7,7 +7,8 @@
import requests
-from moz.l10n.message import message_to_json
+from moz.l10n.message import message_from_json, message_to_json
+from moz.l10n.model import Entry
from sacremoses import MosesDetokenizer
from django.conf import settings
@@ -16,25 +17,42 @@
from django.http import JsonResponse
from django.template.loader import get_template
from django.utils.datastructures import MultiValueDictKeyError
-from django.utils.html import strip_tags
from django.views.decorators.http import require_POST
-from pontoon.base.models import Comment, Entity, Locale, Project, Translation
+from pontoon.base.models import Entity, Locale, Project, Translation
+from pontoon.machinery.composed_refine import (
+ has_translatable_text,
+ is_accesskey,
+ iter_leaves,
+ placeables_survived,
+)
from pontoon.machinery.utils import (
get_concordance_search_data,
get_google_translate_data,
- get_llm_string_id,
+ get_llm_entity_context,
get_microsoft_translator_data,
get_translation_memory_data,
)
-from pontoon.pretranslation.pretranslate import MTEngine, Pretranslation
-from pontoon.terminology.models import Term
+from pontoon.pretranslation.pretranslate import (
+ MTEngine,
+ Pretranslation,
+ message_format,
+ pattern_as_context,
+ pattern_as_text,
+ pattern_from_text,
+ set_accesskey,
+)
from .openai_service import OpenAIService
log = logging.getLogger(__name__)
+# One prompt holds every part of an entity, so an entity with an implausible
+# number of variants would otherwise turn one request into an arbitrarily
+# large one.
+MAX_COMPOSED_LEAVES = 50
+
def _machinery_error_response(service_name, e):
log.error(f"{service_name} error: {e}")
@@ -278,6 +296,42 @@ def _parse_references(raw):
return references
+def _llm_trigger_error(trigger, locale_code):
+ """Automatic requests are restricted to
+ `settings.OPENAI_AUTO_SUGGESTION_LOCALES`, so spend stays bounded by the
+ locales they were enabled for."""
+ if trigger not in ("auto", "manual"):
+ return JsonResponse(
+ {"status": False, "message": f"Bad Request: unknown trigger `{trigger}`"},
+ status=400,
+ )
+ if trigger == "auto" and locale_code not in settings.OPENAI_AUTO_SUGGESTION_LOCALES:
+ return JsonResponse(
+ {
+ "status": False,
+ "message": "Automatic LLM suggestions are not enabled for this locale",
+ },
+ status=403,
+ )
+ return None
+
+
+def _log_llm_suggestion(trigger, locale, characteristic, started, result, **extra):
+ """A flat line rather than `extra`, which the console handler's default
+ formatter would drop, and `key=value` because Cloud Logging parses it into a
+ metric. One line per suggestion, so the metric counts suggestions, not calls.
+ """
+ duration_ms = round((time.monotonic() - started) * 1000)
+ fields = "".join(f" {key}={value}" for key, value in extra.items())
+ log.info(
+ f"llm_suggestion trigger={trigger} locale={locale.code} "
+ f"characteristic={characteristic} "
+ f"cache_hit={'true' if result.cache_hit else 'false'} "
+ f"duration_ms={duration_ms} prompt_tokens={result.prompt_tokens or ''} "
+ f"completion_tokens={result.completion_tokens or ''}{fields}"
+ )
+
+
@require_POST
@login_required(redirect_field_name="", login_url="/403")
def openai_chatgpt(request):
@@ -292,9 +346,7 @@ def openai_chatgpt(request):
reference dropped entirely, without changing the request shape.
`trigger` is `auto` for suggestions generated automatically by the Machinery
- panel, and `manual` for those requested from the AI dropdown. Automatic
- requests are restricted to `settings.OPENAI_AUTO_SUGGESTION_LOCALES`, so that
- spend stays bounded by the locales they were enabled for.
+ panel, and `manual` for those requested from the AI dropdown.
"""
try:
english_text = request.POST.get("english_text")
@@ -310,63 +362,18 @@ def openai_chatgpt(request):
{"status": False, "message": f"Bad Request: {e}"}, status=400
)
- if trigger not in ("auto", "manual"):
- return JsonResponse(
- {
- "status": False,
- "message": f"Bad Request: unknown trigger `{trigger}`",
- },
- status=400,
- )
-
- if (
- trigger == "auto"
- and locale_code not in settings.OPENAI_AUTO_SUGGESTION_LOCALES
- ):
- return JsonResponse(
- {
- "status": False,
- "message": "Automatic LLM suggestions are not enabled for this locale",
- },
- status=403,
- )
+ error = _llm_trigger_error(trigger, locale_code)
+ if error is not None:
+ return error
locale = Locale.objects.get(code=locale_code)
- entity_key = None
- entity_comment = None
- group_comment = None
- resource_comment = None
- pinned_comments = None
- terms = None
-
+ context = {}
if entity_pk:
entity = Entity.objects.select_related("resource", "section").get(
pk=entity_pk
)
- entity_key = get_llm_string_id(entity)
- entity_comment = entity.comment or None
- group_comment = (entity.section.comment if entity.section else None) or None
- resource_comment = entity.resource.comment or None
-
- pinned = [
- stripped
- for content in Comment.objects.filter(
- entity=entity, pinned=True
- ).values_list("content", flat=True)
- if (stripped := strip_tags(content).strip())
- ]
- pinned_comments = pinned if pinned else None
-
- terms_list = [
- {
- "text": term.text,
- "part_of_speech": term.part_of_speech,
- "translation": term.translation(locale),
- }
- for term in Term.objects.for_string(english_text)
- ]
- terms = terms_list if terms_list else None
+ context = get_llm_entity_context(entity, locale, english_text)
service = OpenAIService()
started = time.monotonic()
@@ -375,33 +382,165 @@ def openai_chatgpt(request):
references,
characteristic,
locale,
- entity_key=entity_key,
- entity_comment=entity_comment,
- group_comment=group_comment,
- resource_comment=resource_comment,
- pinned_comments=pinned_comments,
- terms=terms,
- )
- duration_ms = round((time.monotonic() - started) * 1000)
- cache_hit = "true" if result.cache_hit else "false"
- prompt_tokens = result.prompt_tokens or ""
- completion_tokens = result.completion_tokens or ""
- # Logged as a single flat line rather than through `extra`, because the
- # console handler uses the default formatter, which would drop the extra
- # fields. Parsed into a log-based metric in Cloud Logging, so the
- # `key=value` shape matters.
- log.info(
- f"llm_suggestion trigger={trigger} locale={locale.code} "
- f"characteristic={characteristic} cache_hit={cache_hit} "
- f"duration_ms={duration_ms} prompt_tokens={prompt_tokens} "
- f"completion_tokens={completion_tokens}"
+ **context,
)
+ _log_llm_suggestion(trigger, locale, characteristic, started, result)
return JsonResponse({"translation": result.text})
except Exception as e:
return _machinery_error_response("OpenAI ChatGPT", e)
+@require_POST
+@login_required(redirect_field_name="", login_url="/403")
+def openai_chatgpt_composed(request):
+ """
+ Refine a composed multi-value translation using GPT.
+
+ Each leaf is refined against the English it came from, all in one request.
+
+ POST params:
+ entity_pk: Entity pk
+ locale: Locale code
+ characteristic: `rephrased`, `formal` or `informal`
+ value, properties: The composed translation to refine, as the
+ `(value, properties)` data model that `machinery-composed/` returned.
+ trigger: `auto` for suggestions generated automatically by the Machinery
+ panel, `manual` for those requested from the AI dropdown.
+
+ Returns the refined `(value, properties)`, or `{}` when the suggestion has no
+ refinable text.
+ """
+ try:
+ characteristic = request.POST.get("characteristic")
+ locale_code = request.POST.get("locale")
+ trigger = request.POST.get("trigger", "manual")
+
+ try:
+ entity_pk = int(request.POST["entity_pk"])
+ target_value = message_from_json(json.loads(request.POST["value"]))
+ target_properties = {
+ key: message_from_json(prop)
+ for key, prop in json.loads(
+ request.POST.get("properties") or "{}"
+ ).items()
+ }
+ except (KeyError, TypeError, ValueError) as e:
+ return JsonResponse(
+ {"status": False, "message": f"Bad Request: {e}"}, status=400
+ )
+
+ error = _llm_trigger_error(trigger, locale_code)
+ if error is not None:
+ return error
+
+ locale = Locale.objects.get(code=locale_code)
+ entity = Entity.objects.select_related("resource", "section").get(pk=entity_pk)
+
+ source_value = message_from_json(entity.value)
+ source_properties = {
+ key: message_from_json(prop)
+ for key, prop in (entity.properties or {}).items()
+ }
+
+ # A leaf is sent as the format's own syntax, the same text a translator
+ # reads, and the reply is parsed back the way a Translation Memory match
+ # is. A leaf whose format cannot express its placeholders as text is left
+ # alone rather than sent as something that cannot be read back.
+ fmt = message_format(entity.resource.format)
+ payload = []
+ leaves = {}
+ for leaf in iter_leaves(
+ source_value, source_properties, target_value, target_properties
+ ):
+ if not has_translatable_text(leaf.target):
+ continue
+ current = pattern_as_text(leaf.target, fmt)
+ # Fluent's inline form cannot express a line break, so a leaf
+ # carrying one could not be read back and is left alone.
+ if current is None or "\n" in current:
+ continue
+ # The English is only shown, so it does not have to be readable back.
+ source_text = pattern_as_context(leaf.source, fmt)
+ payload.append({"id": leaf.id, "source": source_text, "current": current})
+ leaves[leaf.id] = leaf
+
+ if not payload:
+ return JsonResponse({})
+ if len(payload) > MAX_COMPOSED_LEAVES:
+ return JsonResponse(
+ {
+ "status": False,
+ "message": f"Bad Request: more than {MAX_COMPOSED_LEAVES} parts",
+ },
+ status=400,
+ )
+
+ # Terminology is matched against the leaf sources rather than
+ # `entity.string`, whose serialization would match terms against the
+ # message id and property names too.
+ source_texts = "\n".join(part["source"] for part in payload)
+ context = get_llm_entity_context(entity, locale, source_texts)
+
+ service = OpenAIService()
+ started = time.monotonic()
+ result = service.get_composed_translation(
+ payload,
+ characteristic,
+ locale,
+ **context,
+ )
+
+ applied = 0
+ for part in payload:
+ text = result.leaves.get(part["id"])
+ if text is None or "\n" in text:
+ continue
+ leaf = leaves[part["id"]]
+ try:
+ pattern = pattern_from_text(text, fmt)
+ except Exception:
+ # A reply that does not parse leaves its leaf as it was.
+ continue
+ if not placeables_survived(pattern, leaf.target, fmt):
+ continue
+ leaf.target[:] = pattern
+ applied += 1
+
+ # Derived rather than translated, so they were left out of the request.
+ entry = Entry(
+ id=tuple(entity.key), value=target_value, properties=target_properties
+ )
+ for key, prop in target_properties.items():
+ if is_accesskey(key):
+ set_accesskey(entry, key, prop)
+
+ _log_llm_suggestion(
+ trigger,
+ locale,
+ characteristic,
+ started,
+ result,
+ composed="true",
+ leaves=len(payload),
+ refined=applied,
+ rejected=len(result.leaves) - applied,
+ )
+
+ return JsonResponse(
+ {
+ "value": message_to_json(target_value),
+ "properties": {
+ key: message_to_json(prop)
+ for key, prop in target_properties.items()
+ },
+ }
+ )
+
+ except Exception as e:
+ return _machinery_error_response("OpenAI ChatGPT (composed)", e)
+
+
def caighdean(request):
"""Get translation from Caighdean machine translation service."""
try:
diff --git a/pontoon/pretranslation/pretranslate.py b/pontoon/pretranslation/pretranslate.py
index d2f4c670b8..816e309cf8 100644
--- a/pontoon/pretranslation/pretranslate.py
+++ b/pontoon/pretranslation/pretranslate.py
@@ -66,6 +66,66 @@ def service(self) -> MTService:
return get_microsoft_translator_data
+def message_format(resource_format: str) -> Format | None:
+ """The `moz.l10n` model a resource's messages are parsed into."""
+ match resource_format:
+ case Resource.Format.FLUENT:
+ return Format.fluent
+ case (
+ Resource.Format.ANDROID
+ | Resource.Format.GETTEXT
+ | Resource.Format.WEBEXT
+ | Resource.Format.XCODE
+ | Resource.Format.XLIFF
+ ):
+ return Format.mf2
+ case _:
+ return None
+
+
+def pattern_as_text(pattern: Pattern, format: Format | None) -> str | None:
+ """Serialize a pattern to the text a translator reads and types.
+
+ `None` when the format has no round-trippable text for a pattern holding
+ placeholders, so a caller that needs to read the text back can skip it
+ rather than send something it cannot parse.
+ """
+ if format == Format.fluent:
+ return "".join(
+ el.value if isinstance(el, FTL.TextElement) else serialize_expression(el)
+ for el in fluent_astify_message(
+ PatternMessage(pattern), escape_syntax=False
+ ).elements
+ )
+ return "".join(pattern) if all(isinstance(el, str) for el in pattern) else None
+
+
+def pattern_as_context(pattern: Pattern, format: Format | None) -> str:
+ """Text for a pattern that is only shown to a model, never read back.
+
+ Unlike `pattern_as_text`, a format whose placeholders have no
+ round-trippable syntax still gets something readable: each placeholder is
+ rendered as the source text it was parsed from, which is what a translator
+ sees in the file.
+ """
+ text = pattern_as_text(pattern, format)
+ if text is not None:
+ return text
+ return "".join(
+ el if isinstance(el, str) else el.attributes.get("source", "") or ""
+ for el in pattern
+ )
+
+
+def pattern_from_text(text: str, format: Format | None) -> Pattern:
+ """Parse text back into a pattern, the way a Translation Memory match is parsed."""
+ if format == Format.fluent:
+ msg = fluent_parse_message(text)
+ assert isinstance(msg, PatternMessage)
+ return msg.pattern
+ return [text]
+
+
def get_pretranslation(
entity: Entity, locale: Locale, preserve_placeables: bool = False
) -> tuple[str, Literal["gt", "tm"]]:
@@ -116,19 +176,7 @@ def __init__(
current entity. Defaults to False.
"""
self.entity = entity
- match entity.resource.format:
- case Resource.Format.FLUENT:
- self.format = Format.fluent
- case (
- Resource.Format.ANDROID
- | Resource.Format.GETTEXT
- | Resource.Format.WEBEXT
- | Resource.Format.XCODE
- | Resource.Format.XLIFF
- ):
- self.format = Format.mf2
- case _:
- self.format = None
+ self.format = message_format(entity.resource.format)
self.source = entity.string
self.locale = locale
self.preserve_placeables = preserve_placeables
@@ -240,14 +288,7 @@ def message(self, msg: Message) -> None:
def pattern(self, pattern: Pattern) -> Pattern:
# First try to get a 100% match from Translation Memory
tm_source = (
- "".join(
- el.value
- if isinstance(el, FTL.TextElement)
- else serialize_expression(el)
- for el in fluent_astify_message(
- PatternMessage(pattern), escape_syntax=False
- ).elements
- )
+ pattern_as_text(pattern, self.format)
if self.format == Format.fluent
else self.source
)
@@ -262,12 +303,7 @@ def pattern(self, pattern: Pattern) -> Pattern:
if tm_q100:
tm_best = max(set(tm_q100), key=tm_q100.count)
self.services.append("tm")
- if self.format == Format.fluent:
- msg = fluent_parse_message(tm_best)
- assert isinstance(msg, PatternMessage)
- return msg.pattern
- else:
- return [tm_best]
+ return pattern_from_text(tm_best, self.format)
placeholders: list[Expression | Markup] = []
gt_source = ""
diff --git a/translate/public/locale/en-US/translate.ftl b/translate/public/locale/en-US/translate.ftl
index daebcade69..93c6b8287f 100644
--- a/translate/public/locale/en-US/translate.ftl
+++ b/translate/public/locale/en-US/translate.ftl
@@ -587,17 +587,21 @@ machinery-ConcordanceSearch--translation-memory = TRANSLATION MEMORY
## Machinery Google Translation
## Shows the translation source from Google Translate.
machinery-GoogleTranslation--translation-source = GOOGLE TRANSLATE
-machinery-GoogleTranslation--selector =
+
+
+## Machinery AI Refine
+## The dropdown that refines a Machinery suggestion using AI.
+machinery-AIRefine--selector =
.title = Refine using AI
-machinery-GoogleTranslation--dropdown-title = AI
-
-machinery-GoogleTranslation--option-rephrase = REPHRASE
-machinery-GoogleTranslation--option-rephrased = REPHRASED
-machinery-GoogleTranslation--option-make-formal = MAKE FORMAL
-machinery-GoogleTranslation--option-formal = FORMAL
-machinery-GoogleTranslation--option-make-informal = MAKE INFORMAL
-machinery-GoogleTranslation--option-informal = INFORMAL
-machinery-GoogleTranslation--option-show-original = SHOW ORIGINAL
+machinery-AIRefine--dropdown-title = AI
+
+machinery-AIRefine--option-rephrase = REPHRASE
+machinery-AIRefine--option-rephrased = REPHRASED
+machinery-AIRefine--option-make-formal = MAKE FORMAL
+machinery-AIRefine--option-formal = FORMAL
+machinery-AIRefine--option-make-informal = MAKE INFORMAL
+machinery-AIRefine--option-informal = INFORMAL
+machinery-AIRefine--option-show-original = SHOW ORIGINAL
## Machinery OpenAI Translation
diff --git a/translate/public/locale/kab/translate.ftl b/translate/public/locale/kab/translate.ftl
index 96bdf65e6c..0e76126a26 100644
--- a/translate/public/locale/kab/translate.ftl
+++ b/translate/public/locale/kab/translate.ftl
@@ -440,16 +440,20 @@ machinery-ConcordanceSearch--translation-memory = TAKATUT N TSUQILT
## Shows the translation source from Google Translate.
machinery-GoogleTranslation--translation-source = GOOGLE TRANSLATE
-machinery-GoogleTranslation--selector =
+
+
+## Machinery AI Refine
+## The dropdown that refines a Machinery suggestion using AI.
+machinery-AIRefine--selector =
.title = Refine using AI
-machinery-GoogleTranslation--dropdown-title = AI
-machinery-GoogleTranslation--option-rephrase = REPHRASE
-machinery-GoogleTranslation--option-rephrased = REPHRASED
-machinery-GoogleTranslation--option-make-formal = ERR D ALƔAWAN
-machinery-GoogleTranslation--option-formal = ALƔAW
-machinery-GoogleTranslation--option-make-informal = ERR-IT D ARALƔAWAN
-machinery-GoogleTranslation--option-informal = ARALƔAWAN
-machinery-GoogleTranslation--option-show-original = SKEN AƔBALU
+machinery-AIRefine--dropdown-title = AI
+machinery-AIRefine--option-rephrase = REPHRASE
+machinery-AIRefine--option-rephrased = REPHRASED
+machinery-AIRefine--option-make-formal = ERR D ALƔAWAN
+machinery-AIRefine--option-formal = ALƔAW
+machinery-AIRefine--option-make-informal = ERR-IT D ARALƔAWAN
+machinery-AIRefine--option-informal = ARALƔAWAN
+machinery-AIRefine--option-show-original = SKEN AƔBALU
## Machinery Microsoft Translation
## Shows the translation source from Microsoft Translation.
diff --git a/translate/public/locale/sv-SE/translate.ftl b/translate/public/locale/sv-SE/translate.ftl
index 158421ee94..c78d5ff588 100644
--- a/translate/public/locale/sv-SE/translate.ftl
+++ b/translate/public/locale/sv-SE/translate.ftl
@@ -519,17 +519,21 @@ machinery-ConcordanceSearch--translation-memory = ÖVERSÄTTNINGSMINNE
## Machinery Google Translation
## Shows the translation source from Google Translate.
machinery-GoogleTranslation--translation-source = GOOGLE TRANSLATE
-machinery-GoogleTranslation--selector =
+
+
+## Machinery AI Refine
+## The dropdown that refines a Machinery suggestion using AI.
+machinery-AIRefine--selector =
.title = Förfina med hjälp av AI
-machinery-GoogleTranslation--dropdown-title = AI
-
-machinery-GoogleTranslation--option-rephrase = OMFORMULERA
-machinery-GoogleTranslation--option-rephrased = OMFORMULERAD
-machinery-GoogleTranslation--option-make-formal = GÖR FORMELL
-machinery-GoogleTranslation--option-formal = FORMELL
-machinery-GoogleTranslation--option-make-informal = GÖR INFORMELL
-machinery-GoogleTranslation--option-informal = INFORMELL
-machinery-GoogleTranslation--option-show-original = VISA ORIGINAL
+machinery-AIRefine--dropdown-title = AI
+
+machinery-AIRefine--option-rephrase = OMFORMULERA
+machinery-AIRefine--option-rephrased = OMFORMULERAD
+machinery-AIRefine--option-make-formal = GÖR FORMELL
+machinery-AIRefine--option-formal = FORMELL
+machinery-AIRefine--option-make-informal = GÖR INFORMELL
+machinery-AIRefine--option-informal = INFORMELL
+machinery-AIRefine--option-show-original = VISA ORIGINAL
## Machinery Microsoft Translation
diff --git a/translate/src/api/machinery.test.ts b/translate/src/api/machinery.test.ts
index f6ea7e572c..e9cdcde5ef 100644
--- a/translate/src/api/machinery.test.ts
+++ b/translate/src/api/machinery.test.ts
@@ -1,6 +1,10 @@
import type { Locale } from '~/context/Locale';
-import { fetchComposedMachinery, fetchOpenAITranslation } from './machinery';
+import {
+ fetchComposedMachinery,
+ fetchOpenAIComposedTranslation,
+ fetchOpenAITranslation,
+} from './machinery';
import * as base from './utils/base';
vi.mock('./utils/base', () => ({
@@ -178,3 +182,85 @@ describe('fetchComposedMachinery', () => {
expect(result[0].sources).toEqual(['microsoft-translator']);
});
});
+
+describe('fetchOpenAIComposedTranslation', () => {
+ const POST = vi.mocked(base.POST);
+ const value = ['Hola'];
+ const properties = { title: ['Sugerencia'] };
+ const refined = { value: ['Saludos'], properties: { title: ['Refinada'] } };
+
+ beforeEach(() => {
+ POST.mockResolvedValue(refined);
+ });
+
+ it('sends the whole composed model', async () => {
+ await fetchOpenAIComposedTranslation(42, value, properties, 'formal', 'es');
+
+ const [url, params] = POST.mock.calls[0] as [string, URLSearchParams];
+ expect(url).toBe('/openai-chatgpt-composed/');
+ expect(params.get('entity_pk')).toBe('42');
+ expect(params.get('value')).toBe(JSON.stringify(value));
+ expect(params.get('properties')).toBe(JSON.stringify(properties));
+ expect(params.get('characteristic')).toBe('formal');
+ expect(params.get('locale')).toBe('es');
+ expect(params.get('trigger')).toBe('manual');
+ expect(params.get('csrfmiddlewaretoken')).toBe('test-csrf-token');
+ });
+
+ it('sends an empty object for an entity without properties', async () => {
+ await fetchOpenAIComposedTranslation(42, value, undefined, 'formal', 'es');
+
+ const [, params] = POST.mock.calls[0] as [string, URLSearchParams];
+ expect(params.get('properties')).toBe('{}');
+ });
+
+ it('passes the automatic trigger through', async () => {
+ await fetchOpenAIComposedTranslation(
+ 42,
+ value,
+ properties,
+ 'rephrased',
+ 'es',
+ 'auto',
+ );
+
+ const [, params] = POST.mock.calls[0] as [string, URLSearchParams];
+ expect(params.get('trigger')).toBe('auto');
+ });
+
+ it('returns the refined model', async () => {
+ const result = await fetchOpenAIComposedTranslation(
+ 42,
+ value,
+ properties,
+ 'formal',
+ 'es',
+ );
+ expect(result).toEqual(refined);
+ });
+
+ it('returns null when there was nothing to refine', async () => {
+ POST.mockResolvedValueOnce({});
+ const result = await fetchOpenAIComposedTranslation(
+ 42,
+ value,
+ properties,
+ 'formal',
+ 'es',
+ );
+ expect(result).toBeNull();
+ });
+
+ it('returns null when the request fails', async () => {
+ POST.mockRejectedValueOnce(new Error('boom'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const result = await fetchOpenAIComposedTranslation(
+ 42,
+ value,
+ properties,
+ 'formal',
+ 'es',
+ );
+ expect(result).toBeNull();
+ });
+});
diff --git a/translate/src/api/machinery.ts b/translate/src/api/machinery.ts
index 5a0b236b48..701922a4a4 100644
--- a/translate/src/api/machinery.ts
+++ b/translate/src/api/machinery.ts
@@ -270,6 +270,46 @@ export async function fetchOpenAITranslation(
}
}
+/**
+ * Return a composed multi-value translation refined by OpenAI ChatGPT.
+ *
+ * `null` when the suggestion has nothing refinable, or the request fails.
+ */
+export async function fetchOpenAIComposedTranslation(
+ entityPk: number,
+ value: Message,
+ properties: Record
+ +
+ ) : suggestionFields ? (