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
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
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
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
¶
Source code in unaiverse/uai/coerce.py
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
¶
Source code in unaiverse/uai/coerce.py
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
¶
Source code in unaiverse/uai/coerce.py
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
The pattern of the email format, applied with fullmatch: characters other than whitespace and @, then @, then a host with at least one dot.
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.
The pattern of the characters allowed in a tel value: digits, whitespace, +, -, ( and ). DIGIT_RE then counts the digits.
The pattern of one ASCII digit. A tel value needs at least five matches.
The pattern -?[0-9]+,[0-9]+ of a number written with a decimal comma.
The pattern that a number must match once the unit and the decimal comma are handled: -?([0-9]+\.?[0-9]*|\.[0-9]+).