From 3ef098a8ea91cf96646b8f9bd69ff895346a5c7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20=C4=8Ciha=C5=99?= Date: Fri, 27 Nov 2026 14:02:24 +0100 Subject: [PATCH] feat(screenshots): prioritize OCR matches in the editor picker Rank eligible screenshots by whether their cached image text matches the current source phrase. Mark matches in the picker so translators can find relevant context before attaching an image. Refs #15650. --- docs/changes.rst | 1 + docs/user/translating.rst | 5 +- .../0005_screenshot_ocr_pass_text.py | 72 +++++++ weblate/screenshots/models.py | 23 ++ weblate/screenshots/tests.py | 204 +++++++++++++++++- weblate/screenshots/views.py | 45 +++- .../screenshots/screenshot_select.html | 3 + weblate/trans/tests/test_selenium.py | 39 +++- 8 files changed, 377 insertions(+), 15 deletions(-) create mode 100644 weblate/screenshots/migrations/0005_screenshot_ocr_pass_text.py diff --git a/docs/changes.rst b/docs/changes.rst index 4d78c3ca07f6..fa0a87ce3458 100644 --- a/docs/changes.rst +++ b/docs/changes.rst @@ -47,6 +47,7 @@ Weblate 2026.12 * Added a choice to :ref:`connect an existing GitHub App installation to another workspace `. * Allow five minutes to assign strings to newly uploaded :ref:`screenshots` before raising an unused screenshot alert. +* The :ref:`screenshot picker ` prioritizes screenshots with recognized image text matching the current source string. * Show the last translator and approver in the :ref:`translation editor `. * Keep the original editor search when merging a translation from the :ref:`translation context `. diff --git a/docs/user/translating.rst b/docs/user/translating.rst index 5cdc4762107a..b7873e68a21b 100644 --- a/docs/user/translating.rst +++ b/docs/user/translating.rst @@ -480,7 +480,10 @@ To link a screenshot that has already been uploaded, open the string in the translation editor: 1. In the :guilabel:`Screenshots` panel, choose :guilabel:`Add existing screenshot`. -2. Browse the thumbnails, or enter a query in :guilabel:`Search screenshots` and +2. Browse the thumbnails. Screenshots with the current source phrase in their + recognized image text appear first and show an :guilabel:`Image text match` + badge. To filter by screenshot name or other :ref:`screenshot search fields + `, enter a query in :guilabel:`Search screenshots` and choose :guilabel:`Search`. Use :guilabel:`Previous` and :guilabel:`Next` to browse additional results. 3. Select a screenshot by clicking its card. The card is highlighted and marked diff --git a/weblate/screenshots/migrations/0005_screenshot_ocr_pass_text.py b/weblate/screenshots/migrations/0005_screenshot_ocr_pass_text.py new file mode 100644 index 000000000000..f0b3596b9eb3 --- /dev/null +++ b/weblate/screenshots/migrations/0005_screenshot_ocr_pass_text.py @@ -0,0 +1,72 @@ +# Copyright © Michal Čihař +# +# SPDX-License-Identifier: GPL-3.0-or-later + +from __future__ import annotations + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("screenshots", "0004_screenshot_backup_author_claim"), + ] + + operations = [ + migrations.RunSQL( + # Store a bounded prefix of complete lines for each pass. + sql=""" + CREATE FUNCTION weblate_ocr_pass_text( + cache jsonb, pass_index integer + ) RETURNS text + LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE + RETURN ( + SELECT btrim(regexp_replace( + coalesce(string_agg(line, ' ' ORDER BY line_number), ''), + '[[:space:]]+', ' ', 'g' + )) + FROM ( + SELECT value #>> '{}' AS line, line_number, + sum(octet_length(value #>> '{}') + 1) + OVER (ORDER BY line_number) AS total_bytes + FROM jsonb_path_query( + cache -> 'passes' -> pass_index, + '$.lines[*].text ? (@.type() == "string")' + ) WITH ORDINALITY AS recognized(value, line_number) + ) AS lines + WHERE total_bytes <= 32768 + ); + """, + reverse_sql="DROP FUNCTION weblate_ocr_pass_text(jsonb, integer);", + ), + migrations.AddField( + model_name="screenshotocr", + name="first_pass_text", + field=models.GeneratedField( + expression=models.Func( + "data", + models.Value(0), + function="weblate_ocr_pass_text", + output_field=models.TextField(), + ), + output_field=models.TextField(), + db_persist=True, + null=True, + ), + ), + migrations.AddField( + model_name="screenshotocr", + name="second_pass_text", + field=models.GeneratedField( + expression=models.Func( + "data", + models.Value(1), + function="weblate_ocr_pass_text", + output_field=models.TextField(), + ), + output_field=models.TextField(), + db_persist=True, + null=True, + ), + ), + ] diff --git a/weblate/screenshots/models.py b/weblate/screenshots/models.py index 8b0591bb8389..2bdb60f4ad88 100644 --- a/weblate/screenshots/models.py +++ b/weblate/screenshots/models.py @@ -249,6 +249,29 @@ class ScreenshotOCR(models.Model): requested_at = models.DateTimeField(null=True) error = models.CharField(max_length=16, blank=True) + first_pass_text = models.GeneratedField( + expression=models.Func( + "data", + models.Value(0), + function="weblate_ocr_pass_text", + output_field=models.TextField(), + ), + output_field=models.TextField(), + db_persist=True, + null=True, + ) + second_pass_text = models.GeneratedField( + expression=models.Func( + "data", + models.Value(1), + function="weblate_ocr_pass_text", + output_field=models.TextField(), + ), + output_field=models.TextField(), + db_persist=True, + null=True, + ) + def __str__(self) -> str: return f"Text recognition for screenshot {self.screenshot_id}" diff --git a/weblate/screenshots/tests.py b/weblate/screenshots/tests.py index c46f7a4fbb21..ef4db857afa3 100644 --- a/weblate/screenshots/tests.py +++ b/weblate/screenshots/tests.py @@ -42,6 +42,7 @@ from weblate.screenshots.ocr import ( OCR_LINE_LIMIT, OCR_TEXT_LENGTH_LIMIT, + OCR_WORDS_PER_LINE_LIMIT, TESSERACT_DOWNLOAD_ATTEMPTS, TESSERACT_DOWNLOAD_TIMEOUT, OCRLine, @@ -2859,12 +2860,211 @@ def setUp(self) -> None: name="Target preview", translation=self.unit.translation ) + def cache_text(self, screenshot: Screenshot, *lines: str, error: str = "") -> None: + ScreenshotOCR.objects.create( + screenshot=screenshot, + data={"passes": [{"lines": [{"text": line} for line in lines]}]}, + error=error, + ) + + def test_ocr_matches_before_other_screenshots(self) -> None: + self.cache_text(self.source_screenshot, "Hello") + self.cache_text(self.target_screenshot, "HELLO,", "world!") + pending = Screenshot.objects.create( + name="Pending preview", translation=self.unit.translation + ) + ScreenshotOCR.objects.create(screenshot=pending) + failed = Screenshot.objects.create( + name="Failed preview", translation=self.unit.translation + ) + self.cache_text(failed, "Hello, world!", error="failed") + + response = self.client.get(self.url) + self.assertEqual( + list(response.context["page_obj"]), + [self.target_screenshot, failed, pending, self.source_screenshot], + ) + document = html.fromstring(response.content) + self.assertEqual( + document.xpath('//label[.//span[text()="Image text match"]]/@for'), + [f"screenshot-choice-{self.target_screenshot.pk}"], + ) + self.assertFalse(document.xpath('//input[@name="screenshot"][@checked]')) + + response = self.client.get(self.url, {"q": "Source"}) + self.assertEqual(list(response.context["page_obj"]), [self.source_screenshot]) + self.assertNotContains(response, "Image text match") + + def test_ocr_match_order_across_pages(self) -> None: + self.source_screenshot.name = self.target_screenshot.name + self.source_screenshot.save(update_fields=["name"]) + for screenshot in (self.source_screenshot, self.target_screenshot): + self.cache_text(screenshot, "Hello, world!") + + params = {"page": 1} + # Warm page-level caches before comparing query counts. + self.client.get(self.url, params) + with CaptureQueriesContext(connection) as small_list: + self.assertEqual(self.client.get(self.url, params).status_code, 200) + + unmatched = Screenshot.objects.bulk_create( + Screenshot(name=f"Earlier {index:02}", translation=self.unit.translation) + for index in range(47) + ) + with CaptureQueriesContext(connection) as full_page: + response = self.client.get(self.url, params) + self.assertEqual(len(full_page), len(small_list)) + self.assertEqual( + list(response.context["page_obj"]), + [self.source_screenshot, self.target_screenshot, *unmatched[:46]], + ) + response = self.client.get(self.url, {"page": 2}) + self.assertEqual(list(response.context["page_obj"]), unmatched[46:]) + + def test_ocr_match_requires_an_ordered_phrase_in_one_pass(self) -> None: + Unit.objects.filter(pk=self.unit.pk).update(source="Hello world") + self.cache_text(self.source_screenshot, "Hello draft", "Discard world") + self.cache_text(self.target_screenshot, "world Hello") + split = Screenshot.objects.create( + name="Split between passes", translation=self.unit.translation + ) + ScreenshotOCR.objects.create( + screenshot=split, + data={ + "passes": [ + {"lines": [{"text": "Hello"}]}, + {"lines": [{"text": "world"}]}, + ] + }, + ) + matching = Screenshot.objects.create( + name="Wrapped phrase on second pass", translation=self.unit.translation + ) + ScreenshotOCR.objects.create( + screenshot=matching, + data={ + "passes": [ + {"lines": [{"text": "world Hello"}]}, + {"lines": [{"text": "Hello"}, {"text": "world"}]}, + ] + }, + ) + + response = self.client.get(self.url) + self.assertEqual( + list(response.context["page_obj"]), + [matching, self.source_screenshot, split, self.target_screenshot], + ) + self.assertContains(response, "Image text match", count=1) + + def test_ocr_match_with_large_cache(self) -> None: + # Exercise a cache near the worker's line and word limits. + lines = [ + { + "text": " ".join( + f"prefix{number:05d}aaaaaaaaaa-suffix{number:05d}bbbbbbbbbb" + for number in range(start, start + OCR_WORDS_PER_LINE_LIMIT) + ) + } + for start in range( + 0, + 2 * OCR_LINE_LIMIT * OCR_WORDS_PER_LINE_LIMIT, + OCR_WORDS_PER_LINE_LIMIT, + ) + ] + ScreenshotOCR.objects.create( + screenshot=self.target_screenshot, + data={ + "passes": [ + {"lines": [{"text": "Hello, world!"}, *lines[1:OCR_LINE_LIMIT]]}, + { + "lines": [ + *lines[OCR_LINE_LIMIT:-1], + {"text": "Outside byte budget"}, + ] + }, + ] + }, + ) + response = self.client.get(self.url) + self.assertEqual( + list(response.context["page_obj"]), + [self.target_screenshot, self.source_screenshot], + ) + self.assertContains(response, "Image text match", count=1) + + Unit.objects.filter(pk=self.unit.pk).update(source="Outside byte budget") + self.assertNotContains(self.client.get(self.url), "Image text match") + + def test_ocr_matches_text_without_word_spaces(self) -> None: + Component.objects.filter(pk=self.component.pk).update( + source_language=Language.objects.get(code="zh_Hans") + ) + Unit.objects.filter(pk=self.unit.pk).update(source="保存设置") + self.cache_text(self.source_screenshot, "点击保存设置继续") + self.cache_text(self.target_screenshot, "点击保存", "设置继续") + + response = self.client.get(self.url) + self.assertContains(response, "Image text match", count=2) + + def test_ocr_match_keeps_symbols_and_word_boundaries(self) -> None: + Unit.objects.filter(pk=self.unit.pk).update(source="C++") + self.cache_text(self.source_screenshot, "C#, C++17 and XC++") + self.cache_text(self.target_screenshot, "Learn C#") + self.assertNotContains(self.client.get(self.url), "Image text match") + ScreenshotOCR.objects.filter(screenshot=self.target_screenshot).update( + data={ + "passes": [ + {"lines": [{"text": "Learn"}, {"text": "c++ for beginners"}]} + ] + } + ) + + response = self.client.get(self.url) + self.assertEqual( + list(response.context["page_obj"]), + [self.target_screenshot, self.source_screenshot], + ) + self.assertContains(response, "Image text match", count=1) + response = self.client.get(self.url, {"q": "Source"}) + self.assertNotContains(response, "Image text match") + + def test_ocr_match_without_searchable_source(self) -> None: + self.cache_text(self.target_screenshot, "Hello world") + Unit.objects.filter(pk=self.unit.pk).update(source="?!") + response = self.client.get(self.url) + self.assertEqual( + list(response.context["page_obj"]), + [self.source_screenshot, self.target_screenshot], + ) + self.assertNotContains(response, "Image text match") + + def test_ocr_match_skips_oversized_source(self) -> None: + # The first 512 characters appear in OCR but are only part of the source. + prefix = "Hello " * 85 + "wo" + Unit.objects.filter(pk=self.unit.pk).update(source=f"{prefix}rld") + self.cache_text(self.target_screenshot, prefix) + response = self.client.get(self.url) + self.assertEqual( + list(response.context["page_obj"]), + [self.source_screenshot, self.target_screenshot], + ) + self.assertNotContains(response, "Image text match") + def test_candidates(self) -> None: other = self.component.translation_set.exclude( pk__in=[self.unit.translation_id, self.unit.source_unit.translation_id] ).first() assert other is not None - Screenshot.objects.create(name="Other language preview", translation=other) + other_screenshot = Screenshot.objects.create( + name="Other language preview", translation=other + ) + for screenshot in ( + other_screenshot, + self.source_screenshot, + self.target_screenshot, + ): + self.cache_text(screenshot, "Hello, world!") response = self.client.get(self.url) self.assertContains(response, "Source preview") self.assertContains(response, "Target preview") @@ -2959,6 +3159,7 @@ def test_other_component(self) -> None: Translation.objects.bulk_create([translation]) screenshot = Screenshot(name="Other component preview", translation=translation) Screenshot.objects.bulk_create([screenshot]) + self.cache_text(screenshot, "Hello, world!") response = self.client.get(self.url) self.assertNotContains(response, "Other component preview") response = self.client.post(self.url, {"screenshot": screenshot.pk}) @@ -2984,6 +3185,7 @@ def test_permissions(self) -> None: def test_language_scope(self) -> None: self.make_language_scoped_user("cs", "screenshot.edit") + self.cache_text(self.source_screenshot, "Hello, world!") response = self.client.get(self.url) self.assertContains(response, "Target preview") diff --git a/weblate/screenshots/views.py b/weblate/screenshots/views.py index d1be83fb16c9..803384ba3dc8 100644 --- a/weblate/screenshots/views.py +++ b/weblate/screenshots/views.py @@ -4,6 +4,7 @@ from __future__ import annotations import os +import re from time import monotonic from typing import TYPE_CHECKING, Any, ClassVar, cast @@ -12,8 +13,8 @@ from django.core.exceptions import PermissionDenied from django.core.paginator import Paginator from django.db import DatabaseError, connection, transaction -from django.db.models import Count -from django.db.models.functions import Length +from django.db.models import Count, F, OuterRef, Q, Subquery, TextField, Value +from django.db.models.functions import Coalesce, Length, Replace from django.http import FileResponse, JsonResponse, QueryDict from django.shortcuts import aget_object_or_404, get_object_or_404, redirect, render from django.template.loader import render_to_string @@ -35,7 +36,7 @@ ScreenshotSelectSearchForm, SearchForm, ) -from weblate.screenshots.models import Screenshot +from weblate.screenshots.models import Screenshot, ScreenshotOCR from weblate.screenshots.ocr import ensure_ocr from weblate.trans.actions import ActionEvents from weblate.trans.models import Component, Unit @@ -537,6 +538,7 @@ def search_results( OCR_MATCH_RESULT_LIMIT = 250 OCR_MATCH_DEADLINE = 2 OCR_MATCH_STATEMENT_TIMEOUT_MS = 1000 +OCR_PICKER_QUERY_LENGTH = 512 def ocr_match_parts(data: dict[str, Any]) -> Iterator[str]: @@ -740,7 +742,7 @@ def get_sources(request: AuthenticatedHttpRequest, pk): def select_screenshot(request: AuthenticatedHttpRequest, unit_id: int) -> HttpResponse: unit = get_object_or_404( Unit.objects.filter_access(request.user).select_related( - "translation__component__project" + "translation__component__project", "translation__component__source_language" ), pk=unit_id, ) @@ -804,8 +806,41 @@ def select_screenshot(request: AuthenticatedHttpRequest, unit_id: int) -> HttpRe screenshots = screenshots.annotate(**annotations).filter(filters).distinct() else: screenshots = screenshots.none() + source_phrase = " ".join(unit.effective_source_string.split()) + if len(source_phrase) <= OCR_PICKER_QUERY_LENGTH and any( + character.isalnum() for character in source_phrase + ): + # A scalar lookup checks the cache for each filtered screenshot by ID. + first_pass: F | Replace = F("first_pass_text") + second_pass: F | Replace = F("second_pass_text") + pattern = re.escape(source_phrase) + if unit.effective_source_language.uses_whitespace(): + pattern = rf"(? {{ screenshot.translation.language }} + {% if screenshot.ocr_match %} + {% translate "Image text match" %} + {% endif %} diff --git a/weblate/trans/tests/test_selenium.py b/weblate/trans/tests/test_selenium.py index f3b24e1b4aa7..7419240d846d 100644 --- a/weblate/trans/tests/test_selenium.py +++ b/weblate/trans/tests/test_selenium.py @@ -5403,21 +5403,30 @@ def test_screenshot_filemask_repository_filename(self) -> None: def test_select_existing_screenshot(self) -> None: project = self.create_component() self.do_login(superuser=True) - unit = Unit.objects.filter( + unit = Unit.objects.get( translation__component__project=project, translation__component__slug="django", translation__language__code="cs", - ).first() - assert unit is not None + source="Add new translation string", + ) screenshot = Screenshot.objects.create( name="Source strings", translation=unit.source_unit.translation ) translated_screenshot = Screenshot.objects.create( - name="Translated strings", translation=unit.translation + name="Other strings", translation=unit.translation + ) + with patch("weblate.screenshots.ocr.schedule_ocr"): + for image in (screenshot, translated_screenshot): + with open(get_test_file("screenshot.png"), "rb") as handle: + image.image.save("picker.png", File(handle)) + ScreenshotOCR.objects.create( + screenshot=screenshot, + data={ + "passes": [ + {"lines": [{"text": "Add new"}, {"text": "translation string"}]} + ], + }, ) - for image in (screenshot, translated_screenshot): - with open(get_test_file("screenshot.png"), "rb") as handle: - image.image.save("picker.png", File(handle)) with self.wait_for_page_load(): self.driver.get(f"{self.live_server_url}{unit.get_absolute_url()}") editor_url = self.driver.current_url @@ -5431,6 +5440,20 @@ def test_select_existing_screenshot(self) -> None: WebDriverWait(self.driver, 5).until( lambda driver: driver.switch_to.active_element == search ) + choices = self.find_elements_now( + By.CSS_SELECTOR, "#screenshot-picker-selection input[name=screenshot]" + ) + self.assertEqual( + [choice.get_attribute("id") for choice in choices], + [ + f"screenshot-choice-{screenshot.pk}", + f"screenshot-choice-{translated_screenshot.pk}", + ], + ) + self.assertTrue(all(not choice.is_selected() for choice in choices)) + self.assert_text_contains( + f'label[for="screenshot-choice-{screenshot.pk}"]', "Image text match" + ) search_button = self.driver.find_element( By.CSS_SELECTOR, "#screenshot-picker-search button" ) @@ -5485,7 +5508,7 @@ def test_select_existing_screenshot(self) -> None: self.assertEqual( self.find_elements_now(By.ID, f"screenshot-choice-{screenshot.pk}"), [] ) - self.assert_text_contains("#screenshot-picker-content", "Translated strings") + self.assert_text_contains("#screenshot-picker-content", "Other strings") search.clear() search.send_keys("unmatched screenshot", Keys.ENTER) WebDriverWait(self.driver, 10).until(staleness_of(search))