Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion packages/uipath/pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
42 changes: 42 additions & 0 deletions packages/uipath/src/uipath/eval/_helpers/_edit_distance.py
Original file line number Diff line number Diff line change
@@ -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]
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import math
from typing import Any, Tuple

from .._helpers._edit_distance import levenshtein_distance
from ..models import (
EvaluationResult,
EvaluatorType,
Expand Down Expand Up @@ -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))
Expand All @@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))
Expand All @@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
2 changes: 1 addition & 1 deletion packages/uipath/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading