Skip to content

Utils

Dict

Module evalsense.utils.dict.

Functions:

Name Description
deep_update

Recursively updates a dictionary with data from another dictionary.

deep_update

deep_update(old_dict: dict, new_dict: dict) -> dict

Recursively updates a dictionary with data from another dictionary.

Parameters:

Name Type Description Default
old_dict dict

The dictionary to update.

required
new_dict dict

The new dictionary data.

required
Source code in evalsense/utils/dict.py
def deep_update(old_dict: dict, new_dict: dict) -> dict:
    """Recursively updates a dictionary with data from another dictionary.

    Args:
        old_dict (dict): The dictionary to update.
        new_dict (dict): The new dictionary data.
    """
    old_dict = old_dict.copy()
    for key, value in new_dict.items():
        if key in old_dict and isinstance(value, dict):
            old_dict[key] = deep_update(old_dict[key], value)
        else:
            old_dict[key] = value
    return old_dict

Files

Module evalsense.utils.files.

Functions:

Name Description
download_file

Downloads a file from a URL.

get_remote_file_headers

Gets the HTTP headers of a remote file.

to_safe_filename

Converts a string to a safe filename.

verify_file

Verifies the integrity of a file against the provided metadata.

download_file

download_file(
    url: str,
    target_path: str | Path,
    resume_download: bool = True,
    force_download: bool = False,
    show_progress: bool = True,
    max_attempts: int = 2,
    expected_hash: str | None = None,
    hash_type: str = DEFAULT_HASH_TYPE,
    chunk_size: int = 10 * 1024**2,
) -> None

Downloads a file from a URL.

Parameters:

Name Type Description Default
url str

The URL of the file to download.

required
target_path str | Path

The path to save the downloaded file.

required
resume_download bool

Whether to resume a partially downloaded file when the server provides a strong ETag.

True
force_download bool

Whether to force the download even if the file already exists.

False
show_progress bool

Whether to show download progress.

True
max_attempts int

The maximum number of download attempts. Defaults to 2.

2
expected_hash str

The expected hash of the downloaded file.

None
hash_type str

The hash algorithm to use. Defaults to "sha256".

DEFAULT_HASH_TYPE
chunk_size int

The size of each download chunk in bytes. Defaults to 10MB.

10 * 1024 ** 2

Raises:

Type Description
RuntimeError

If the download fails after the maximum number of attempts.

ValueError

If max_attempts is invalid.

Source code in evalsense/utils/files.py
def download_file(
    url: str,
    target_path: str | Path,
    resume_download: bool = True,
    force_download: bool = False,
    show_progress: bool = True,
    max_attempts: int = 2,
    expected_hash: str | None = None,
    hash_type: str = DEFAULT_HASH_TYPE,
    chunk_size: int = 10 * 1024**2,
) -> None:
    """Downloads a file from a URL.

    Args:
        url (str): The URL of the file to download.
        target_path (str | Path): The path to save the downloaded file.
        resume_download (bool, optional): Whether to resume a partially
            downloaded file when the server provides a strong ETag.
        force_download (bool, optional): Whether to force the download even
            if the file already exists.
        show_progress (bool, optional): Whether to show download progress.
        max_attempts (int, optional): The maximum number of download attempts.
            Defaults to 2.
        expected_hash (str, optional): The expected hash of the downloaded file.
        hash_type (str, optional): The hash algorithm to use. Defaults to "sha256".
        chunk_size (int, optional): The size of each download chunk in bytes.
            Defaults to 10MB.

    Raises:
        RuntimeError: If the download fails after the maximum number of attempts.
        ValueError: If max_attempts is invalid.
    """
    if max_attempts < 1:
        raise ValueError("max_attempts must be 1 or greater")

    target_path = Path(target_path)
    target_name = target_path.name
    target_path.parent.mkdir(parents=True, exist_ok=True)

    # Try to determine the size of the downloaded file and resume support
    remote_file_headers = get_remote_file_headers(url, max_attempts=max_attempts)
    file_size = _content_length(remote_file_headers)
    supports_resume = (
        remote_file_headers.get("Accept-Ranges", "").strip().lower() == "bytes"
        and _identity_encoding(remote_file_headers)
    )

    if (
        not force_download
        and (file_size is not None or expected_hash is not None)
        and verify_file(
            target_path,
            expected_size=file_size,
            expected_hash=expected_hash,
            hash_type=hash_type,
        )
    ):
        return

    # Check existing partial download
    temp_path = target_path.with_suffix(target_path.suffix + ".part")
    validator_path = temp_path.with_suffix(".part.etag")
    partial_path = temp_path if resume_download and supports_resume else None
    headers = {"User-Agent": USER_AGENT, "Accept-Encoding": "identity"}

    # Try to download the file
    try:
        for attempt in Retrying(
            stop=stop_after_attempt(max_attempts),
            wait=wait_exponential(multiplier=1, min=2, max=32),
            reraise=True,
        ):
            with (
                attempt as _,
                FileLock(temp_path.with_suffix(".part.lock")),
                _download_response(url, headers, partial_path, file_size) as (
                    response,
                    write_offset,
                    expected_size,
                ),
            ):
                if expected_size is None and expected_hash is None:
                    raise RuntimeError(
                        "Cannot verify download: no decoded byte count or expected hash"
                    )
                mode = "ab" if write_offset else "wb"
                with (
                    open(temp_path, mode) as file,
                    tqdm(
                        total=expected_size,
                        initial=write_offset,
                        unit="B",
                        unit_scale=True,
                        unit_divisor=1024,
                        disable=not show_progress,
                        desc=f"Downloading {target_name}",
                        leave=False,
                    ) as progress,
                ):
                    if not write_offset:
                        _save_validator(validator_path, url, response)
                    for chunk in response.iter_content(chunk_size):
                        if chunk:
                            file.write(chunk)
                            file.flush()
                            progress.update(len(chunk))

                validator_path.unlink(missing_ok=True)
                if not verify_file(
                    temp_path,
                    expected_size=expected_size,
                    expected_hash=expected_hash,
                    hash_type=hash_type,
                ):
                    temp_path.unlink()
                    raise RuntimeError(
                        f"Downloaded file {target_path} could not be verified."
                    )

                # Success, move the temporary file to the target path
                temp_path.replace(target_path)

    except Exception as e:
        raise RuntimeError(
            f"Download from {url} failed after {max_attempts} attempts: {e}"
        )

get_remote_file_headers

get_remote_file_headers(
    url: str, max_attempts: int = 2
) -> CaseInsensitiveDict[str]

Gets the HTTP headers of a remote file.

Parameters:

Name Type Description Default
url str

The URL of the file.

required
max_attempts int

The maximum number of attempts to get the headers. Defaults to 2.

2

Returns:

Type Description
CaseInsensitiveDict[str]

The headers of the file.

Raises:

Type Description
RuntimeError

If the headers cannot be determined in the maximum number of attempts.

Source code in evalsense/utils/files.py
def get_remote_file_headers(
    url: str, max_attempts: int = 2
) -> CaseInsensitiveDict[str]:
    """Gets the HTTP headers of a remote file.

    Args:
        url (str): The URL of the file.
        max_attempts (int, optional): The maximum number of attempts to get the headers.
            Defaults to 2.

    Returns:
        (CaseInsensitiveDict[str]): The headers of the file.

    Raises:
        RuntimeError: If the headers cannot be determined in the maximum
            number of attempts.
    """
    try:
        for attempt in Retrying(
            stop=stop_after_attempt(max_attempts),
            wait=wait_exponential(multiplier=1, min=2, max=32),
            reraise=True,
        ):
            headers = {"User-Agent": USER_AGENT, "Accept-Encoding": "identity"}
            with (
                attempt as _,
                requests.head(
                    url, headers=headers, allow_redirects=True, timeout=10
                ) as response,
            ):
                response.raise_for_status()
                return response.headers
    except Exception as e:
        raise RuntimeError(f"Failed to get headers for {url}: {e}")
    assert False, "Unreachable code (included as a hint for type checking)"

to_safe_filename

to_safe_filename(name: str) -> str

Converts a string to a safe filename.

Parameters:

Name Type Description Default
name str

The string to convert.

required

Returns:

Type Description
str

The safe filename.

Source code in evalsense/utils/files.py
def to_safe_filename(name: str) -> str:
    """Converts a string to a safe filename.

    Args:
        name (str): The string to convert.

    Returns:
        (str): The safe filename.
    """
    name = unicodedata.normalize("NFKD", name)
    name = regex.sub(r"[^\w\s-_]", "-", name)
    name = regex.sub(r"[-\s]+", "-", name)
    return name

verify_file

verify_file(
    file_path: str | Path,
    expected_size: int | None = None,
    expected_hash: str | None = None,
    hash_type: str = DEFAULT_HASH_TYPE,
    show_progress: bool = True,
    chunk_size: int = 10 * 1024**2,
) -> bool

Verifies the integrity of a file against the provided metadata.

Parameters:

Name Type Description Default
file_path str | Path

The path to the file to verify.

required
expected_size int

The expected size of the file in bytes (skips checking size if None).

None
expected_hash str

The expected hash of the file (skips checking hash if None).

None
hash_type str

The hash algorithm to use. Defaults to "sha256".

DEFAULT_HASH_TYPE
show_progress bool

Whether to show verification progress.

True
chunk_size int

The size of each verification chunk in bytes. Defaults to 10MB.

10 * 1024 ** 2

Returns:

Type Description
bool

True if the file matches the expected metadata, False otherwise.

Raises:

Type Description
ValueError

If the hash type is unsupported.

Source code in evalsense/utils/files.py
def verify_file(
    file_path: str | Path,
    expected_size: int | None = None,
    expected_hash: str | None = None,
    hash_type: str = DEFAULT_HASH_TYPE,
    show_progress: bool = True,
    chunk_size: int = 10 * 1024**2,
) -> bool:
    """Verifies the integrity of a file against the provided metadata.

    Args:
        file_path (str | Path): The path to the file to verify.
        expected_size (int, optional): The expected size of the file in bytes
            (skips checking size if None).
        expected_hash (str, optional): The expected hash of the file (skips checking
            hash if None).
        hash_type (str, optional): The hash algorithm to use. Defaults to "sha256".
        show_progress (bool, optional): Whether to show verification progress.
        chunk_size (int, optional): The size of each verification chunk in bytes.
            Defaults to 10MB.

    Returns:
        (bool): True if the file matches the expected metadata, False otherwise.

    Raises:
        ValueError: If the hash type is unsupported.
    """
    file_path = Path(file_path)
    file_name = file_path.name
    if not file_path.exists():
        return False

    if expected_size is not None and file_path.stat().st_size != expected_size:
        return False

    if expected_hash is not None:
        try:
            hash_func = hashlib.new(hash_type)
        except ValueError:
            raise ValueError(f"Unsupported hash type: {hash_type}")

        with (
            file_path.open("rb") as f,
            tqdm(
                total=expected_size,
                unit="B",
                unit_scale=True,
                unit_divisor=1024,
                disable=not show_progress,
                desc=f"Verifying {file_name}",
                leave=False,
            ) as progress,
        ):
            while chunk := f.read(chunk_size):
                hash_func.update(chunk)
                progress.update(len(chunk))

        computed_hash = hash_func.hexdigest()

        if computed_hash.lower() != expected_hash.lower():
            return False

    return True

🤗 Huggingface

Module evalsense.utils.huggingface.

Functions:

Name Description
disable_dataset_progress_bars

Context manager to disable progress bars for Hugging Face datasets.

disable_dataset_progress_bars

disable_dataset_progress_bars()

Context manager to disable progress bars for Hugging Face datasets.

Source code in evalsense/utils/huggingface.py
@contextmanager
def disable_dataset_progress_bars():
    """Context manager to disable progress bars for Hugging Face datasets."""
    progress_bars_enabled = not are_progress_bars_disabled()
    if progress_bars_enabled:
        disable_progress_bars()
    try:
        yield
    finally:
        if progress_bars_enabled:
            enable_progress_bars()

Text

Classes:

Name Description
WeightedRating

A conditional mean and the returned rating probabilities that support it.

Functions:

Name Description
extract_lines

Extract lines from the text based on a filter function.

extract_score

Parse one complete, in-range, non-negative decimal integer.

extract_ternary_answer

Extract a ternary answer (True/False/Unknown) from the text.

extract_weighted_binary_answer

Extract a weighted binary answer from the model output.

extract_weighted_rating

Average complete rating tokens from a one-token judge request.

extract_weighted_score

Return the conditional rating mean from validated one-token evidence.

format_template

Format a template string with the provided keyword arguments.

parse_ternary_answer

Parse a complete answer, allowing one balanced presentation wrapper.

strip_list_prefix

Remove recognised list prefixes without stripping leading numerical values.

validate_score_range

Require non-negative integer endpoints and a usable normalisation span.

WeightedRating dataclass

A conditional mean and the returned rating probabilities that support it.

Source code in evalsense/utils/text.py
@dataclass(frozen=True)
class WeightedRating:
    """A conditional mean and the returned rating probabilities that support it."""

    score: float
    probabilities: dict[int, float]
    probability_mass: float

extract_lines

extract_lines(
    text: str,
    include_filter_fun: Callable[[str], bool] = lambda _: (
        True
    ),
    trim_lines: bool = True,
) -> list[str]

Extract lines from the text based on a filter function.

Parameters:

Name Type Description Default
text str

The text to extract lines from.

required
include_filter_fun Callable[[str], bool]

A function that takes a line and returns True if it should be included, False otherwise. Defaults to a function that includes all lines.

lambda _: True
trim_lines bool

Whether to trim bullet points, list numbers and whitespace from the beginning/end of each line. Defaults to True.

True

Returns:

Type Description
list[str]

list[str]: A list of extracted lines.

Source code in evalsense/utils/text.py
def extract_lines(
    text: str,
    include_filter_fun: Callable[[str], bool] = lambda _: True,
    trim_lines: bool = True,
) -> list[str]:
    """
    Extract lines from the text based on a filter function.

    Args:
        text (str): The text to extract lines from.
        include_filter_fun (Callable[[str], bool], optional): A function that
            takes a line and returns True if it should be included, False
            otherwise. Defaults to a function that includes all lines.
        trim_lines (bool, optional): Whether to trim bullet points, list numbers
            and whitespace from the beginning/end of each line. Defaults to True.

    Returns:
        list[str]: A list of extracted lines.
    """
    lines = text.splitlines()
    if trim_lines:
        lines = [regex.sub(r"^\s*\d+\.\s*", "", line) for line in lines]
        lines = [line.strip().lstrip("*").lstrip("-").strip() for line in lines]

    return [line for line in lines if include_filter_fun(line)]

extract_score

extract_score(
    text: str, min_score: int = 1, max_score: int = 10
) -> int

Parse one complete, in-range, non-negative decimal integer.

Outer whitespace and leading zeroes are accepted. Signs, fractions, decimals, wrappers and explanatory text are rejected instead of searching for digits.

Parameters:

Name Type Description Default
text str

The complete judge response.

required
min_score int

The minimum valid score. Defaults to 1.

1
max_score int

The maximum valid score. Defaults to 10.

10

Returns:

Name Type Description
int int

The validated integer rating.

Raises:

Type Description
ValueError

If the response is not a complete in-range integer.

Source code in evalsense/utils/text.py
def extract_score(text: str, min_score: int = 1, max_score: int = 10) -> int:
    """Parse one complete, in-range, non-negative decimal integer.

    Outer whitespace and leading zeroes are accepted. Signs, fractions, decimals,
    wrappers and explanatory text are rejected instead of searching for digits.

    Args:
        text (str): The complete judge response.
        min_score (int): The minimum valid score. Defaults to 1.
        max_score (int): The maximum valid score. Defaults to 10.

    Returns:
        int: The validated integer rating.

    Raises:
        ValueError: If the response is not a complete in-range integer.
    """
    validate_score_range(min_score, max_score)
    if not isinstance(text, str) or not regex.fullmatch(r"[0-9]+", text.strip()):
        raise ValueError("Expected one complete integer score without extra text.")
    try:
        score = int(text.strip())
    except ValueError:
        raise ValueError("Integer score exceeds the supported range.") from None
    if not min_score <= score <= max_score:
        raise ValueError("Integer score is outside the configured rating scale.")
    return score

extract_ternary_answer

extract_ternary_answer(
    text: str,
    binary_only: Literal[True],
    unknown_on_mismatch: Literal[False] = False,
) -> bool
extract_ternary_answer(
    text: str,
    binary_only: Literal[False],
    unknown_on_mismatch: bool = True,
) -> bool | None
extract_ternary_answer(
    text: str,
    binary_only: bool,
    unknown_on_mismatch: bool = True,
) -> bool | None

Extract a ternary answer (True/False/Unknown) from the text.

This legacy helper searches within text and can return unknown on mismatch. Use parse_ternary_answer for complete-response validation with distinct errors.

Valid answers are 'yes', 'no', 'true', 'false', 'unknown', and 'I don't know'.

Parameters:

Name Type Description Default
text str

The text to extract the answer from.

required
binary_only bool

If True, only 'yes' or 'no' are valid answers.

required
unknown_on_mismatch bool

If True, return None for answers not matching any of the valid answers. If False, raise an error. Only relevant if binary_only is False. Defaults to True.

True

Returns:

Type Description
bool | None

bool | None: The extracted answer - bool for True/False, None for Unknown.

Source code in evalsense/utils/text.py
def extract_ternary_answer(
    text: str, binary_only: bool, unknown_on_mismatch: bool = True
) -> bool | None:
    """
    Extract a ternary answer (True/False/Unknown) from the text.

    This legacy helper searches within text and can return unknown on mismatch.
    Use ``parse_ternary_answer`` for complete-response validation with distinct errors.

    Valid answers are 'yes', 'no', 'true', 'false', 'unknown', and 'I don't know'.

    Args:
        text (str): The text to extract the answer from.
        binary_only (bool): If True, only 'yes' or 'no' are valid answers.
        unknown_on_mismatch (bool): If True, return None for answers not
            matching any of the valid answers. If False, raise an error.
            Only relevant if binary_only is False. Defaults to True.

    Returns:
        bool | None: The extracted answer - bool for True/False, None for Unknown.
    """
    pattern = r"\b(?:yes|no|true|false|unknown|i don't know)\b"
    match = regex.search(pattern, text, regex.IGNORECASE)
    if match:
        answer = match.group(0).lower()
        if answer in ["yes", "true"]:
            return True
        elif answer in ["no", "false"]:
            return False
        else:
            if binary_only:
                raise ValueError(
                    "Binary answer expected, but 'unknown' or 'I don't know' found."
                )
            return None
    if not binary_only and unknown_on_mismatch:
        return None
    raise ValueError(f"Unable to extract a binary answer from text: {text}.")

extract_weighted_binary_answer

extract_weighted_binary_answer(
    output: ModelOutput,
) -> float

Extract a weighted binary answer from the model output.

Parameters:

Name Type Description Default
output ModelOutput

The model output containing logprobs.

required

Returns:

Name Type Description
float float

The model probability of the answer being True.

Source code in evalsense/utils/text.py
def extract_weighted_binary_answer(output: ModelOutput) -> float:
    """
    Extract a weighted binary answer from the model output.

    Args:
        output (ModelOutput): The model output containing logprobs.

    Returns:
        float: The model probability of the answer being True.
    """
    valid_options = ["true", "false", "yes", "no"]

    def normalise_token(token: str) -> str:
        return token.strip().replace("▁", "").replace("_", "").lower()

    def match_target_token(token: str) -> bool:
        return token in valid_options

    def token_parsing_function(token: str) -> bool:
        if token not in valid_options:
            raise ValueError

        return token in ["true", "yes"]

    probabilities = _eval_weighted_options(
        output,
        normalise_token,
        match_target_token,
        token_parsing_function,
    )

    return probabilities[True]

extract_weighted_rating

extract_weighted_rating(
    output: ModelOutput,
    min_score: int = 1,
    max_score: int = 10,
) -> WeightedRating

Average complete rating tokens from a one-token judge request.

Every allowed rating must occur in the returned alternatives. The result is conditional on the valid rating tokens in that table, whose probabilities are renormalised. It is not a full-sequence probability estimate.

Callers must request at most one output token. Missing ratings, multi-token responses and inconsistent probability evidence raise ValueError.

Source code in evalsense/utils/text.py
def extract_weighted_rating(
    output: ModelOutput, min_score: int = 1, max_score: int = 10
) -> WeightedRating:
    """Average complete rating tokens from a one-token judge request.

    Every allowed rating must occur in the returned alternatives. The result is
    conditional on the valid rating tokens in that table, whose probabilities
    are renormalised. It is not a full-sequence probability estimate.

    Callers must request at most one output token. Missing ratings, multi-token
    responses and inconsistent probability evidence raise ValueError.
    """
    if len(output.choices) != 1:
        raise ValueError("Weighted ratings require exactly one judge response.")
    target_score = extract_score(output.completion, min_score, max_score)
    if output.completion.strip() != str(target_score):
        raise ValueError(
            "Weighted ratings require canonical integer labels without leading zeroes."
        )
    logprobs = output.choices[0].logprobs
    if logprobs is None or len(logprobs.content) != 1:
        raise ValueError(
            "Weighted ratings require exactly one output token with logprobs. "
            "Use logprobs=False for an explicit sampled rating."
        )
    token = logprobs.content[0]
    if not math.isfinite(token.logprob) or token.logprob > 0:
        raise ValueError(
            "The sampled rating token must have a finite non-positive log probability."
        )

    def rating_label(text: str) -> int:
        label = text.strip().removeprefix("▁").strip()
        value = extract_score(label, min_score, max_score)
        if label != str(value):
            raise ValueError(
                "Weighted rating tokens must use canonical integer labels."
            )
        return value

    try:
        matches_response = rating_label(token.token) == target_score
    except ValueError:
        matches_response = False
    if not matches_response:
        raise ValueError(
            "The single weighted rating token does not match the complete response."
        )
    if not token.top_logprobs:
        raise ValueError("Top logprobs are required for weighted ratings.")

    probabilities: dict[int, float] = defaultdict(float)
    seen: set[str] = set()
    sampled_logprob: float | None = None
    total_mass = 0.0
    for alternative in token.top_logprobs:
        if alternative.token in seen:
            raise ValueError("Weighted rating alternatives contain a duplicate token.")
        seen.add(alternative.token)
        logprob = alternative.logprob
        if math.isnan(logprob) or logprob > 0:
            raise ValueError(
                "Weighted rating log probabilities must be non-positive and not NaN."
            )
        mass = math.exp(logprob)
        total_mass += mass
        if alternative.token == token.token:
            sampled_logprob = logprob
        try:
            rating = rating_label(alternative.token)
        except ValueError:
            continue
        probabilities[rating] += mass

    if sampled_logprob is None or not math.isclose(
        sampled_logprob, token.logprob, rel_tol=1e-6, abs_tol=1e-6
    ):
        raise ValueError(
            "The sampled token must have matching logprobs in the alternatives."
        )
    if total_mass > 1 + 1e-5:
        raise ValueError(
            "Reported token probabilities must have mass no greater than one."
        )
    if len(probabilities) != max_score - min_score + 1:
        missing = []
        for rating in range(min_score, max_score + 1):
            if rating not in probabilities:
                missing.append(str(rating))
                if len(missing) == 5:
                    break
        raise ValueError(
            "Weighted ratings require a complete single-token alternative for every "
            f"rating on the scale. Missing ratings include {', '.join(missing)}. "
            "Multi-token labels and incomplete top_logprobs are unsupported. "
            "Increase top_logprobs where supported, or use logprobs=False "
            "for an explicit sampled rating."
        )
    rating_mass = math.fsum(probabilities.values())
    if not 0 < rating_mass <= 1 + 1e-5:
        raise ValueError(
            "Valid rating probabilities must have positive finite mass no greater than one."
        )
    normalised = {rating: mass / rating_mass for rating, mass in probabilities.items()}
    return WeightedRating(
        score=math.fsum(
            rating * probability for rating, probability in normalised.items()
        ),
        probabilities=normalised,
        probability_mass=rating_mass,
    )

extract_weighted_score

extract_weighted_score(
    output: ModelOutput,
    min_score: int = 1,
    max_score: int = 10,
) -> float

Return the conditional rating mean from validated one-token evidence.

See extract_weighted_rating for the token and probability requirements.

Source code in evalsense/utils/text.py
def extract_weighted_score(
    output: ModelOutput, min_score: int = 1, max_score: int = 10
) -> float:
    """Return the conditional rating mean from validated one-token evidence.

    See extract_weighted_rating for the token and probability requirements.
    """
    return extract_weighted_rating(output, min_score, max_score).score

format_template

format_template(template: str, **kwargs) -> str

Format a template string with the provided keyword arguments.

Parameters:

Name Type Description Default
template str

The template string to format.

required
**kwargs dict[str, any]

Keyword arguments to replace placeholders in the template.

{}

Returns:

Name Type Description
str str

The formatted string.

Source code in evalsense/utils/text.py
def format_template(template: str, **kwargs) -> str:
    """
    Format a template string with the provided keyword arguments.

    Args:
        template (str): The template string to format.
        **kwargs (dict[str, any]): Keyword arguments to replace placeholders in the template.

    Returns:
        str: The formatted string.
    """
    try:
        return template.format(**kwargs)
    except KeyError as e:
        raise KeyError(
            f"Missing key in template formatting: {str(e)}. "
            f"The provided keys were: {list(kwargs.keys())}. "
            "Ensure all placeholders in the template are provided in kwargs."
        )

parse_ternary_answer

parse_ternary_answer(
    text: str, *, binary_only: bool = False
) -> bool | None

Parse a complete answer, allowing one balanced presentation wrapper.

Parameters:

Name Type Description Default
text str

A complete yes/no/true/false/unknown/"I don't know" label, ignoring case and surrounding whitespace. A single quote pair (straight or typographic), Markdown emphasis (, *, _, __) or inline backticks may wrap the label. One final period or exclamation mark is allowed inside or outside the wrapper, but not both. Nested wrappers, explanations, JSON and conflicting labels are rejected.

required
binary_only bool

Reject explicit unknown answers when True.

False

Returns:

Type Description
bool | None

bool | None: True or False for a binary label, or None for an explicit unknown. Invalid text never returns None.

Raises:

Type Description
ValueError

If the complete response does not match the accepted format, or an unknown label is used in binary-only mode. Messages omit text.

Source code in evalsense/utils/text.py
def parse_ternary_answer(text: str, *, binary_only: bool = False) -> bool | None:
    """Parse a complete answer, allowing one balanced presentation wrapper.

    Args:
        text (str): A complete yes/no/true/false/unknown/"I don't know" label,
            ignoring case and surrounding whitespace. A single quote pair
            (straight or typographic), Markdown emphasis (*, **, _, __) or inline
            backticks may wrap the label. One final period or exclamation mark
            is allowed inside or outside the wrapper, but not both. Nested
            wrappers, explanations, JSON and conflicting labels are rejected.
        binary_only (bool): Reject explicit unknown answers when True.

    Returns:
        bool | None: True or False for a binary label, or None for an explicit
            unknown. Invalid text never returns None.

    Raises:
        ValueError: If the complete response does not match the accepted format,
            or an unknown label is used in binary-only mode. Messages omit text.
    """
    answer = " ".join(text.strip().casefold().split())
    label_pattern = r"(yes|no|true|false|unknown|i don['’]t know)"
    match = regex.fullmatch(label_pattern + r"[.!]?", answer)
    if match is None:
        outside_punctuation = answer.endswith((".", "!"))
        wrapped = answer[:-1] if outside_punctuation else answer
        for opening, closing in (
            ('"', '"'),
            ("'", "'"),
            ("“", "”"),
            ("‘", "’"),
            ("**", "**"),
            ("__", "__"),
            ("*", "*"),
            ("_", "_"),
            ("`", "`"),
        ):
            if wrapped.startswith(opening) and wrapped.endswith(closing):
                inner = wrapped[len(opening) : len(wrapped) - len(closing)].strip()
                match = regex.fullmatch(
                    label_pattern + ("" if outside_punctuation else r"[.!]?"), inner
                )
                if match is not None:
                    break
    if match is None:
        raise ValueError("Expected a complete yes/no/unknown answer.")
    label = match.group(1)
    if label in ("yes", "true"):
        return True
    if label in ("no", "false"):
        return False
    if binary_only:
        raise ValueError("A comparison must be yes/no, not unknown.")
    return None

strip_list_prefix

strip_list_prefix(text: str) -> str

Remove recognised list prefixes without stripping leading numerical values.

Prefixes are -, *, •, 1., 1) or [1]. They must be followed by whitespace or, for unspaced lists, a letter. Ambiguous prefixes before numbers or punctuation are retained: 1.5 mg and -2 mg are not list numbering. Leading/trailing whitespace is removed; internal text is kept.

Source code in evalsense/utils/text.py
def strip_list_prefix(text: str) -> str:
    """Remove recognised list prefixes without stripping leading numerical values.

    Prefixes are ``-``, ``*``, ``•``, ``1.``, ``1)`` or ``[1]``. They must be
    followed by whitespace or, for unspaced lists, a letter. Ambiguous prefixes
    before numbers or punctuation are retained: ``1.5 mg`` and ``-2 mg`` are not
    list numbering. Leading/trailing whitespace is removed; internal text is kept.
    """
    prefix = r"(?:[-*•]|\d+[.)]|\[\d+\])"
    return regex.sub(rf"^\s*(?:{prefix}\s+|{prefix}(?=\p{{L}}))+", "", text).strip()

validate_score_range

validate_score_range(
    min_score: int,
    max_score: int,
    *,
    normalise: bool = False,
) -> None

Require non-negative integer endpoints and a usable normalisation span.

Source code in evalsense/utils/text.py
def validate_score_range(
    min_score: int, max_score: int, *, normalise: bool = False
) -> None:
    """Require non-negative integer endpoints and a usable normalisation span."""
    if type(min_score) is not int or type(max_score) is not int:
        raise ValueError(
            "Rating scale endpoints must be integers, not booleans or floats."
        )
    if min_score < 0 or max_score < min_score:
        raise ValueError("Rating scale must satisfy 0 <= min_score <= max_score.")
    if type(normalise) is not bool:
        raise ValueError("normalise must be a boolean.")
    if normalise and min_score == max_score:
        raise ValueError("Normalised ratings require min_score < max_score.")