Skip to content

unaiverse.uai.coerce

An answer to a form reaches a world in two shapes. A widget sends a reply block whose values are already canonical: a JSON number for a number field, true for a bool, an option value for a select. A person typing by hand or a language model, on the other hand, writes words such as 180 cm, sì or Vegetarian. This module turns both into the same canonical value and re-checks the constraints that the field declares. coerce_text reads a string, check_canonical type-checks a value that came inside a block and both then call check_constraints. An out-of-range value is therefore caught the same way on both paths. The narrative guide is Interactive messages.

Nothing in the module raises. Every function returns a Coerced with either a value or a reason from the closed list of the contract.

Reason Constant Meaning
type ISSUE_TYPE The input cannot be converted to a value of the declared type.
below_min ISSUE_BELOW_MIN A number, integer or date under min. A multi-select with fewer than min items.
above_max ISSUE_ABOVE_MAX A number, integer or date over max. A multi-select with more than max items.
too_long ISSUE_TOO_LONG A text or textarea value longer than maxLength.
format ISSUE_FORMAT A text value that does not satisfy its format.
unknown_option ISSUE_UNKNOWN_OPTION A select item that matches no option.

Callers import from unaiverse.uai. The package re-exports Coerced, coerce_text, check_canonical, check_constraints, parse_number and parse_date. The function resolve_option and the patterns EMAIL_RE, URL_RE, TEL_RE, DIGIT_RE, DECIMAL_COMMA_RE and NUMBER_RE are used inside the package and are documented here for completeness.

Object Role
Coerced The outcome (ok, value, reason).
coerce_text Converts a written string into the canonical value of a field.
check_canonical Checks the type of a value that arrived in canonical form.
check_constraints Checks the constraints of a field on a canonical value.
parse_number, parse_date Tolerant readers of numbers and dates.
resolve_option Maps a written option to its value.
from unaiverse.uai import coerce_text, check_canonical

height = {"name": "height", "type": "number", "unit": "cm", "min": 50, "max": 250}
coerce_text(height, "180,5 CM")   # Coerced(ok=True, value=180.5, reason=None)
coerce_text(height, "999")        # Coerced(ok=False, value=None, reason='above_max')
check_canonical(height, "180")    # Coerced(ok=False, value=None, reason='type')

Coerced

Bases: NamedTuple

A typing.NamedTuple with three fields. It can be read as a tuple (ok, value, reason = result) or by attribute (result.ok).

Field Type Default Meaning
ok bool required True when the input produced a valid canonical value.
value any None The canonical value when ok is True. It stays None on failure.
reason str or None None One of the six reasons above when ok is False. It stays None on success.

coerce_text

coerce_text(f: dict, raw, lang=None, allow_decimal_comma: bool = True) -> Coerced
Source code in unaiverse/uai/coerce.py
def coerce_text(f: dict, raw, lang=None, allow_decimal_comma: bool = True) -> Coerced:
    """Coerces a string to the canonical value of a field.

    Args:
        f: A validated field spec.
        raw: What the human or the model wrote for that field.
        lang: Language of the form, which selects the accepted words and date shapes.
        allow_decimal_comma: False in the positional csv rung, where a comma is a separator.
    """
    s = ("" if raw is None else str(raw)).strip()
    _, t = template_for(lang)

    if f["type"] in ("text", "textarea"):
        return check_constraints(f, s)
    if f["type"] in ("number", "integer"):
        n = parse_number(s, f.get("unit"), allow_decimal_comma)
        if n is None:
            return _fail(ISSUE_TYPE)
        if f["type"] == "integer" and not is_int(n):
            return _fail(ISSUE_TYPE)
        return check_constraints(f, n)
    if f["type"] == "bool":
        w = s.lower()
        if w in t["true_words"]:
            return _ok(True)
        if w in t["false_words"]:
            return _ok(False)
        return _fail(ISSUE_TYPE)
    if f["type"] == "date":
        iso = parse_date(s, t)
        if iso is None:
            return _fail(ISSUE_TYPE)
        return check_constraints(f, iso)
    if f["type"] == "select":
        if f["max"] == 1:
            v = resolve_option(f, s)
            if v is None:
                return _fail(ISSUE_UNKNOWN_OPTION)
            return check_constraints(f, v)
        values = []
        for item in [x.strip() for x in s.split(",")]:
            if not item:
                continue
            v = resolve_option(f, item)
            if v is None:
                return _fail(ISSUE_UNKNOWN_OPTION)
            if v not in values:
                values.append(v)
        return check_constraints(f, values)
    return check_constraints(f, s)

Reads what a person or a model wrote for one field and returns its canonical value. The interpreter calls it at rungs 2, 3 and 4 of the ladder (see interpret_reply).

Argument Type Default Meaning
f dict required One validated field spec.
raw any required The written answer. None becomes "" and any other value goes through str. The result is stripped of leading and trailing whitespace before reading.
lang str or None None The language of the form. It selects the words accepted for bool and the date shapes (see template_for). An unknown or missing language falls back to English.
allow_decimal_comma bool True Accept 180,5 as 180.5. The interpreter passes False at the csv rung because there a comma separates the values.

Each field type reads the input in its own way.

Type Accepted input Canonical value
text, textarea Anything. The stripped string, then maxLength and format are checked.
number What parse_number accepts with the declared unit. A float.
integer As number. A number with a fractional part gives the reason type and is never rounded. A float with an integral value.
bool it: sì, si, vero, yes, true, 1 and no, falso, false, 0. en: yes, true, 1, y and no, false, 0, n. The comparison ignores case. True or False.
date What parse_date accepts. An ISO string YYYY-MM-DD.
select with max 1 A value or a label, matched by resolve_option. The option value.
select with max above 1 Items separated by commas, each resolved like a single option. Empty items are skipped and repeated options are kept once. A list of option values in the order written.
colour = {"name": "c", "type": "select", "max": 2, "min": 1,
          "options": [{"value": "r", "label": "Red"}, {"value": "g", "label": "Green"},
                      {"value": "b", "label": "Blue"}]}
coerce_text(colour, "red, g, Blue")   # Coerced(ok=False, value=None, reason='above_max')
coerce_text(colour, "")               # Coerced(ok=False, value=None, reason='below_min')
coerce_text(colour, "red, pink")      # Coerced(ok=False, value=None, reason='unknown_option')
coerce_text({"name": "d", "type": "date"}, "31/12/2023", lang="it")   # value '2023-12-31'
coerce_text({"name": "b", "type": "bool"}, "sì", lang="en")           # reason 'type'

Number and integer values come back as Python float objects. An integer field answered with 42 yields 42.0. Serialisation writes it as 42 (see num_to_text) and a world that needs an int converts it. The two languages accept different words (English lacks sì and Italian lacks n). Because a bool field declares no constraint, none is checked.

check_canonical

check_canonical(f: dict, v) -> Coerced
Source code in unaiverse/uai/coerce.py
def check_canonical(f: dict, v) -> Coerced:
    """Type-checks a value that arrived already canonical, in a reply block.

    It is never re-parsed: the string "180" for a number field is a type issue, not the number 180.
    """
    if f["type"] in ("text", "textarea"):
        return check_constraints(f, v) if isinstance(v, str) else _fail(ISSUE_TYPE)
    if f["type"] == "number":
        return check_constraints(f, v) if is_num(v) else _fail(ISSUE_TYPE)
    if f["type"] == "integer":
        return check_constraints(f, v) if is_int(v) else _fail(ISSUE_TYPE)
    if f["type"] == "bool":
        return _ok(v) if isinstance(v, bool) else _fail(ISSUE_TYPE)
    if f["type"] == "date":
        return check_constraints(f, v) if is_iso_date(v) else _fail(ISSUE_TYPE)
    if f["type"] == "select":
        known = {o["value"] for o in f["options"]}
        if f["max"] == 1:
            if not isinstance(v, str):
                return _fail(ISSUE_TYPE)
            return check_constraints(f, v) if v in known else _fail(ISSUE_UNKNOWN_OPTION)
        if not isinstance(v, list) or not all(isinstance(x, str) for x in v):
            return _fail(ISSUE_TYPE)
        if not all(x in known for x in v):
            return _fail(ISSUE_UNKNOWN_OPTION)
        return check_constraints(f, list(dict.fromkeys(v)))
    return check_constraints(f, v) if isinstance(v, str) else _fail(ISSUE_TYPE)

Type-checks a value that arrived inside a reply block and then applies check_constraints. The value is never parsed again and the string "180" for a number field is therefore a type issue and not the number 180. The interpreter calls it at rung 1 through apply_canonical. encode_reply calls it to leave out values that would fail on the receiving side.

Argument Type Meaning
f dict One validated field spec.
v any The value from the block.
Type Accepted value
text, textarea A str.
number A finite int or float that is not a bool.
integer An integer in the JavaScript sense. 3 and 3.0 both pass and 3.0 stays a float.
bool A bool. No constraint is checked.
date An ISO date string that exists in the calendar.
select with max 1 A str that is one of the option values. Another string gives unknown_option and any other type gives type.
select with max above 1 A list of option values. Duplicates are removed (first occurrence kept) before the count is checked.
check_canonical(colour, ["r", "r"])   # Coerced(ok=True, value=['r'], reason=None)
check_canonical(colour, "r")          # Coerced(ok=False, value=None, reason='type')
check_canonical({"name": "b", "type": "bool"}, 1)   # Coerced(ok=False, value=None, reason='type')

check_constraints

check_constraints(f: dict, v) -> Coerced
Source code in unaiverse/uai/coerce.py
def check_constraints(f: dict, v) -> Coerced:
    """Re-checks the constraints declared by a field on an already canonical value."""
    if f["type"] == "text":
        if "maxLength" in f and len(v) > f["maxLength"]:
            return _fail(ISSUE_TOO_LONG)
        fmt = f.get("format")
        if fmt == "email" and EMAIL_RE.fullmatch(v) is None:
            return _fail(ISSUE_FORMAT)
        if fmt == "url" and URL_RE.fullmatch(v) is None:
            return _fail(ISSUE_FORMAT)
        if fmt == "tel" and (TEL_RE.fullmatch(v) is None or len(DIGIT_RE.findall(v)) < 5):
            return _fail(ISSUE_FORMAT)
        return _ok(v)
    if f["type"] == "textarea":
        if "maxLength" in f and len(v) > f["maxLength"]:
            return _fail(ISSUE_TOO_LONG)
        return _ok(v)
    if f["type"] in ("number", "integer", "date"):
        if "min" in f and v < f["min"]:
            return _fail(ISSUE_BELOW_MIN)
        if "max" in f and v > f["max"]:
            return _fail(ISSUE_ABOVE_MAX)
        return _ok(v)
    if f["type"] == "select":
        if f["max"] == 1:
            return _ok(v)
        if "min" in f and len(v) < f["min"]:
            return _fail(ISSUE_BELOW_MIN)
        if len(v) > f["max"]:
            return _fail(ISSUE_ABOVE_MAX)
        return _ok(v)
    return _ok(v)

Re-checks the constraints of a field on a value that already has the right type. It does not check the type again. The checks follow the field type.

Type Checks, in order
text maxLength (reason too_long) and then format (reason format). email needs x@y.z with no whitespace. url needs http:// or https:// followed by a host. tel accepts digits, spaces, +, -, ( and ) with at least 5 digits.
textarea maxLength.
number, integer, date min (reason below_min) and then max (reason above_max). Dates compare as ISO strings.
select with max above 1 The number of items against min and max. A single-choice select has no constraint to check.

Any other type passes untouched. Lengths are counted in Python characters (code points).

check_constraints({"name": "t", "type": "text", "format": "tel"}, "+39 055 1234")
# Coerced(ok=True, value='+39 055 1234', reason=None)
check_constraints({"name": "e", "type": "text", "format": "email", "maxLength": 5}, "a@b.co")
# Coerced(ok=False, value=None, reason='too_long')

parse_number

parse_number(s: str, unit=None, allow_decimal_comma: bool = True)
Source code in unaiverse/uai/coerce.py
def parse_number(s: str, unit=None, allow_decimal_comma: bool = True):
    """Reads a number from text, stripping the declared unit and, where allowed, the decimal comma."""
    x = s.strip()
    if unit:
        u = unit.lower()
        if x.lower().endswith(u):
            x = x[:len(x) - len(u)].strip()
    if allow_decimal_comma and DECIMAL_COMMA_RE.fullmatch(x) is not None:
        x = x.replace(",", ".")
    if NUMBER_RE.fullmatch(x) is None:
        return None
    try:
        n = float(x)
    except ValueError:
        return None
    return n if n == n and n not in (float("inf"), float("-inf")) else None

Reads a number from a string. It returns a float and returns None when the string is not a number.

Argument Type Default Meaning
s str required The text. Leading and trailing whitespace is ignored.
unit str or None None The unit of the field. When the text ends with it (case ignored) the unit is cut off first.
allow_decimal_comma bool True Read -?digits,digits as a decimal number.

The accepted shape after these two steps is an optional minus, then digits with an optional decimal point (5., .5, 180.5). Exponents, a leading +, thousands separators and NaN are refused.

Input unit="cm" allow_decimal_comma=False
"180" 180.0 180.0
"180 cm", "180CM" 180.0 180.0
"180,5" 180.5 None
"1,234" 1.234 None
".5", "5." 0.5, 5.0 0.5, 5.0
"1e3" None None

A thousands separator written with a comma is read as a decimal comma: "1,234" becomes 1.234.

parse_date

parse_date(s: str, t: dict)
Source code in unaiverse/uai/coerce.py
def parse_date(s: str, t: dict):
    """Reads a date from text: ISO first, then the shapes of the language."""
    if is_iso_date(s):
        return s
    for pattern, order in t["date_shapes"]:
        m = pattern.fullmatch(s)
        if m is None:
            continue
        g = {order[0]: m.group(1), order[1]: m.group(2), order[2]: m.group(3)}
        iso = f"{g['y']}-{g['m'].zfill(2)}-{g['d'].zfill(2)}"
        if is_iso_date(iso):
            return iso
    return None

Reads a date and returns it as an ISO string. A text that is not a date gives None. The argument s is the stripped text and t is a template table (a value of TEMPLATES). An ISO date is accepted first. Then each shape of the language is tried with one or two digits for day and month: D/M/YYYY or D-M-YYYY (day first) in Italian and M/D/YYYY or M-D-YYYY (month first) in English. The result must exist in the calendar.

from unaiverse.uai import TEMPLATES, parse_date

parse_date("03/04/2024", TEMPLATES["en"])   # '2024-03-04'
parse_date("03/04/2024", TEMPLATES["it"])   # '2024-04-03'
parse_date("31-12-2023", TEMPLATES["en"])   # None (there is no month 31)

resolve_option

resolve_option(f: dict, s: str)
Source code in unaiverse/uai/coerce.py
def resolve_option(f: dict, s: str):
    """Maps a written option (value or label, exact or normalised) to its canonical value."""
    for o in f["options"]:
        if o["value"] == s:
            return o["value"]
    for o in f["options"]:
        if o["label"] == s:
            return o["value"]
    n = normalize_label(s)
    for o in f["options"]:
        if normalize_label(o["value"]) == n:
            return o["value"]
    for o in f["options"]:
        if normalize_label(o["label"]) == n:
            return o["value"]
    return None

Maps one written option to its value and returns None when no option matches. The argument f is a validated select field and s the stripped text. Four passes run in this order and the first match wins: (1) an exact value, (2) an exact label, (3) a value equal after normalize_label, (4) a label equal after normalisation.

sel = {"name": "c", "type": "select", "max": 1,
       "options": [{"value": "r", "label": "Dark Red"}, {"value": "g", "label": "Green"}]}
resolve_option(sel, "dark   RED")   # 'r'
resolve_option(sel, "G")            # 'g'
resolve_option(sel, "blue")         # None

EMAIL_RE module-attribute

EMAIL_RE = re.compile('[^\\s@]+@[^\\s@]+\\.[^\\s@]+')

The pattern of the email format, applied with fullmatch: characters other than whitespace and @, then @, then a host with at least one dot.

URL_RE module-attribute

URL_RE = re.compile('https?://[^\\s/$.?#].[^\\s]*', re.IGNORECASE)

The pattern of the url format, applied with fullmatch and without regard to case: http:// or https:// followed by a host and an optional path with no whitespace. A url answer may use http even though the media URLs of a block may not.

TEL_RE module-attribute

TEL_RE = re.compile('[+()0-9\\s-]+')

The pattern of the characters allowed in a tel value: digits, whitespace, +, -, ( and ). DIGIT_RE then counts the digits.

DIGIT_RE module-attribute

DIGIT_RE = re.compile('[0-9]')

The pattern of one ASCII digit. A tel value needs at least five matches.

DECIMAL_COMMA_RE module-attribute

DECIMAL_COMMA_RE = re.compile('-?[0-9]+,[0-9]+')

The pattern -?[0-9]+,[0-9]+ of a number written with a decimal comma.

NUMBER_RE module-attribute

NUMBER_RE = re.compile('-?([0-9]+\\.?[0-9]*|\\.[0-9]+)')

The pattern that a number must match once the unit and the decimal comma are handled: -?([0-9]+\.?[0-9]*|\.[0-9]+).