diff --git a/packages/uipath/pyproject.toml b/packages/uipath/pyproject.toml index 6c2bfecab..315573e59 100644 --- a/packages/uipath/pyproject.toml +++ b/packages/uipath/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath" -version = "2.14.40" +version = "2.14.40.post1" description = "Python SDK and CLI for UiPath Platform, enabling programmatic interaction with automation services, process management, and deployment tools." readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" diff --git a/packages/uipath/src/uipath/eval/_helpers/_edit_distance.py b/packages/uipath/src/uipath/eval/_helpers/_edit_distance.py new file mode 100644 index 000000000..d13f8ee03 --- /dev/null +++ b/packages/uipath/src/uipath/eval/_helpers/_edit_distance.py @@ -0,0 +1,42 @@ +"""Edit distance shared by the JSON similarity evaluators.""" + + +def levenshtein_distance(source: str, target: str) -> int: + """Return the exact edit distance using linear auxiliary memory.""" + if not source or not target: + return len(source) + len(target) + if source == target: + return 0 + + # Keep the DP rows as short as possible. + if len(source) < len(target): + source, target = target, source + + # Matching edges cannot affect the distance. Use indices so trimming + # does not copy whole strings or let the prefix and suffix overlap. + start = 0 + source_end, target_end = len(source), len(target) + while start < target_end and source[start] == target[start]: + start += 1 + while target_end > start and source[source_end - 1] == target[target_end - 1]: + source_end -= 1 + target_end -= 1 + + target_len = target_end - start + if not target_len: + return source_end - start + + target_middle = target[start:target_end] + previous = list(range(target_len + 1)) + current = [0] * (target_len + 1) + for i in range(start, source_end): + current[0] = i - start + 1 + source_char = source[i] + for j, target_char in enumerate(target_middle, start=1): + current[j] = min( + previous[j] + 1, + current[j - 1] + 1, + previous[j - 1] + (source_char != target_char), + ) + previous, current = current, previous + return previous[-1] diff --git a/packages/uipath/src/uipath/eval/evaluators/json_similarity_evaluator.py b/packages/uipath/src/uipath/eval/evaluators/json_similarity_evaluator.py index 9ab67be22..4e4d2517b 100644 --- a/packages/uipath/src/uipath/eval/evaluators/json_similarity_evaluator.py +++ b/packages/uipath/src/uipath/eval/evaluators/json_similarity_evaluator.py @@ -3,6 +3,7 @@ import math from typing import Any, Tuple +from .._helpers._edit_distance import levenshtein_distance from ..models import ( EvaluationResult, EvaluatorType, @@ -157,7 +158,7 @@ def _compare_strings( total = 1.0 if not expected_string and not actual_string: return 1.0, total - distance = self._levenshtein(expected_string, actual_string) + distance = levenshtein_distance(expected_string, actual_string) max_length = max(len(expected_string), len(actual_string)) similarity = 1.0 - (distance / max_length) if max_length else 1.0 similarity = max(0.0, min(1.0, similarity)) @@ -172,29 +173,5 @@ def _count_leaves(self, token_node: Any) -> float: return sum(self._count_leaves(child_value) for child_value in token_node) return 1.0 - def _levenshtein(self, source_text: str, target_text: str) -> int: - if not source_text: - return len(target_text) - if not target_text: - return len(source_text) - source_len, target_len = len(source_text), len(target_text) - distance_matrix = [[0] * (target_len + 1) for _ in range(source_len + 1)] - for row_idx in range(source_len + 1): - distance_matrix[row_idx][0] = row_idx - for col_idx in range(target_len + 1): - distance_matrix[0][col_idx] = col_idx - for row_idx in range(1, source_len + 1): - for col_idx in range(1, target_len + 1): - substitution_cost = ( - 0 if source_text[row_idx - 1] == target_text[col_idx - 1] else 1 - ) - distance_matrix[row_idx][col_idx] = min( - distance_matrix[row_idx - 1][col_idx] + 1, # deletion - distance_matrix[row_idx][col_idx - 1] + 1, # insertion - distance_matrix[row_idx - 1][col_idx - 1] - + substitution_cost, # substitution - ) - return distance_matrix[source_len][target_len] - def _is_number(self, value: Any) -> bool: return isinstance(value, (int, float)) and not isinstance(value, bool) diff --git a/packages/uipath/src/uipath/eval/evaluators/legacy_json_similarity_evaluator.py b/packages/uipath/src/uipath/eval/evaluators/legacy_json_similarity_evaluator.py index 0fbb99b8e..1e47eb8c2 100644 --- a/packages/uipath/src/uipath/eval/evaluators/legacy_json_similarity_evaluator.py +++ b/packages/uipath/src/uipath/eval/evaluators/legacy_json_similarity_evaluator.py @@ -3,6 +3,7 @@ import math from typing import Any, Tuple, TypeVar +from .._helpers._edit_distance import levenshtein_distance from .._helpers.output_path import resolve_output_path from ..models import EvaluationResult, NumericEvaluationResult from ..models.models import WorkloadExecution @@ -137,7 +138,7 @@ def _compare_strings( total = 1.0 if not expected_string and not actual_string: return 1.0, total - distance = self._levenshtein(expected_string, actual_string) + distance = levenshtein_distance(expected_string, actual_string) max_length = max(len(expected_string), len(actual_string)) similarity = 1.0 - (distance / max_length) if max_length else 1.0 similarity = max(0.0, min(1.0, similarity)) @@ -152,29 +153,5 @@ def _count_leaves(self, token_node: Any) -> float: return sum(self._count_leaves(child_value) for child_value in token_node) return 1.0 - def _levenshtein(self, source_text: str, target_text: str) -> int: - if not source_text: - return len(target_text) - if not target_text: - return len(source_text) - source_len, target_len = len(source_text), len(target_text) - distance_matrix = [[0] * (target_len + 1) for _ in range(source_len + 1)] - for row_idx in range(source_len + 1): - distance_matrix[row_idx][0] = row_idx - for col_idx in range(target_len + 1): - distance_matrix[0][col_idx] = col_idx - for row_idx in range(1, source_len + 1): - for col_idx in range(1, target_len + 1): - substitution_cost = ( - 0 if source_text[row_idx - 1] == target_text[col_idx - 1] else 1 - ) - distance_matrix[row_idx][col_idx] = min( - distance_matrix[row_idx - 1][col_idx] + 1, # deletion - distance_matrix[row_idx][col_idx - 1] + 1, # insertion - distance_matrix[row_idx - 1][col_idx - 1] - + substitution_cost, # substitution - ) - return distance_matrix[source_len][target_len] - def _is_number(self, value: Any) -> bool: return isinstance(value, (int, float)) and not isinstance(value, bool) diff --git a/packages/uipath/tests/cli/evaluators/test_json_similarity_evaluator.py b/packages/uipath/tests/cli/evaluators/test_json_similarity_evaluator.py index 1ce823f22..4746789bc 100644 --- a/packages/uipath/tests/cli/evaluators/test_json_similarity_evaluator.py +++ b/packages/uipath/tests/cli/evaluators/test_json_similarity_evaluator.py @@ -4,11 +4,17 @@ """ import json +import random +import tracemalloc from typing import Any import pytest -from uipath.eval.evaluators import LegacyJsonSimilarityEvaluator +from uipath.eval._helpers._edit_distance import levenshtein_distance +from uipath.eval.evaluators import ( + JsonSimilarityEvaluator, + LegacyJsonSimilarityEvaluator, +) from uipath.eval.evaluators.base_legacy_evaluator import LegacyEvaluationCriteria from uipath.eval.models.models import ( LegacyEvaluatorCategory, @@ -241,3 +247,101 @@ async def test_json_similarity_exact_score_4(self) -> None: ) assert result.score == 43.24977043158861 + + +def _reference_levenshtein(source: str, target: str) -> int: + """Textbook full-matrix edit distance, used to check the optimized one.""" + rows = [[0] * (len(target) + 1) for _ in range(len(source) + 1)] + for i in range(len(source) + 1): + rows[i][0] = i + for j in range(len(target) + 1): + rows[0][j] = j + for i in range(1, len(source) + 1): + for j in range(1, len(target) + 1): + rows[i][j] = min( + rows[i - 1][j] + 1, + rows[i][j - 1] + 1, + rows[i - 1][j - 1] + (source[i - 1] != target[j - 1]), + ) + return rows[-1][-1] + + +class TestLevenshtein: + @pytest.mark.parametrize( + ("source", "target", "expected"), + [ + ("", "", 0), + ("", "abc", 3), + ("abc", "", 3), + ("same", "same", 0), + ("kitten", "sitting", 3), + ("flaw", "lawn", 2), + ("prefix-a-suffix", "prefix-b-suffix", 1), + ("abc", "abcabc", 3), + ("aXa", "aa", 1), + ("prefixX", "prefix", 1), + ("Xsuffix", "suffix", 1), + ("文𐐀olé", "文𐐀olè", 1), + ], + ) + def test_known_distances(self, source: str, target: str, expected: int) -> None: + assert levenshtein_distance(source, target) == expected + assert levenshtein_distance(target, source) == expected + + def test_matches_reference_on_random_strings(self) -> None: + rng = random.Random(7) + for _ in range(300): + source = "".join(rng.choices("abcé漢𐐀", k=rng.randint(0, 12))) + target = "".join(rng.choices("abcé漢𐐀", k=rng.randint(0, 12))) + assert levenshtein_distance(source, target) == _reference_levenshtein( + source, target + ) + + def test_long_identical_strings_do_no_matrix_work(self) -> None: + text = "lorem ipsum " * 170 + tracemalloc.start() + try: + assert levenshtein_distance(text, text) == 0 + _, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + assert peak < 1_000_000 + + def test_memory_stays_linear_for_long_different_strings(self) -> None: + source, target = "ab" * 750, "ba" * 750 + tracemalloc.start() + try: + distance = levenshtein_distance(source, target) + _, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + assert distance == 2 + # The full matrix for these 1500-char strings held about 18 MB. + assert peak < 1_000_000 + + +@pytest.mark.parametrize( + "evaluator_type", [JsonSimilarityEvaluator, LegacyJsonSimilarityEvaluator] +) +def test_long_document_similarity_uses_shared_distance( + evaluator_type: type[JsonSimilarityEvaluator] | type[LegacyJsonSimilarityEvaluator], +) -> None: + evaluator = evaluator_type.__new__(evaluator_type) + expected = "a" * 3500 + "x" + "é" * 3682 + actual = "a" * 3500 + "y" + "é" * 3682 + assert evaluator._compare_strings(expected, actual) == ( + pytest.approx(1 - 1 / len(expected)), + 1.0, + ) + + +def test_empty_against_long_unicode_string_skips_buffer_allocation() -> None: + text = "𐐀" * 1_000_000 + tracemalloc.start() + try: + assert levenshtein_distance(text, "") == len(text) + assert levenshtein_distance("", text) == len(text) + _, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + assert peak < 32_768 diff --git a/packages/uipath/uv.lock b/packages/uipath/uv.lock index 2a951b6b2..ea3b38dfe 100644 --- a/packages/uipath/uv.lock +++ b/packages/uipath/uv.lock @@ -2599,7 +2599,7 @@ wheels = [ [[package]] name = "uipath" -version = "2.14.40" +version = "2.14.40.post1" source = { editable = "." } dependencies = [ { name = "applicationinsights" },