Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
12 changes: 11 additions & 1 deletion pontoon/pretranslation/pretranslate.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,17 @@ def serialize(self, value: Message, properties: dict[str, Message]) -> str:
pretranslation behavior (unlike sync, which escapes them).
"""
entry = Entry(id=tuple(self.entity.key), value=value, properties=properties)
return as_string(self.format, entry, fluent_escape_syntax=False)
res = as_string(self.format, entry, fluent_escape_syntax=False)
if self.format == Format.fluent:
try:
fluent_parse_entry(res, with_linepos=False)
except ValueError:
# MT returns plain text, which can hold a brace that isn't Fluent
# syntax, e.g. `Rhowch { yma`. Raw, that serializes to something
# unparseable. Escaping is the fallback rather than the default
# because it would also turn a verbatim placeable into literal text.
res = as_string(self.format, entry, fluent_escape_syntax=True)
return res

def message(self, msg: Message) -> None:
"""Modifies `msg`."""
Expand Down
20 changes: 15 additions & 5 deletions pontoon/pretranslation/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,14 @@ def pretranslate(project: Project, paths: set[str] | None):
if locale_entity in translated_entities or locale_resource not in tr_pairs:
continue

entity_desc = (
f"entity {entity.pk} ({entity.resource.path}) in {locale.code}"
)

try:
pretranslation = get_pretranslation(entity, locale)
except ValueError as e:
log.info(f"Pretranslation error: {e}")
log.info(f"Pretranslation error for {entity_desc}: {e}")
Comment thread
eemeli marked this conversation as resolved.
Resolved
continue

failed_checks = run_checks(
Expand All @@ -132,13 +136,19 @@ def pretranslate(project: Project, paths: set[str] | None):
entity, locale, preserve_placeables=True
)
except ValueError as e:
log.info(f"Pretranslation error: {e}")
log.info(f"Pretranslation error for {entity_desc}: {e}")
Comment thread
eemeli marked this conversation as resolved.
Resolved
continue

string, author_key = pretranslation
_, value, properties = parse_source_string_to_json(
entity.resource.format, string
)
try:
_, value, properties = parse_source_string_to_json(
entity.resource.format, string
)
except ValueError as e:
log.error(
f"Unparsable pretranslation for {entity_desc}: {e}: {string!r}"
Comment thread
eemeli marked this conversation as resolved.
Resolved
)
continue

t = Translation(
entity=entity,
Expand Down
41 changes: 37 additions & 4 deletions pontoon/pretranslation/tests/test_pretranslate.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,14 +409,15 @@ def test_get_pretranslations_fluent_accesskeys_ignore_placeables(

gt_mock.return_value = "{ $0 } gt_translation"

# The `title` value here is hacky, but demonstrates that
# a Google Translate response that includes an unexpected `{$0}`
# does not cause a failure, just odd output.
# The `title` value here is hacky, but demonstrates that a Google Translate
# response that includes an unexpected `{$0}` does not cause a failure, just
# odd output. `$0` is not a valid Fluent identifier, so the braces are
# escaped to keep the entry parseable.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Sigh.

# For the `.label` it's expected,
# and therefore replaced with the correct placeholder.
expected = dedent(
"""
title = {$0} gt_translation
title = { "{" }$0{ "}" } gt_translation
.label = { $brand } gt_translation
.accesskey = g

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is this test proposing that something like this should ever be output from pretranslation? If we get garbage like this, why aren't we just giving up on pretranslating this message?

"""
Expand Down Expand Up @@ -847,3 +848,35 @@ def test_get_pretranslations_fluent_sibling_selectors(
google_translate_locale.cldr_plurals = "1,5"
response = get_pretranslation(fluent_entity, google_translate_locale)
assert response == (pretranslated_string, "tm")


@patch("pontoon.pretranslation.pretranslate.get_google_translate_data")
@pytest.mark.django_db
def test_get_pretranslations_fluent_mt_stray_brace(
gt_mock, fluent_resource, google_translate_locale
):
# MT returns plain text, which can hold a brace that isn't Fluent syntax.
# Escaped, it stays a literal brace; raw, the entry wouldn't parse at all.
gt_mock.return_value = "Rhowch { yma"

fluent_entity = EntityFactory(resource=fluent_resource, string="key = Enter here\n")

response = get_pretranslation(fluent_entity, google_translate_locale)
assert response == ('key = Rhowch { "{" } yma\n', "gt")


@patch("pontoon.pretranslation.pretranslate.get_google_translate_data")
@pytest.mark.django_db
def test_get_pretranslations_fluent_mt_placeable_kept_raw(
gt_mock, fluent_resource, google_translate_locale
):
# Output that parses is left alone, so a placeable MT returned verbatim
# stays a placeable instead of being escaped into literal text.
gt_mock.return_value = "50 { $count } cyn"

fluent_entity = EntityFactory(
resource=fluent_resource, string="key = 50 more to go\n"
)

response = get_pretranslation(fluent_entity, google_translate_locale)
assert response == ("key = 50 { $count } cyn\n", "gt")
41 changes: 41 additions & 0 deletions pontoon/pretranslation/tests/test_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,44 @@ def test_which_strings_to_pretranslate(
assert len(non_rejected.translation_set.filter(string="pretranslation")) == 0
assert len(rejected_by_human.translation_set.filter(string="pretranslation")) == 1
assert len(rejected_by_machine.translation_set.filter(string="pretranslation")) == 0


@patch("pontoon.pretranslation.tasks.run_checks")
@patch("pontoon.pretranslation.tasks.get_pretranslation")
@pytest.mark.django_db
def test_pretranslate_skips_unparsable_pretranslation(
gt_mock, checks_mock, project_a, locale_a, gt_user, caplog
):
"""
An entity whose pretranslation doesn't parse must not abort the pretranslation
of other entities.
"""
project_a.pretranslation_enabled = True
project_a.save()

resource = ResourceFactory.create(
project=project_a, path="resource.ftl", format="fluent"
)
TranslatedResourceFactory.create(resource=resource, locale=locale_a)
ProjectLocaleFactory.create(
project=project_a,
locale=locale_a,
pretranslation_enabled=True,
)

EntityFactory.create(resource=resource, string="key-a = A\n", order=0)
EntityFactory.create(resource=resource, string="key-b = B\n", order=1)

checks_mock.return_value = {}
gt_mock.side_effect = [
("key-a = unescaped { brace\n", "gt"),
("key-b = GT\n", "gt"),
]

with caplog.at_level("ERROR", logger="pontoon.pretranslation.tasks"):
pretranslate_task(project_a.pk)

assert "Unparsable pretranslation" in caplog.text
assert [t.string for t in Translation.objects.filter(user=gt_user)] == [
"key-b = GT\n"
]
Loading