You ask a model to classify an item and reply with a label and a confidence. Replies come back as clean JSON, as key: value lines, or as free prose. Write the parser that turns any reply into a validated result with a safe fallback.
Implement parse_classification(text, labels, default) returning {"label": str, "confidence": float | None, "source": str}.
labels is the list of allowed labels; default is the label to use when nothing valid is found. A candidate label is valid if, after stripping whitespace, it equals one of labels case-insensitively; the returned label always uses the casing from labels.
Try these strategies in order and return the first that yields a valid label:
"json": scan the text for {; at each one, try to decode a JSON value starting there (json.JSONDecoder().raw_decode). Use the first that decodes to a dict containing a "label" key (or, failing that, a "category" key) whose string value is valid. Its confidence comes from the dict's "confidence" key."kv": the first line matching label, category or class (case-insensitive, optional leading spaces), then : or =, then a value. Strip whitespace and the characters "'*. from both ends of the value. Its confidence comes from the first line of the form confidence: <value> or confidence = <value> (case-insensitive), if any."mention": find which labels occur in the text as whole words, case-insensitively. If exactly one distinct label occurs, use it with confidence None."fallback": return default with confidence None.Confidence parsing. Accept an int or float (not a bool) or a string holding a number with an optional trailing %. A % divides by 100. Otherwise a value in is read as a percentage and divided by 100. The result must lie in , else confidence is None. Round to 4 decimals. Anything unparsable gives None.