Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions pontoon/machinery/openai_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,31 @@
from django.conf import settings
from django.core.cache import cache

from pontoon.base.models import Entity, Resource
from pontoon.machinery.utils import (
get_machinery_service_cache_key,
set_machinery_service_cache_key,
)


def get_llm_string_id(entity: Entity) -> str | None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this file is service-specific, shall we move this function outside of it, e.g. utils.py?

"""
String identifier to pass to the LLM prompt as additional context,
or None if the entity doesn't have a meaningful one.
"""
key = entity.key
section_key = entity.section.key if entity.section_id is not None else []
# Entity.key is the section key followed by the entry's own id, so drop
# the section part.
if section_key and key[: len(section_key)] == section_key:
key = key[len(section_key) :]
if entity.resource.format == Resource.Format.GETTEXT:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we skip the ID when it equals entity.string, regardless of format? It's also the case for at least some XCODE/XLIFF files.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense, didn't think of those.

# For gettext, don't include the msgid as it's the same as source text.
# key is (msgid,) or (msgid, msgctxt)
key = key[1:]
return ".".join(key) or None


class OpenAIService:
def __init__(self):
if not settings.OPENAI_API_KEY:
Expand Down
63 changes: 63 additions & 0 deletions pontoon/machinery/tests/test_openai_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import pytest

from pontoon.base.models import Resource
from pontoon.machinery.openai_service import get_llm_string_id
from pontoon.test.factories import (
EntityFactory,
ResourceFactory,
SectionFactory,
)


@pytest.mark.django_db
@pytest.mark.parametrize(
"format, section_key, entity_key, expected",
[
# Formats without a section key
(Resource.Format.PROPERTIES, [], ["open-browser"], "open-browser"),
# Formats with the file name or section name as the section key
(
Resource.Format.XLIFF,
["Client/Client.strings"],
["Client/Client.strings", "Settings.Title"],
"Settings.Title",
),
(
Resource.Format.XCODE,
["Localizable.strings"],
["Localizable.strings", "Settings.Title"],
"Settings.Title",
),
(Resource.Format.INI, ["Strings"], ["Strings", "label"], "label"),
(Resource.Format.ANDROID, ["!ENTITY"], ["!ENTITY", "brandName"], "brandName"),
# For gettext, the message id is the source string, optionally
# followed by the message context
(Resource.Format.GETTEXT, [], ["Open browser"], None),
(Resource.Format.GETTEXT, [], ["Open browser", "toolbar"], "toolbar"),
# Nested keys are joined
(
Resource.Format.PLAIN_JSON,
[],
["toolbar", "open-browser"],
"toolbar.open-browser",
),
# Missing key
(Resource.Format.PROPERTIES, [], [], None),
],
)
def test_get_llm_string_id(format, section_key, entity_key, expected):
resource = ResourceFactory(format=format)
section = SectionFactory(key=section_key, resource=resource)
entity = EntityFactory(
key=entity_key, string="Open browser", resource=resource, section=section
)

assert get_llm_string_id(entity) == expected


@pytest.mark.django_db
def test_get_llm_string_id_without_section():
resource = ResourceFactory(format=Resource.Format.PROPERTIES)
entity = EntityFactory(key=["open-browser"], resource=resource, section=None)

assert get_llm_string_id(entity) == "open-browser"
65 changes: 63 additions & 2 deletions pontoon/machinery/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@
from pontoon.base.models import (
Entity,
Locale,
Resource,
)
from pontoon.test.factories import (
EntityFactory,
ProjectLocaleFactory,
ResourceFactory,
SectionFactory,
TeamCommentFactory,
TermFactory,
Expand Down Expand Up @@ -319,12 +321,13 @@ def test_view_gpt_transform_context(member, locale_a, openai_api_key):

# Create entity with full context: key, comment, group (section) comment,
# resource comment
section = SectionFactory(key=["nav"], comment="Navigation section")
resource = ResourceFactory(path="ui.properties", format=Resource.Format.PROPERTIES)
section = SectionFactory(key=[], comment="Navigation section", resource=resource)
entity = EntityFactory(
key=["open-browser"],
string="Open browser",
comment="Button label",
resource=section.resource,
resource=resource,
section=section,
)
entity.resource.comment = "Main UI file"
Expand Down Expand Up @@ -374,6 +377,64 @@ def test_view_gpt_transform_context(member, locale_a, openai_api_key):
assert '"browser" (noun) → "navigateur"' in user_message


@pytest.mark.django_db
@pytest.mark.parametrize(
"format, section_key, entity_key, expected",
[
# For XLIFF (e.g. iOS projects), the section key is the file name
(
Resource.Format.XLIFF,
["Client/Client.strings"],
["Client/Client.strings", "Settings.Title"],
"STRING ID:\nSettings.Title",
),
# For gettext, the message id is the source string itself
(Resource.Format.GETTEXT, [], ["Open browser"], None),
],
)
def test_view_gpt_transform_string_id(
member, locale_a, openai_api_key, format, section_key, entity_key, expected
):
url = reverse("pontoon.gpt_transform")
cache.clear()

mock_response = MagicMock()
mock_response.choices[0].message.content = "translated"

resource = ResourceFactory(format=format)
section = SectionFactory(key=section_key, resource=resource)
entity = EntityFactory(
key=entity_key,
string="Open browser",
resource=resource,
section=section,
)

with patch("pontoon.machinery.openai_service.OpenAI") as MockOpenAI:
MockOpenAI.return_value.chat.completions.create.return_value = mock_response

member.client.post(
url,
{
"english_text": "Open browser",
"translated_text": "Ouvrir le navigateur",
"characteristic": "formal",
"locale": locale_a.code,
"entity_pk": entity.pk,
},
)

call_args = MockOpenAI.return_value.chat.completions.create.call_args
system_message = call_args.kwargs["messages"][0]["content"]
user_message = call_args.kwargs["messages"][1]["content"]
if expected is None:
assert "STRING ID" not in user_message
assert "STRING ID" not in system_message
else:
assert expected in user_message
assert "STRING ID:" in system_message


@pytest.mark.django_db
def test_view_caighdean(client, entity_a):
gd = Locale.objects.get(code="gd")
Expand Down
4 changes: 2 additions & 2 deletions pontoon/machinery/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from pontoon.pretranslation.pretranslate import MTEngine, Pretranslation
from pontoon.terminology.models import Term

from .openai_service import OpenAIService
from .openai_service import OpenAIService, get_llm_string_id


log = logging.getLogger(__name__)
Expand Down Expand Up @@ -290,7 +290,7 @@ def gpt_transform(request):
entity = Entity.objects.select_related("resource", "section").get(
pk=entity_pk
)
entity_key = entity.key[0] if entity.key else None
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
Expand Down
Loading