from __future__ import annotations import csv import json import math import re from collections.abc import Mapping, Sequence from typing import Any from jsonschema import Draft202012Validator, ValidationError from . import ar, html_rows, printed_numbers LOCAL_SCOPE_INPUT = ( "The row to classify is provided in the requested field instructions." ) def _column(value: str) -> str: return re.sub("[\\W_]+", "", value.casefold()) def _header_keys(cells: Sequence[str], names: Mapping[str, str]) -> list[str]: keys = [_column(cell) for cell in cells] return [ "quantity" if key == "qty" and "qty" not in names and ("quantity" in names) else key for key in keys ] def join_wrapped_descriptions(instructions: str) -> bool: positive = False for clause in re.split("[.;\\n]", instructions): wrapped = re.search( "\\b(?:wrapped|multiline|multi-line|continuation)\\b", clause, re.IGNORECASE ) joining = re.search("\\b(?:join|combine|merge)\\b", clause, re.IGNORECASE) negative = re.search( "\\b(?:not|no|never|without|separate\\w*|independent\\w*)\\b|\\b\\w+n['’]t\\b", clause, re.IGNORECASE, ) if negative and (wrapped or joining): return False positive |= bool( re.search( "\\b(?:join|combine)\\b[^.;\\n]*\\b(?:wrapped|multiline|multi-line|continuation)\\b[^.;\\n]*\\b(?:descriptions?|lines?|text)\\b", clause, re.IGNORECASE, ) ) return positive def _wrapped_rows( rows: list[dict[str, Any]], properties: dict[str, dict[str, Any]] ) -> list[dict[str, Any]] | None: texts = [name for (name, spec) in properties.items() if spec["type"] == "text"] numbers = [name for (name, spec) in properties.items() if spec["type"] == "number"] if len(texts) != 1 or not numbers: return rows text = texts[0] joined: list[dict[str, Any]] = [] for row in rows: previous = joined[-1] if joined else None if ( previous and previous["values"][text] and row["values"][text] and (previous["spans"][text] is not None) and (row["spans"][text] is not None) and all((previous["values"][key] is None for key in numbers)) and any((row["values"][key] is not None for key in numbers)) and ( row["line"].find(row["values"][text]) >= previous["line"].find(previous["values"][text]) + 2 ) ): value = previous["values"][text] + " " + row["values"][text] if not Draft202012Validator(ar.schema(properties[text])).is_valid(value): return None joined[-1] = { "line": previous["line"] + "\n" + row["line"], "values": {**row["values"], text: value}, "spans": {**row["spans"], text: None}, } else: joined.append(row) return joined def _source_row( cells: Sequence[str], keys: Sequence[str], line: str, offset: int, properties: dict[str, dict[str, Any]], names: Mapping[str, str], ) -> dict[str, Any] | None: value: str | int | float | None (values, spans) = ({}, {}) for key, cell in zip(keys, cells, strict=True): name = names[key] spec = properties[name] if not cell: value = None elif spec["type"] == "number": try: value = printed_numbers.normalize(cell, spec) except (ValueError, TypeError, OverflowError, ValidationError): return None else: value = cell if not Draft202012Validator(ar.schema(spec)).is_valid(value): return None values[name] = value start = line.find(cell) if cell and line.count(cell) == 1 else -1 spans[name] = ( [offset + start, offset + start + len(cell)] if start >= 0 else None ) for name, spec in properties.items(): if name not in values: if not Draft202012Validator(ar.schema(spec)).is_valid(None): return None (values[name], spans[name]) = (None, None) return {"line": line.rstrip("\r\n"), "values": values, "spans": spans} def _html_candidates( source: str, properties: dict[str, dict[str, Any]], names: Mapping[str, str] ) -> list[dict[str, Any]] | None: tables = html_rows.tables(source) if tables is None or len(tables) != 1 or len(tables[0]) < 2: return None (header, *body) = tables[0] keys = [_column(cell) for cell in header["cells"]] if ( len(keys) < 2 or len(set(keys)) != len(keys) or any((key not in names for key in keys)) ): return None rows = [] for row in body: if len(row["cells"]) != len(keys) or not any(row["cells"]): return None parsed = _source_row( row["cells"], keys, row["line"], row["offset"], properties, names ) if parsed is None: return None for key, span in zip(keys, row["spans"], strict=True): parsed["spans"][names[key]] = span rows.append(parsed) return rows def candidates( source: str, properties: dict[str, dict[str, Any]], *, wrapped: bool = False ) -> list[dict[str, Any]] | None: if any( ( spec["type"] not in ("text", "number") or spec.get("knowledge") for spec in properties.values() ) ): return None names = {_column(name): name for name in properties} if len(names) != len(properties): return None if re.search(" 2 and (not header[0]) trailing = delimiter == "|" and len(header) > 2 and (not header[-1]) if trailing: header = header[:-1] if leading: header = header[1:] keys = _header_keys(header, names) if ( len(keys) < 2 or len(set(keys)) != len(keys) or any((key not in names for key in keys)) ): continue rows: list[dict[str, Any]] = [] for row_index in range(index + 1, len(lines)): text = lines[row_index] if delimiter not in text: break try: cells = next(csv.reader([text], delimiter=delimiter, strict=True)) except csv.Error: return None cells = [cell.strip() for cell in cells] if trailing and cells and (not cells[-1]): cells = cells[:-1] if leading and cells and (not cells[0]): cells = cells[1:] if len(cells) != len(keys): return None if not rows and all( (re.fullmatch(":?-{3,}:?", cell) for cell in cells) ): continue if not any(cells): return None row = _source_row( cells, keys, text, offsets[row_index], properties, names ) if row is None: return None rows.append(row) tables.append(_wrapped_rows(rows, properties) if wrapped else rows) return tables[0] if len(tables) == 1 else None def _scope_instruction(instructions: str) -> str | None: requested = re.split( "[.\\n]|\\bExclude\\b", instructions, maxsplit=1, flags=re.IGNORECASE )[0] roles = [ bool(re.search(pattern, requested, re.IGNORECASE)) for pattern in ( "\\bfees?\\b", "\\btax(?:es)?\\b", "\\b(?:charges?|goods|products?|services?)\\b", ) ] if sum(roles) != 1: return None priority = "Evaluate exclusions first for this exact row; an exclusion overrides a general category match. " if roles[0]: return ( priority + "Include only a separately printed fee or surcharge. A billed product or service charge, tax, total or payment is not a fee merely because it has a monetary amount. The row label must explicitly establish that it is a fee or surcharge. " ) if roles[1]: return ( priority + "Include only an explicitly identified tax, such as sales tax, VAT or GST. A product, service charge, fee, total or payment is not a tax merely because it has an amount. " ) if roles[2]: return ( priority + "Include only billed goods or service charges. A separately identified tax, fee, surcharge, payment, subtotal or total is excluded, even though it is a monetary charge. " ) return None def scoped_pairs(source: str, spec: dict[str, Any]) -> list[dict[str, Any]] | None: instructions = spec.get("instructions", "") scope_instruction = _scope_instruction(instructions) properties = spec["items"]["properties"] if ( len(properties) != 2 or scope_instruction is None or (not re.match("\\s*Only\\b[^.\\n]*\\brows\\b", instructions, re.IGNORECASE)) or re.search( "\\b(?:summar\\w*|calculat\\w*|combin\\w*|group\\w*|aggregat\\w*|deduplicat\\w*)\\b|\\buse\\b[^.\\n]*\\bas\\b", instructions, re.IGNORECASE, ) ): return None texts = [ name for (name, child) in properties.items() if child.get("type") == "text" ] numbers = [ name for (name, child) in properties.items() if child.get("type") == "number" ] if ( len(texts) != 1 or len(numbers) != 1 or any((child.get("knowledge") for child in properties.values())) ): return None if not re.search( "\\b(?:exact|verbatim)\\b[^.\\n]*\\b(?:printed|row)\\b[^.\\n]*\\blabel\\b", properties[texts[0]].get("instructions", ""), re.IGNORECASE, ): return None names = {_column(name): name for name in properties} if len(names) != len(properties): return None keys = [_column(texts[0]), _column(numbers[0])] tables = [] for delimiter in ("|", "\t", ";"): (rows, offset) = ([], 0) for line in source.splitlines(keepends=True): if delimiter in line: try: cells = [ cell.strip() for cell in next( csv.reader([line], delimiter=delimiter, strict=True) ) ] except csv.Error: return None if len(cells) != 2 or not all(cells): return None row = _source_row(cells, keys, line, offset, properties, names) if row is None: return None row["eligibility_only"] = True row["scope_instruction"] = scope_instruction rows.append(row) offset += len(line) if len(rows) >= 2: tables.append(rows) return tables[0] if len(tables) == 1 else None def prepare( source: str, fields: dict[str, dict[str, Any]], *, has_media: bool = False, allow_scoped_pairs: bool = False, ) -> dict[str, list[dict[str, Any]]]: if has_media: return {} result = {} for name, spec in fields.items(): item = spec.get("items") if ( spec.get("type") != "list" or not isinstance(item, dict) or item.get("type") != "object" ): continue explicit_rows = re.search( "\\bone\\s+(?:object|entry|record)\\s+(?:per|for\\s+each)\\b[^.\\n]*\\brow\\b", spec.get("instructions", ""), re.IGNORECASE, ) wrapped = join_wrapped_descriptions(spec.get("instructions", "")) rows = ( candidates(source, item["properties"], wrapped=wrapped) if explicit_rows else scoped_pairs(source, spec) if allow_scoped_pairs else None ) if rows and len(rows) <= spec.get("max_items", 32): missing_columns = [ key for (key, child) in item["properties"].items() if child.get("type") == "number" and all((row["values"][key] is None for row in rows)) ] if missing_columns: for row in rows: row["eligibility_only"] = True result[name] = rows return result def membership_instructions(instructions: str) -> str: if re.search( "[\\r\\n`\\\"“”]|(? dict[str, Any]: missing = [name for (name, value) in row["values"].items() if value is None] missing_instruction = ( "Missing cells or entire columns do not exclude an otherwise matching row. These source cells are missing and must remain null: " + ", ".join(missing) + ". " if missing else "" ) scope = membership_instructions(spec.get("instructions", "")) if eligibility: return { "type": "boolean", "nullable": False, "instructions": "Classify exactly this physical source row for inclusion in the requested list. Return true if and only if this row satisfies the requested list instructions. Return false if the row is excluded, unrelated, or does not belong to the requested list, even though it exists. This is an eligibility decision, not a request to copy its cells. " + missing_instruction + row.get("scope_instruction", "") + "Requested list instructions: " + scope + "\nExact physical source row: " + row["line"], } properties = {} for name, child in spec["items"]["properties"].items(): value = row["values"][name] properties[name] = {**child, "nullable": value is None, "enum": [value]} return { **spec["items"], "properties": properties, "nullable": True, "instructions": scope + "\nRead only this exact physical source row: " + json.dumps(row["line"], ensure_ascii=False) + "\nReturn null if this row does not satisfy the requested scope. Otherwise copy its cells together. " + missing_instruction + "Do not substitute a different row. Missing cells are null. This query has no list ordinal to count.", } def local_scope_context( rows: Sequence[dict[str, Any]], queries: Sequence[str], *, offset: int = 0 ) -> tuple[dict[str, str], dict[str, str]]: if not rows or not all((row.get("scope_instruction") for row in rows)): return ({}, {}) pairs = list(zip(queries, rows, strict=True)) inputs = dict.fromkeys(queries, LOCAL_SCOPE_INPUT) names = { query: f"source_scope_{offset + index}" for (index, (query, _)) in enumerate(pairs, 1) } return (inputs, names) def assemble( predictions: dict[str, dict[str, Any]], rows: Sequence[dict[str, Any]], queries: Sequence[str], *, eligibility: bool = False, ) -> dict[str, Any]: checks = [predictions[name] for name in queries] selected = [ (row, answer) for (row, answer) in zip(rows, checks, strict=True) if ( answer.get("value") is True if eligibility else answer.get("value") is not None ) ] valid = all( ( answer.get("valid", False) and answer.get("complete", False) for answer in checks ) ) scored = True if eligibility: valid &= all((type(answer.get("value")) is bool for answer in checks)) scored = all( ( isinstance((score := answer.get("p_excluded")), (int, float)) and (not isinstance(score, bool)) and math.isfinite(score) and (0 <= score <= 1) for answer in checks ) ) valid &= scored p_null = ( math.exp(sum((math.log(answer["p_excluded"]) for answer in checks))) if scored and all((answer["p_excluded"] > 0 for answer in checks)) else 0.0 ) p_null_method = ( "product_source_row_exclusion_probabilities" if scored else "unavailable_source_row_exclusion_probability" ) else: p_null = min((answer.get("p_null", 0.0) for answer in checks)) p_null_method = "minimum_source_row_null_probability" log_probability = sum( (answer.get("log_probability", -math.inf) for answer in checks) ) if not math.isfinite(log_probability): log_probability = None result = { "value": [ dict(row["values"]) if eligibility else answer["value"] for (row, answer) in selected ], "valid": valid, "complete": valid, "confidence": math.exp(min(0, log_probability)) if valid and log_probability is not None else 0.0, "confidence_method": "ar_source_row_eligibility_probability" if eligibility else "ar_source_row_sequence_probability", "p_null": p_null, "p_null_method": p_null_method, "confidences": [answer.get("confidence", 0.0) for (row, answer) in selected], "p_nulls": [ answer.get("p_excluded" if eligibility else "p_null", 0.0) for (row, answer) in selected ], "spans": [None] * len(selected), "property_spans": [row["spans"] for (row, answer) in selected], } if log_probability is not None: result["log_probability"] = log_probability if eligibility and (not scored): result.pop("p_nulls") if not valid: result["failure_reason"] = ( "source_row_eligibility_unscored" if eligibility and (not scored) else "source_row_read_incomplete" ) return result