Skip to content
Closed
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
46 changes: 37 additions & 9 deletions packages/flow/openadapt_flow/form_tx/codecs.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@
import re
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
from typing import Any, Sequence
from typing import Any, Optional, Sequence

from openadapt_flow.form_tx.presets import load_words
from openadapt_flow.form_tx.types import (
FieldCodecSpec,
FormCodecKind,
Expand Down Expand Up @@ -54,8 +55,10 @@
r"^(?P<unit>[$€£₹])?\s*(?P<amount>[+-]?(?:[0-9]{1,3}(?:,[0-9]{3})+|[0-9]+)(?:\.[0-9]{1,2})?)$"
)
_PHONE_RE = re.compile(r"^\+?[0-9 ()\t.-]+$")
_TRUTHY_TOKENS = frozenset({"yes", "y", "true", "1"})
_FALSY_TOKENS = frozenset({"no", "n", "false", "0"})
#: The default yes/no texts (data: ``presets/words/true_tokens.json`` and
#: ``false_tokens.json``). A codec may replace them.
_TRUTHY_TOKENS = frozenset(load_words("true_tokens"))
_FALSY_TOKENS = frozenset(load_words("false_tokens"))


class CodecValueError(ValueError):
Expand Down Expand Up @@ -194,17 +197,37 @@ def normalize_currency_cents(raw: Any) -> int:
raise CodecValueError(f"Invalid currency amount: {raw!r}") from exc


def normalize_boolean_yes_no(raw: Any) -> str:
"""Normalize boolean/yes-no values strictly to ``'yes'`` or ``'no'``."""
def normalize_boolean_yes_no(
raw: Any,
true_tokens: Optional[Sequence[str]] = None,
false_tokens: Optional[Sequence[str]] = None,
) -> str:
"""Normalize boolean/yes-no values strictly to ``'yes'`` or ``'no'``.

``true_tokens`` and ``false_tokens`` replace the default texts (a codec's
override); a text in both is ambiguous and raises.
"""
truthy = (
_TRUTHY_TOKENS
if true_tokens is None
else frozenset(collapse_whitespace(t).lower() for t in true_tokens)
)
falsy = (
_FALSY_TOKENS
if false_tokens is None
else frozenset(collapse_whitespace(t).lower() for t in false_tokens)
)
if isinstance(raw, bool):
return "yes" if raw else "no"
if isinstance(raw, int) and raw in (0, 1):
return "yes" if raw == 1 else "no"
if isinstance(raw, str):
tok = collapse_whitespace(raw).lower()
if tok in _TRUTHY_TOKENS:
if tok in truthy and tok in falsy:
raise CodecValueError(f"Ambiguous boolean/yes-no value: {raw!r}")
if tok in truthy:
return "yes"
if tok in _FALSY_TOKENS:
if tok in falsy:
return "no"
raise CodecValueError(f"Ambiguous boolean/yes-no value: {raw!r}")

Expand Down Expand Up @@ -246,7 +269,7 @@ def normalize_with_codec(value: Any, spec: FieldCodecSpec) -> Any:
raise CodecValueError("Currency unit contradicts the field contract")
return normalize_currency_cents(value)
if kind == FormCodecKind.BOOLEAN_YES_NO:
return normalize_boolean_yes_no(value)
return normalize_boolean_yes_no(value, spec.true_tokens, spec.false_tokens)
if kind == FormCodecKind.ENUM_MAP:
probe = collapse_whitespace(str(value)).casefold()
matches: list[str] = []
Expand Down Expand Up @@ -337,7 +360,12 @@ def format_for_text_entry(intended_value: Any, spec: FieldCodecSpec) -> str:
return f"{sign}{whole}"
return f"{sign}{whole}.{minor:02d}"
if spec.kind == FormCodecKind.BOOLEAN_YES_NO:
return "Yes" if normalize_boolean_yes_no(intended_value) == "yes" else "No"
yes = normalize_with_codec(intended_value, spec) == "yes"
# A codec with its own words types its own first word, side by side,
# so what is typed is always a word the read-back accepts.
if yes:
return spec.true_tokens[0] if spec.true_tokens else "Yes"
return spec.false_tokens[0] if spec.false_tokens else "No"
if spec.kind in (FormCodecKind.PHONE_DIGITS, FormCodecKind.INTEGER):
return str(normalize_with_codec(intended_value, spec))
if isinstance(intended_value, (int, float)):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"schema": "openadapt.form-word-list/v1",
"name": "false_tokens",
"about": "Texts a yes/no field reads as no (compared case-folded, whitespace collapsed). A codec may give its own list.",
"words": [
"no",
"n",
"false",
"0"
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"schema": "openadapt.form-word-list/v1",
"name": "true_tokens",
"about": "Texts a yes/no field reads as yes (compared case-folded, whitespace collapsed). A codec may give its own list.",
"words": [
"yes",
"y",
"true",
"1"
]
}
18 changes: 17 additions & 1 deletion packages/flow/openadapt_flow/form_tx/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from enum import Enum
from typing import Any, Callable, Literal, Mapping, Optional, Sequence

from pydantic import BaseModel, ConfigDict, Field, model_validator
from pydantic import BaseModel, ConfigDict, Field, model_serializer, model_validator

FORM_DOSSIER_SCHEMA: Literal["openadapt.form-dossier/v1"] = "openadapt.form-dossier/v1"
UI_PROFILE_SCHEMA: Literal["openadapt.ui-profile/v1"] = "openadapt.ui-profile/v1"
Expand Down Expand Up @@ -256,6 +256,22 @@ class FieldCodecSpec(BaseModel):
date_order: Literal["YMD", "MDY", "DMY"] = "YMD"
currency_symbol: Optional[Literal["$", "€", "£", "₹"]] = None
enum_aliases: dict[str, tuple[str, ...]] = Field(default_factory=dict)
# Overrides of the default yes/no texts (``presets/words/true_tokens.json``
# and ``false_tokens.json``) for a ``boolean_yes_no`` codec. None keeps
# the default. Typed entry uses the first word of a set list.
true_tokens: Optional[tuple[str, ...]] = Field(default=None, min_length=1)
false_tokens: Optional[tuple[str, ...]] = Field(default=None, min_length=1)

@model_serializer(mode="wrap")
def _omit_unset_overrides(self, handler: Any) -> Any:
# An unset override is not written, so a pack made before these
# fields existed dumps (and hashes) exactly as before.
data = handler(self)
if isinstance(data, dict):
for name in ("true_tokens", "false_tokens"):
if data.get(name) is None:
data.pop(name, None)
return data


class FieldAnchorSpec(BaseModel):
Expand Down
81 changes: 81 additions & 0 deletions packages/flow/tests/test_form_tx_presets.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,18 @@ def _secondary_role_qualifiers() -> object:
return pack_compiler._SECONDARY_ROLE_QUALIFIERS


def _true_tokens() -> object:
from openadapt_flow.form_tx import codecs

return codecs._TRUTHY_TOKENS


def _false_tokens() -> object:
from openadapt_flow.form_tx import codecs

return codecs._FALSY_TOKENS


#: word list: (current value, the commit before the move, file, constant)
MOVED_WORDS = {
"primary_entity_kinds": (
Expand All @@ -148,6 +160,18 @@ def _secondary_role_qualifiers() -> object:
"packages/flow/openadapt_flow/form_tx/pack_compiler.py",
"_SECONDARY_ROLE_QUALIFIERS",
),
"true_tokens": (
_true_tokens,
"2f506d6c463aef8098fc8fcc2fd5bc46e55c1829",
"packages/flow/openadapt_flow/form_tx/codecs.py",
"_TRUTHY_TOKENS",
),
"false_tokens": (
_false_tokens,
"2f506d6c463aef8098fc8fcc2fd5bc46e55c1829",
"packages/flow/openadapt_flow/form_tx/codecs.py",
"_FALSY_TOKENS",
),
}


Expand Down Expand Up @@ -241,3 +265,60 @@ def test_a_domain_schema_can_override_the_role_qualifiers() -> None:
ctrl, spec, open_domain.role_qualifiers()
)
assert allowed > 0


def test_a_codec_can_override_the_yes_no_words() -> None:
from openadapt_flow.form_tx.codecs import (
CodecValueError,
format_for_text_entry,
normalize_with_codec,
values_equivalent,
)
from openadapt_flow.form_tx.types import FieldCodecSpec, FormCodecKind

default = FieldCodecSpec(kind=FormCodecKind.BOOLEAN_YES_NO)
assert normalize_with_codec("Yes", default) == "yes"
with pytest.raises(CodecValueError):
normalize_with_codec("Ja", default)
assert format_for_text_entry(True, default) == "Yes"

german = FieldCodecSpec(
kind=FormCodecKind.BOOLEAN_YES_NO,
true_tokens=("Ja", "j"),
false_tokens=("Nein", "n"),
)
assert normalize_with_codec(" ja ", german) == "yes"
assert normalize_with_codec("NEIN", german) == "no"
with pytest.raises(CodecValueError):
normalize_with_codec("yes", german)
assert values_equivalent(True, "Ja", german)
assert format_for_text_entry(True, german) == "Ja"
assert format_for_text_entry(False, german) == "Nein"

french_yes = FieldCodecSpec(kind=FormCodecKind.BOOLEAN_YES_NO, true_tokens=("oui",))
# Only one side overridden: what is typed for each side reads back.
assert format_for_text_entry(True, french_yes) == "oui"
assert (
normalize_with_codec(format_for_text_entry(True, french_yes), french_yes)
== "yes"
)
assert format_for_text_entry(False, french_yes) == "No"
assert normalize_with_codec("No", french_yes) == "no"
with pytest.raises(ValueError):
FieldCodecSpec(kind=FormCodecKind.BOOLEAN_YES_NO, true_tokens=())

both = FieldCodecSpec(
kind=FormCodecKind.BOOLEAN_YES_NO, true_tokens=("x",), false_tokens=("x",)
)
with pytest.raises(CodecValueError):
normalize_with_codec("x", both)


def test_an_unset_yes_no_override_is_not_dumped() -> None:
from openadapt_flow.form_tx.types import FieldCodecSpec, FormCodecKind

spec = FieldCodecSpec(kind=FormCodecKind.BOOLEAN_YES_NO)
assert "true_tokens" not in spec.model_dump(mode="json")
assert FieldCodecSpec.model_validate(spec.model_dump(mode="json")) == spec
set_ = FieldCodecSpec(kind=FormCodecKind.BOOLEAN_YES_NO, true_tokens=("ja",))
assert set_.model_dump(mode="json")["true_tokens"] == ["ja"]
Loading