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 | undefined, + characteristic: string, + localeCode: string, + trigger: 'auto' | 'manual' = 'manual', +): Promise | null> { + const url = '/openai-chatgpt-composed/'; + const payload = new URLSearchParams({ + csrfmiddlewaretoken: getCSRFToken(), + entity_pk: String(entityPk), + value: JSON.stringify(value), + properties: JSON.stringify(properties ?? {}), + characteristic: characteristic, + locale: localeCode, + trigger: trigger, + }); + + try { + const result = (await POST(url, payload, { + signal: abortController.signal, + })) as { + value?: Message; + properties?: Record; + }; + return result?.value + ? { value: result.value, properties: result.properties } + : null; + } catch (error) { + console.error('Error fetching OpenAI ChatGPT composed translation:', error); + return null; + } +} + /** * Return translation by Microsoft Translator. */ diff --git a/translate/src/context/MachineryTranslations.test.jsx b/translate/src/context/MachineryTranslations.test.jsx index 2598a5ed56..6a10ea6f0f 100644 --- a/translate/src/context/MachineryTranslations.test.jsx +++ b/translate/src/context/MachineryTranslations.test.jsx @@ -17,6 +17,7 @@ vi.mock('~/api/machinery', () => ({ fetchCaighdeanTranslation: vi.fn(() => Promise.resolve([])), fetchComposedMachinery: vi.fn(() => Promise.resolve([])), fetchGoogleTranslation: vi.fn(() => Promise.resolve([])), + fetchOpenAIComposedTranslation: vi.fn(() => Promise.resolve(null)), fetchOpenAITranslation: vi.fn(() => Promise.resolve([])), fetchMicrosoftTranslation: vi.fn(() => Promise.resolve([])), fetchTranslationMemory: vi.fn(() => Promise.resolve([])), @@ -201,3 +202,228 @@ describe(' automatic LLM suggestions', () => { ); }); }); + +describe(' automatic composed LLM suggestions', () => { + // Two leaves, so `hasMultipleFields()` asks for a composed suggestion. + const multiFieldEntity = (translation) => ({ + ...entityOf(translation), + format: 'fluent', + properties: { title: ['Tooltip'] }, + }); + + const COMPOSED_GT = [ + { + sources: ['google-translate'], + value: ['Hola'], + properties: { title: ['Sugerencia'] }, + }, + ]; + + function ComposedConsumer() { + const { composed } = useContext(MachineryTranslations); + return ( + + {composed.map((t) => t.sources.join('+')).join(',')} + + ); + } + + const mountComposed = (entity) => + render( + + + + + + + + + , + ); + + beforeEach(() => { + vi.clearAllMocks(); + api.fetchGoogleTranslation.mockResolvedValue(GT_RESULT); + api.fetchComposedMachinery.mockImplementation((_pk, _locale, service) => + Promise.resolve(service === 'google-translate' ? COMPOSED_GT : []), + ); + }); + + it('refines the Google-Translate-backed composition', async () => { + setRootFlags({ enabled: true }); + api.fetchOpenAIComposedTranslation.mockResolvedValue({ + value: ['Saludos'], + properties: { title: ['Refinada'] }, + }); + + const { getByTestId } = mountComposed(multiFieldEntity(undefined)); + + await waitFor(() => + expect(api.fetchOpenAIComposedTranslation).toHaveBeenCalled(), + ); + + const [pk, value, properties, characteristic, code, trigger] = + api.fetchOpenAIComposedTranslation.mock.calls[0]; + expect(pk).toBe(42); + expect(value).toEqual(['Hola']); + expect(properties).toEqual({ title: ['Sugerencia'] }); + expect(characteristic).toBe('rephrased'); + expect(code).toBe('es'); + expect(trigger).toBe('auto'); + + await waitFor(() => + expect(getByTestId('composed').textContent).toBe( + 'google-translate,openai-chatgpt', + ), + ); + }); + + it('replaces the single-string suggestion rather than adding to it', async () => { + // One automatic call per string: refining the flattened string would only + // ever fill the focused field. + setRootFlags({ enabled: true }); + api.fetchOpenAIComposedTranslation.mockResolvedValue({ + value: ['Saludos'], + properties: { title: ['Refinada'] }, + }); + + mountComposed(multiFieldEntity(undefined)); + + await waitFor(() => + expect(api.fetchOpenAIComposedTranslation).toHaveBeenCalled(), + ); + expect(api.fetchOpenAITranslation).not.toHaveBeenCalled(); + }); + + it('merges the sources when the LLM returns the composition unchanged', async () => { + setRootFlags({ enabled: true }); + api.fetchOpenAIComposedTranslation.mockResolvedValue({ + value: ['Hola'], + properties: { title: ['Sugerencia'] }, + }); + + const { getByTestId } = mountComposed(multiFieldEntity(undefined)); + + await waitFor(() => + expect(getByTestId('composed').textContent).toBe( + 'google-translate+openai-chatgpt', + ), + ); + }); + + it('skips strings that already have an approved translation', async () => { + setRootFlags({ enabled: true }); + mountComposed( + multiFieldEntity({ + pk: 1, + status: 'approved', + string: 'Hola', + value: ['Hola'], + }), + ); + + await waitFor(() => expect(api.fetchComposedMachinery).toHaveBeenCalled()); + expect(api.fetchOpenAIComposedTranslation).not.toHaveBeenCalled(); + }); + + it('skips locales it is not enabled for', async () => { + setRootFlags({ enabled: false }); + mountComposed(multiFieldEntity(undefined)); + + await waitFor(() => expect(api.fetchComposedMachinery).toHaveBeenCalled()); + expect(api.fetchOpenAIComposedTranslation).not.toHaveBeenCalled(); + }); + + it('skips single-field entities, which have no composition to refine', async () => { + setRootFlags({ enabled: true }); + mountComposed(entityOf(undefined)); + + await waitFor(() => expect(api.fetchGoogleTranslation).toHaveBeenCalled()); + expect(api.fetchComposedMachinery).not.toHaveBeenCalled(); + expect(api.fetchOpenAIComposedTranslation).not.toHaveBeenCalled(); + }); + + it('skips when the composed request returns nothing to refine', async () => { + setRootFlags({ enabled: true }); + api.fetchComposedMachinery.mockResolvedValue([]); + mountComposed(multiFieldEntity(undefined)); + + await waitFor(() => expect(api.fetchComposedMachinery).toHaveBeenCalled()); + expect(api.fetchOpenAIComposedTranslation).not.toHaveBeenCalled(); + }); + + it('skips when the user moved on before the composition resolved', async () => { + setRootFlags({ enabled: true }); + let resolveComposed; + api.fetchComposedMachinery.mockImplementation((_pk, _locale, service) => + service === 'google-translate' + ? new Promise((resolve) => { + resolveComposed = resolve; + }) + : Promise.resolve([]), + ); + + const { unmount } = mountComposed(multiFieldEntity(undefined)); + unmount(); + resolveComposed(COMPOSED_GT); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(api.fetchOpenAIComposedTranslation).not.toHaveBeenCalled(); + }); +}); + +describe(' result merging', () => { + beforeEach(() => { + vi.clearAllMocks(); + setRootFlags({ enabled: false }); + }); + + it('keeps the suggestion object when a later result merges into it', () => { + // LLM refinement state is keyed by this object in a WeakMap, so replacing + // it mid-refinement would strand the answer under a key nothing renders. + const seen = []; + + function IdentityConsumer() { + const { translations } = useContext(MachineryTranslations); + if (translations[0]) { + seen.push(translations[0]); + } + return ( + + {translations.map((t) => t.sources.join('+')).join(',')} + + ); + } + + // Translation Memory and Google Translate return the same string, so the + // two rows merge into one. + api.fetchTranslationMemory.mockResolvedValue([ + { + sources: ['translation-memory'], + original: 'Hello', + translation: 'Hola', + quality: 90, + }, + ]); + api.fetchGoogleTranslation.mockResolvedValue(GT_RESULT); + + const { getByTestId } = render( + + + + + + + + + , + ); + + return waitFor(() => { + expect(getByTestId('order').textContent).toBe( + 'translation-memory+google-translate', + ); + expect(new Set(seen).size).toBe(1); + }); + }); +}); diff --git a/translate/src/context/MachineryTranslations.tsx b/translate/src/context/MachineryTranslations.tsx index ab86491ed4..0e44550a98 100644 --- a/translate/src/context/MachineryTranslations.tsx +++ b/translate/src/context/MachineryTranslations.tsx @@ -7,10 +7,12 @@ import { fetchCaighdeanTranslation, fetchComposedMachinery, fetchGoogleTranslation, + fetchOpenAIComposedTranslation, fetchOpenAITranslation, fetchMicrosoftTranslation, fetchTranslationMemory, MachineryTranslation, + SourceType, } from '~/api/machinery'; import { USER } from '~/modules/user'; import { useAppSelector } from '~/hooks'; @@ -107,6 +109,22 @@ function composedEquals( ); } +/** + * Fold a later result's sources into the suggestion already on screen. + * + * Updated in place rather than replaced: LLM refinement state is held in a + * WeakMap keyed by the suggestion object, so a replacement would hide the + * spinner of a refinement in flight and file its answer under a key nothing + * renders any more. Deduplicated so that merging twice changes nothing. + */ +function mergeInto( + target: { sources: SourceType[]; quality?: number }, + extra: { sources: SourceType[]; quality?: number }, +): void { + target.sources = [...new Set([...target.sources, ...extra.sources])]; + target.quality ??= extra.quality; +} + export function MachineryProvider({ children, }: { @@ -142,10 +160,7 @@ export function MachineryProvider({ if (i === -1) { translations.push(tx); } else { - const t0 = translations[i]; - const sources = t0.sources.concat(tx.sources); - const quality = t0.quality ?? tx.quality; - translations[i] = { ...t0, sources, quality }; + mergeInto(translations[i], tx); } } translations.sort(sortByQuality); @@ -165,10 +180,7 @@ export function MachineryProvider({ if (i === -1) { composed.push(tx); } else { - const t0 = composed[i]; - const sources = t0.sources.concat(tx.sources); - const quality = t0.quality ?? tx.quality; - composed[i] = { ...t0, sources, quality }; + mergeInto(composed[i], tx); } } composed.sort(sortByQuality); @@ -222,13 +234,19 @@ export function MachineryProvider({ root?.dataset.isLlmAutoSuggestionLocale === 'true' && entity.translation?.status !== 'approved'; + // One automatic suggestion per string, composed where the entity has + // fields to compose: refining the flattened string would only ever fill + // the focused one, so it is the weaker of the two to spend a call on. + const wantsComposedLLMSuggestion = wantsLLMSuggestion && wantsComposed; + const wantsPlainLLMSuggestion = wantsLLMSuggestion && !wantsComposed; + if (isGoogleTranslateSupported && locale.googleTranslateCode) { promises.push( fetchGoogleTranslation(plain, locale).then(async (results) => { addResults(results); // LLM suggestion refines the Google Translate output, so it can // only be requested once that has resolved. - if (!cancelled && wantsLLMSuggestion && results.length > 0) { + if (!cancelled && wantsPlainLLMSuggestion && results.length > 0) { addResults( await fetchOpenAITranslation( plain, @@ -245,7 +263,30 @@ export function MachineryProvider({ if (wantsComposed) { promises.push( fetchComposedMachinery(pk!, locale, 'google-translate').then( - addComposed, + async (results) => { + addComposed(results); + // As for the single-string suggestion above, the LLM refines + // the composition, so it can only run once that has resolved. + if ( + !cancelled && + wantsComposedLLMSuggestion && + results.length > 0 + ) { + const refined = await fetchOpenAIComposedTranslation( + pk!, + results[0].value, + results[0].properties, + 'rephrased', + locale.code, + 'auto', + ); + if (refined) { + addComposed([ + { sources: ['openai-chatgpt'], ...refined }, + ]); + } + } + }, ), ); } diff --git a/translate/src/context/TranslationContext.tsx b/translate/src/context/TranslationContext.tsx index 50f493456d..16da7b9763 100644 --- a/translate/src/context/TranslationContext.tsx +++ b/translate/src/context/TranslationContext.tsx @@ -1,46 +1,71 @@ +import type { Message } from '@mozilla/l10n'; import React, { createContext, useContext, useState, useRef } from 'react'; import { + type ComposedMachineryTranslation, type MachineryTranslation, + fetchOpenAIComposedTranslation, fetchOpenAITranslation, } from '~/api/machinery'; +type ComposedRefinement = { + value: Message; + properties?: Record; +}; + type SelState = { loading: boolean; selectedOption: string; llmTranslation: string; + llmComposed: ComposedRefinement | null; }; +/** Object identity keys either kind in the WeakMap. */ +type Refinable = MachineryTranslation | ComposedMachineryTranslation; + interface LLMTranslationContextType { - getSelState(mt: MachineryTranslation): SelState; + getSelState(mt: Refinable): SelState; transformLLMTranslation: ( mt: MachineryTranslation, characteristic: string, localeCode: string, entityPk?: number, ) => Promise; - restoreOriginal: (mt: MachineryTranslation) => void; + transformComposedLLMTranslation: ( + ct: ComposedMachineryTranslation, + characteristic: string, + localeCode: string, + entityPk: number, + ) => Promise; + restoreOriginal: (mt: Refinable) => void; } const initSelState = () => ({ loading: false, selectedOption: '', llmTranslation: '', + llmComposed: null, }); const LLMTranslationContext = createContext({ getSelState: initSelState, transformLLMTranslation: async () => {}, + transformComposedLLMTranslation: async () => {}, restoreOriginal: () => {}, }); export const LLMTranslationProvider: React.FC = ({ children }) => { - const stateRef = useRef(new WeakMap()); + const stateRef = useRef(new WeakMap()); const [, setVersion] = useState(0); // Counter to trigger re-renders - const getSelState = (mt: MachineryTranslation): SelState => { + const getSelState = (mt: Refinable): SelState => { return stateRef.current.get(mt) ?? initSelState(); }; + const setLoading = (mt: Refinable) => { + stateRef.current.set(mt, { ...getSelState(mt), loading: true }); + setVersion((v) => v + 1); // Trigger re-render + }; + const transformLLMTranslation = async ( mt: MachineryTranslation, characteristic: string, @@ -48,11 +73,7 @@ export const LLMTranslationProvider: React.FC = ({ children }) => { entityPk?: number, ) => { const currentState = getSelState(mt); - stateRef.current.set(mt, { - ...currentState, - loading: true, - }); - setVersion((v) => v + 1); // Trigger re-render + setLoading(mt); const machineryTranslations = await fetchOpenAITranslation( mt.original, @@ -66,6 +87,7 @@ export const LLMTranslationProvider: React.FC = ({ children }) => { loading: false, selectedOption: characteristic, llmTranslation: machineryTranslations[0].translation, + llmComposed: null, }); } else { stateRef.current.set(mt, { @@ -76,18 +98,56 @@ export const LLMTranslationProvider: React.FC = ({ children }) => { setVersion((v) => v + 1); }; - const restoreOriginal = (mt: MachineryTranslation) => { + const transformComposedLLMTranslation = async ( + ct: ComposedMachineryTranslation, + characteristic: string, + localeCode: string, + entityPk: number, + ) => { + const currentState = getSelState(ct); + setLoading(ct); + + const refined = await fetchOpenAIComposedTranslation( + entityPk, + ct.value, + ct.properties, + characteristic, + localeCode, + ); + if (refined) { + stateRef.current.set(ct, { + loading: false, + selectedOption: characteristic, + llmTranslation: '', + llmComposed: refined, + }); + } else { + stateRef.current.set(ct, { + ...currentState, + loading: false, + }); + } + setVersion((v) => v + 1); + }; + + const restoreOriginal = (mt: Refinable) => { const currentState = getSelState(mt); stateRef.current.set(mt, { ...currentState, selectedOption: '', llmTranslation: '', + llmComposed: null, }); setVersion((v) => v + 1); }; return ( {children} @@ -95,13 +155,17 @@ export const LLMTranslationProvider: React.FC = ({ children }) => { }; export const useLLMTranslation = () => { - const { getSelState, transformLLMTranslation, restoreOriginal } = useContext( - LLMTranslationContext, - ); + const { + getSelState, + transformLLMTranslation, + transformComposedLLMTranslation, + restoreOriginal, + } = useContext(LLMTranslationContext); - return (mt: MachineryTranslation) => ({ + return (mt: Refinable) => ({ ...getSelState(mt), transformLLMTranslation, + transformComposedLLMTranslation, restoreOriginal, }); }; diff --git a/translate/src/modules/machinery/components/MachineryTranslation.css b/translate/src/modules/machinery/components/MachineryTranslation.css index 49179313f4..e0f208229a 100644 --- a/translate/src/modules/machinery/components/MachineryTranslation.css +++ b/translate/src/modules/machinery/components/MachineryTranslation.css @@ -57,25 +57,31 @@ cursor: default; } -.machinery .translation > header li.google-translation { +.machinery .translation > header li.ai-refine { position: relative; } +/* The AI badge reads as a button rather than as another source, so it gets no + separator; `.selected-option` supplies the gap that sets it apart instead. */ .machinery .translation > header - li.google-translation:hover - .translation-source { - color: var(--status-translated); + .sources:not(.projects) + > li.ai-refine::before { + content: none; +} + +.machinery .translation > header ul li.ai-refine { + padding-left: 0; } -.machinery .translation > header li.google-translation .selected-option { +.machinery .translation > header li.ai-refine .selected-option { margin-left: 3px; margin-right: 3px; color: var(--status-translated); } -.machinery .translation > header li.google-translation .dropdown-toggle { +.machinery .translation > header li.ai-refine .dropdown-toggle { background: var(--status-translated); border: none; border-radius: 2px; @@ -83,15 +89,19 @@ padding: 0 2px; } -.machinery .translation > header li.google-translation .dropdown-title { +.machinery .translation > header li.ai-refine .dropdown-title { padding-right: 2px; } -.machinery .translation > header li.google-translation .dropdown-menu { +/* Sized by its own content, not by the badge: the badge is only as wide as its + button, which would clip every option. Anchored right because the sources are + right-aligned, so the menu opens inward instead of off the panel edge. */ +.machinery .translation > header li.ai-refine .dropdown-menu { position: absolute; top: 100%; - left: 0; + left: auto; right: 0; + width: max-content; padding: 10px 12px; background-color: var(--black-3); border: 1px solid var(--main-border-1); @@ -100,14 +110,14 @@ list-style: none; } -.machinery .translation > header li.google-translation .dropdown-menu li { +.machinery .translation > header li.ai-refine .dropdown-menu li { padding: 2px 4px; text-align: left; display: block; white-space: nowrap; } -.machinery .translation > header li.google-translation .dropdown-menu li:hover { +.machinery .translation > header li.ai-refine .dropdown-menu li:hover { background: var(--dark-grey-2); color: var(--white-1); } @@ -115,7 +125,7 @@ .machinery .translation > header - li.google-translation + li.ai-refine .dropdown-menu li.horizontal-separator { border-top: 1px solid var(--main-border-1); diff --git a/translate/src/modules/machinery/components/MachineryTranslation.test.jsx b/translate/src/modules/machinery/components/MachineryTranslation.test.jsx index bdc704410d..8abf959c1b 100644 --- a/translate/src/modules/machinery/components/MachineryTranslation.test.jsx +++ b/translate/src/modules/machinery/components/MachineryTranslation.test.jsx @@ -1,6 +1,10 @@ import React from 'react'; +import { act, fireEvent, screen } from '@testing-library/react'; +import { vi } from 'vitest'; +import * as machineryApi from '~/api/machinery'; import { EntityView } from '~/context/EntityView'; +import { LLMTranslationProvider } from '~/context/TranslationContext'; import { createDefaultUser, createReduxStore, @@ -158,4 +162,152 @@ describe('', () => { expect(suggestion.textContent).toContain('Un popup'); expect(suggestion.textContent).toContain('Des popups'); }); + describe('AI refinement', () => { + const ENTITY = { + pk: 42, + format: 'fluent', + key: ['button'], + value: ['Click Me'], + properties: { title: ['Tooltip'] }, + }; + const COMPOSED = { + sources: ['translation-memory', 'google-translate'], + value: ['Cliquez'], + properties: { title: ['Infobulle'] }, + }; + + let root; + + beforeEach(() => { + root = document.createElement('div'); + root.id = 'root'; + root.dataset.isOpenaiChatgptSupported = 'true'; + document.body.appendChild(root); + }); + + afterEach(() => { + root.remove(); + vi.restoreAllMocks(); + }); + + function mountComposed(translation = COMPOSED, entity = ENTITY) { + const store = createReduxStore(); + const Wrapped = (props) => ( + + + + + + ); + const result = mountComponentWithStore(Wrapped, store, { + index: 0, + translation, + }); + createDefaultUser(store); + return result; + } + + it('offers the AI dropdown on a composed suggestion', () => { + const { container } = mountComposed(); + const sources = container.querySelector('ul.sources'); + expect(sources.lastElementChild).toHaveClass('ai-refine'); + }); + + it('does not offer to refine a suggestion that is already LLM output', () => { + const { container } = mountComposed({ + ...COMPOSED, + sources: ['openai-chatgpt'], + }); + expect(container.querySelector('li.ai-refine')).not.toBeInTheDocument(); + }); + + it('hides the dropdown when OpenAI is not supported', () => { + root.dataset.isOpenaiChatgptSupported = 'false'; + const { container } = mountComposed(); + expect(container.querySelector('li.ai-refine')).not.toBeInTheDocument(); + }); + + it('replaces every field with the refined translation', async () => { + const fetchRefined = vi + .spyOn(machineryApi, 'fetchOpenAIComposedTranslation') + .mockResolvedValue({ + value: ['Veuillez cliquer'], + properties: { title: ['Infobulle raffinée'] }, + }); + + const { container } = mountComposed(); + + fireEvent.click(container.querySelector('li.ai-refine .selector')); + await act(async () => { + fireEvent.click(screen.getByText('MAKE FORMAL')); + }); + + expect(fetchRefined).toHaveBeenCalledWith( + 42, + COMPOSED.value, + COMPOSED.properties, + 'formal', + expect.anything(), + ); + + const suggestion = container.querySelector( + '.fluent-rich-string.suggestion', + ); + expect(suggestion.textContent).toContain('Veuillez cliquer'); + expect(suggestion.textContent).toContain('Infobulle raffinée'); + expect(suggestion.textContent).not.toContain('Cliquez'); + + expect( + container.querySelector('.fluent-rich-string.original').textContent, + ).toContain('Click Me'); + expect(container.querySelector('.selected-option').textContent).toContain( + 'formal', + ); + }); + + it('restores the unrefined suggestion', async () => { + vi.spyOn( + machineryApi, + 'fetchOpenAIComposedTranslation', + ).mockResolvedValue({ + value: ['Veuillez cliquer'], + properties: { title: ['Raffiné'] }, + }); + + const { container } = mountComposed(); + + fireEvent.click(container.querySelector('li.ai-refine .selector')); + await act(async () => { + fireEvent.click(screen.getByText('MAKE FORMAL')); + }); + + fireEvent.click(container.querySelector('li.ai-refine .selector')); + await act(async () => { + fireEvent.click(screen.getByText('SHOW ORIGINAL')); + }); + + expect( + container.querySelector('.fluent-rich-string.suggestion').textContent, + ).toContain('Cliquez'); + }); + + it('keeps the suggestion when refinement fails', async () => { + vi.spyOn( + machineryApi, + 'fetchOpenAIComposedTranslation', + ).mockResolvedValue(null); + + const { container } = mountComposed(); + + fireEvent.click(container.querySelector('li.ai-refine .selector')); + await act(async () => { + fireEvent.click(screen.getByText('REPHRASE')); + }); + + expect( + container.querySelector('.fluent-rich-string.suggestion').textContent, + ).toContain('Cliquez'); + expect(container.querySelector('.selected-option').textContent).toBe(''); + }); + }); }); diff --git a/translate/src/modules/machinery/components/MachineryTranslation.tsx b/translate/src/modules/machinery/components/MachineryTranslation.tsx index 489825e57d..63bd7d182c 100644 --- a/translate/src/modules/machinery/components/MachineryTranslation.tsx +++ b/translate/src/modules/machinery/components/MachineryTranslation.tsx @@ -184,21 +184,37 @@ export function ComposedTranslationComponent({ const isSelected = element === index; const locale = useContext(Locale); + const getLLMTranslationState = useLLMTranslation(); + const { llmComposed } = getLLMTranslationState(translation); + const copyIntoEditor = useCallback(() => { if (window.getSelection()?.isCollapsed !== false) { setElement(index); - setEditorFromComposed( - translation.value, - translation.properties, - translation.sources, - true, - ); - logUXAction('Machinery Translation Copied', 'Machinery Adoption', { - sources: translation.sources.join(','), - localeCode: locale.code, - }); + const refined = llmComposed ?? translation; + const sources: SourceType[] = llmComposed + ? ['openai-chatgpt'] + : translation.sources; + setEditorFromComposed(refined.value, refined.properties, sources, true); + if (llmComposed) { + logUXAction('LLM Translation Copied', 'LLM Feature Adoption', { + action: 'Copy LLM Translation', + localeCode: locale.code, + }); + } else { + logUXAction('Machinery Translation Copied', 'Machinery Adoption', { + sources: sources.join(','), + localeCode: locale.code, + }); + } } - }, [index, locale, setEditorFromComposed, setElement, translation]); + }, [ + index, + llmComposed, + locale, + setEditorFromComposed, + setElement, + translation, + ]); const className = classNames( 'translation', @@ -230,11 +246,16 @@ function ComposedSuggestion({ }) { const { code, direction, script } = useContext(Locale); const machineryEntry = useMachineryEntry(); + + const getLLMTranslationState = useLLMTranslation(); + const { llmComposed, loading } = getLLMTranslationState(translation); + + const suggestion = llmComposed ?? translation; const suggestionEntry = createMessageEntry( machineryEntry.format, machineryEntry.id, - translation.value, - translation.properties, + suggestion.value, + suggestion.properties, ); const originalFields = richFields(machineryEntry); @@ -256,7 +277,11 @@ function ComposedSuggestion({

)} - {suggestionFields ? ( + {loading ? ( +

+ +

+ ) : suggestionFields ? ( ', () => { getByText(translationMemoryTitle); getByText(microsoftTerminologyTitle); }); + + it('leads with Translation Memory, which the quality score belongs to', () => { + // Google Translate resolving first used to render + // `100% • GOOGLE TRANSLATE • TRANSLATION MEMORY`, reading as if the score + // scored Google Translate. + const { container } = render( + , + ); + + const sources = container.querySelector('ul.sources'); + expect(sources.firstElementChild).toHaveTextContent(translationMemoryTitle); + }); + + it('keeps the order the other sources arrived in', () => { + const { container } = render( + , + ); + + const sources = container.querySelector('ul.sources'); + expect([...sources.children].map((li) => li.textContent)).toEqual([ + caighdeanTranslationTitle, + microsoftTranslationTitle, + ]); + }); + + describe('AI badge', () => { + let root; + + beforeEach(() => { + root = document.createElement('div'); + root.id = 'root'; + root.dataset.isOpenaiChatgptSupported = 'true'; + document.body.appendChild(root); + }); + + afterEach(() => root.remove()); + + const sourceList = (translation, props) => + render( + , + ).container.querySelector('ul.sources'); + + it('comes last, not where its source landed in the list', () => { + // Google Translate arriving anywhere but last used to leave the dropdown + // stranded mid-list, because it hung off the label. + const sources = sourceList({ + sources: ['google-translate', 'microsoft-translator'], + }); + + expect([...sources.children].map((li) => li.className)).toEqual([ + 'google-translation', + '', + 'ai-refine', + ]); + }); + + it('carries no source label of its own', () => { + const sources = sourceList({ sources: ['google-translate'] }); + const badge = sources.querySelector('li.ai-refine'); + + expect( + badge.querySelector('.translation-source'), + ).not.toBeInTheDocument(); + expect(sources.querySelector('li.google-translation')).toHaveTextContent( + googleTranslationTitle, + ); + }); + + it('is offered only for Google Translate output', () => { + for (const source of [ + 'translation-memory', + 'microsoft-translator', + 'caighdean', + ]) { + const sources = sourceList({ sources: [source] }); + expect(sources.querySelector('li.ai-refine')).not.toBeInTheDocument(); + } + }); + + it('is hidden when OpenAI is not supported', () => { + root.dataset.isOpenaiChatgptSupported = 'false'; + const sources = sourceList({ sources: ['google-translate'] }); + + expect(sources.querySelector('li.ai-refine')).not.toBeInTheDocument(); + }); + }); }); diff --git a/translate/src/modules/machinery/components/MachineryTranslationSource.tsx b/translate/src/modules/machinery/components/MachineryTranslationSource.tsx index aa704c8e17..05a6265ccd 100644 --- a/translate/src/modules/machinery/components/MachineryTranslationSource.tsx +++ b/translate/src/modules/machinery/components/MachineryTranslationSource.tsx @@ -1,11 +1,15 @@ -import { Localized } from '@fluent/react'; -import React from 'react'; +import React, { useContext } from 'react'; import type { ComposedMachineryTranslation, MachineryTranslation, } from '~/api/machinery'; +import { EntityView } from '~/context/EntityView'; +import { Locale } from '~/context/Locale'; +import { SearchData } from '~/context/SearchData'; +import { useLLMTranslation } from '~/context/TranslationContext'; +import { AIRefine } from './source/AIRefine'; import { GoogleTranslation } from './source/GoogleTranslation'; import { OpenAITranslation } from './source/OpenAITranslation'; import { MicrosoftTranslation } from './source/MicrosoftTranslation'; @@ -32,7 +36,15 @@ export function MachineryTranslationSource({ const isOpenAIChatGPTSupported = root?.dataset.isOpenaiChatgptSupported === 'true'; - for (const source of translation.sources) { + // The quality score is rendered ahead of this list and always comes from the + // Translation Memory match, so that badge has to lead for the two to read as + // one. A stable sort leaves the rest in arrival order. + const ordered = [...translation.sources].sort( + (a, b) => + Number(b === 'translation-memory') - Number(a === 'translation-memory'), + ); + + for (const source of ordered) { if (seen.includes(source)) { continue; } @@ -49,21 +61,7 @@ export function MachineryTranslationSource({ ); break; case 'google-translate': - sources.push( - composed ? ( -
  • - - GOOGLE TRANSLATE - -
  • - ) : ( - - ), - ); + sources.push(); break; case 'openai-chatgpt': sources.push(); @@ -80,5 +78,90 @@ export function MachineryTranslationSource({ } } - return
      {sources}
    ; + return ( +
      + {sources} + {isOpenAIChatGPTSupported && + (composed ? ( + + ) : ( + + ))} +
    + ); +} + +/** + * A suggestion that is already LLM output doesn't offer to refine itself, which + * matches the single-string rows the Machinery panel generates automatically. + */ +function ComposedAIRefine({ + translation, +}: { + translation: ComposedMachineryTranslation; +}): React.ReactElement<'li'> | null { + const locale = useContext(Locale); + const { entity } = useContext(EntityView); + const getLLMTranslationState = useLLMTranslation(); + const { selectedOption, transformComposedLLMTranslation, restoreOriginal } = + getLLMTranslationState(translation); + + if (translation.sources.every((source) => source === 'openai-chatgpt')) { + return null; + } + + return ( + + transformComposedLLMTranslation( + translation, + characteristic, + locale.code, + entity.pk, + ) + } + onRestore={() => restoreOriginal(translation)} + /> + ); +} + +/** + * Offered for Google Translate output only: the refinement prompt takes one + * machine translation as its reference, and that is the one the panel has. + */ +function SingleAIRefine({ + translation, +}: { + translation: MachineryTranslation; +}): React.ReactElement<'li'> | null { + const locale = useContext(Locale); + const { entity } = useContext(EntityView); + const { query } = useContext(SearchData); + const getLLMTranslationState = useLLMTranslation(); + const { selectedOption, transformLLMTranslation, restoreOriginal } = + getLLMTranslationState(translation); + + if (!translation.sources.includes('google-translate')) { + return null; + } + + return ( + + transformLLMTranslation( + translation, + characteristic, + locale.code, + // A Concordance search result is not the entity being translated, so + // its context would be the wrong context to refine against. + query ? undefined : entity.pk, + ) + } + onRestore={() => restoreOriginal(translation)} + /> + ); } diff --git a/translate/src/modules/machinery/components/source/AIRefine.test.jsx b/translate/src/modules/machinery/components/source/AIRefine.test.jsx new file mode 100644 index 0000000000..d4128df40b --- /dev/null +++ b/translate/src/modules/machinery/components/source/AIRefine.test.jsx @@ -0,0 +1,74 @@ +import React from 'react'; +import { act, fireEvent, render, within } from '@testing-library/react'; +import { vi } from 'vitest'; + +import { MockLocalizationProvider } from '~/test/utils'; + +import { AIRefine } from './AIRefine'; + +const mount = (props) => + render( + + {}} + onRestore={() => {}} + {...props} + /> + , + ); + +describe('', () => { + it('opens a menu of refinement options', () => { + const { container, getByRole, queryByRole } = mount(); + + expect(queryByRole('list')).not.toBeInTheDocument(); + + fireEvent.click(container.querySelector('.selector')); + expect(within(getByRole('list')).getAllByRole('listitem')).toHaveLength(3); + }); + + it('offers to restore the original once an option is applied', () => { + const { container, getByRole } = mount({ selectedOption: 'formal' }); + + fireEvent.click(container.querySelector('.selector')); + // The three options, the separator, and SHOW ORIGINAL. + expect(within(getByRole('list')).getAllByRole('listitem')).toHaveLength(5); + expect(container.querySelector('.selected-option')).toHaveTextContent( + 'formal', + ); + }); + + it('reports the chosen characteristic and closes', async () => { + const onSelect = vi.fn(); + const { container, queryByRole, getByText } = mount({ onSelect }); + + fireEvent.click(container.querySelector('.selector')); + // The handler awaits the refinement before closing, so the close lands a + // microtask later than the click. + await act(async () => { + fireEvent.click(getByText('MAKE INFORMAL')); + }); + + expect(onSelect).toHaveBeenCalledWith('informal'); + expect(queryByRole('list')).not.toBeInTheDocument(); + }); + + it('restores rather than refines when showing the original', async () => { + const onSelect = vi.fn(); + const onRestore = vi.fn(); + const { container, getByText } = mount({ + selectedOption: 'formal', + onSelect, + onRestore, + }); + + fireEvent.click(container.querySelector('.selector')); + await act(async () => { + fireEvent.click(getByText('SHOW ORIGINAL')); + }); + + expect(onRestore).toHaveBeenCalled(); + expect(onSelect).not.toHaveBeenCalled(); + }); +}); diff --git a/translate/src/modules/machinery/components/source/AIRefine.tsx b/translate/src/modules/machinery/components/source/AIRefine.tsx new file mode 100644 index 0000000000..a229ec8a90 --- /dev/null +++ b/translate/src/modules/machinery/components/source/AIRefine.tsx @@ -0,0 +1,125 @@ +import { Localized } from '@fluent/react'; +import React, { useContext, useState } from 'react'; + +import { logUXAction } from '~/api/uxaction'; +import { Locale } from '~/context/Locale'; + +type Props = { + /** The characteristic currently applied, or '' when showing the original. */ + selectedOption: string; + onSelect: (characteristic: string) => Promise | void; + onRestore: () => void; +}; + +/** + * The "Refine using AI" dropdown. + * + * Always the last item of a suggestion's source list, never attached to one of + * the source labels: it acts on the suggestion, and a suggestion can be + * assembled from several sources with no one of them owning it. + */ +export function AIRefine({ + selectedOption, + onSelect, + onRestore, +}: Props): React.ReactElement<'li'> { + const [isDropdownOpen, setDropdownOpen] = useState(false); + const locale = useContext(Locale); + + const toggleDropdown = (ev: React.MouseEvent) => { + ev.stopPropagation(); + setDropdownOpen((isDropdownOpen) => !isDropdownOpen); + }; + + const handleOptionClick = async (ev: React.MouseEvent) => { + ev.stopPropagation(); + const characteristic = ev.currentTarget.dataset['characteristic'] as string; + + if (characteristic === 'original') { + onRestore(); + } else { + await onSelect(characteristic); + logUXAction('LLM Dropdown Select', 'LLM Feature Adoption', { + optionSelected: characteristic, + localeCode: locale.code, + }); + } + setDropdownOpen(false); + }; + + return ( +
  • + + + {selectedOption ? ( + + {selectedOption} + + ) : ( + {selectedOption} + )} + + + + + {isDropdownOpen && ( +
      + +
    • + REPHRASE +
    • +
      + +
    • + MAKE FORMAL +
    • +
      + +
    • + MAKE INFORMAL +
    • +
      + {selectedOption && ( + <> +
    • + +
    • + SHOW ORIGINAL +
    • +
      + + )} +
    + )} +
  • + ); +} diff --git a/translate/src/modules/machinery/components/source/GoogleTranslation.test.jsx b/translate/src/modules/machinery/components/source/GoogleTranslation.test.jsx index c673cc9733..7cbdda3d65 100644 --- a/translate/src/modules/machinery/components/source/GoogleTranslation.test.jsx +++ b/translate/src/modules/machinery/components/source/GoogleTranslation.test.jsx @@ -1,17 +1,9 @@ import React from 'react'; import { GoogleTranslation } from './GoogleTranslation'; -import { fireEvent, render, within } from '@testing-library/react'; +import { render } from '@testing-library/react'; import { MockLocalizationProvider } from '~/test/utils'; -vi.mock('~/hooks', () => ({ - useAppSelector: (selector) => - selector({ - term: { terms: [], fetching: false, entity: 0, locale: '' }, - teamcomments: { comments: [], fetching: false, entity: null }, - }), -})); - describe('', () => { it('renders the GoogleTranslation component properly', () => { const message = 'test-source'; @@ -28,34 +20,4 @@ describe('', () => { getByRole('listitem'); getByText(message); }); - - it('renders the GoogleTranslation LLM features properly', () => { - const mockTranslation = { - translation: 'Translated text here', - original: 'Original text here', - }; - const message = 'test-source'; - - const { container, getByRole } = render( - - - , - ); - - getByRole('listitem'); - - expect( - container.querySelector('span.translation-source'), - ).toHaveTextContent(message); - - fireEvent.click(container.querySelector('.selector')); - expect(within(getByRole('list')).getAllByRole('listitem')).toHaveLength(3); - }); }); diff --git a/translate/src/modules/machinery/components/source/GoogleTranslation.tsx b/translate/src/modules/machinery/components/source/GoogleTranslation.tsx index f3b35018da..aaa70daf84 100644 --- a/translate/src/modules/machinery/components/source/GoogleTranslation.tsx +++ b/translate/src/modules/machinery/components/source/GoogleTranslation.tsx @@ -1,151 +1,15 @@ -import React, { useState, useRef, useContext } from 'react'; +import React from 'react'; import { Localized } from '@fluent/react'; -import type { MachineryTranslation } from '~/api/machinery'; -import { EntityView } from '~/context/EntityView'; -import { Locale } from '~/context/Locale'; -import { SearchData } from '~/context/SearchData'; -import { logUXAction } from '~/api/uxaction'; -import { useLLMTranslation } from '~/context/TranslationContext'; - -type Props = { - isOpenAIChatGPTSupported: boolean; - translation: MachineryTranslation; -}; /** * Show the translation source from Google Translate. - * - * If OpenAI ChatGPT is supported, this component also handles machine translation - * refinement using AI. */ - -export function GoogleTranslation({ - isOpenAIChatGPTSupported, - translation, -}: Props): React.ReactElement<'li'> { - const [isDropdownOpen, setDropdownOpen] = useState(false); - const dropdownRef = useRef(null); - const locale = useContext(Locale); - const { entity } = useContext(EntityView); - const { query } = useContext(SearchData); - - const getLLMTranslationState = useLLMTranslation(); - - const { transformLLMTranslation, selectedOption, restoreOriginal } = - getLLMTranslationState(translation); - - const toggleDropdown = (ev: React.MouseEvent) => { - ev.stopPropagation(); - setDropdownOpen((isDropdownOpen) => !isDropdownOpen); - }; - - const handleOptionClick = async (ev: React.MouseEvent) => { - ev.stopPropagation(); - const target = ev.currentTarget; - const characteristic = target.dataset['characteristic'] as string; - - if (characteristic === 'original') { - restoreOriginal(translation); - } else { - await transformLLMTranslation( - translation, - characteristic, - locale.code, - query ? undefined : entity.pk, - ); - logUXAction('LLM Dropdown Select', 'LLM Feature Adoption', { - optionSelected: characteristic, - localeCode: locale.code, - }); - } - setDropdownOpen(false); - }; - - const title = ( - - GOOGLE TRANSLATE - - ); - - return isOpenAIChatGPTSupported ? ( -
  • - - - {title} - - {selectedOption ? ( - - {selectedOption} - - ) : ( - {selectedOption} - )} - - - +export function GoogleTranslation(): React.ReactElement<'li'> { + return ( +
  • + + GOOGLE TRANSLATE - {isDropdownOpen && ( -
      - -
    • - REPHRASE -
    • -
      - -
    • - MAKE FORMAL -
    • -
      - -
    • - MAKE INFORMAL -
    • -
      - {selectedOption && ( - <> -
    • - -
    • - SHOW ORIGINAL -
    • -
      - - )} -
    - )}
  • - ) : ( -
  • {title}
  • ); } diff --git a/translate/src/modules/translationform/utils/editFieldShortcuts.ts b/translate/src/modules/translationform/utils/editFieldShortcuts.ts index 2ac0641d65..63b45d5a02 100644 --- a/translate/src/modules/translationform/utils/editFieldShortcuts.ts +++ b/translate/src/modules/translationform/utils/editFieldShortcuts.ts @@ -115,8 +115,25 @@ export function useHandleCtrlShiftArrow(): ( if (isMachinery) { if (nextIdx < composed.length) { - const { value, properties, sources } = composed[nextIdx]; - setEditorFromComposed(value, properties, sources, true); + const composedObj = composed[nextIdx]; + const { llmComposed } = getLLMTranslationState(composedObj); + const refined = llmComposed ?? composedObj; + setEditorFromComposed( + refined.value, + refined.properties, + llmComposed ? ['openai-chatgpt'] : composedObj.sources, + true, + ); + if (llmComposed) { + logUXAction( + 'LLM Translation Copied via Shortcut', + 'LLM Feature Adoption', + { + action: 'Copy LLM Translation via Shortcut', + localeCode: locale.code, + }, + ); + } return true; } @@ -129,7 +146,11 @@ export function useHandleCtrlShiftArrow(): ( const llmState = getLLMTranslationState(translationObj); const updatedTranslation = llmState.llmTranslation || translationObj.translation; - setEditorFromHelpers(updatedTranslation, translationObj.sources, true); + setEditorFromHelpers( + updatedTranslation, + llmState.llmTranslation ? ['openai-chatgpt'] : translationObj.sources, + true, + ); if (llmState.llmTranslation) { logUXAction(