|
| 1 | +"""Pure-Python validator for Content Understanding analyzer schema JSON. |
| 2 | +
|
| 3 | +Catches structural mistakes (missing keys, unknown ``baseAnalyzerId`` values, |
| 4 | +malformed ``contentCategories`` routes) **before** any call to the Content |
| 5 | +Understanding service. Failing fast here gives users an actionable error |
| 6 | +message and avoids a wasted service round-trip. |
| 7 | +
|
| 8 | +Design rules (see ``README.md`` in this directory): |
| 9 | +
|
| 10 | +* No ``azure.*`` imports. |
| 11 | +* No network calls. |
| 12 | +* Standard library only. |
| 13 | +
|
| 14 | +The validator accepts either a parsed ``dict`` (preferred) or a path to a |
| 15 | +JSON file (convenience). |
| 16 | +
|
| 17 | +Public surface: |
| 18 | +
|
| 19 | +* :func:`validate_schema` — validate a parsed schema dict. |
| 20 | +* :func:`validate_schema_file` — convenience wrapper that loads a JSON file. |
| 21 | +* :data:`KNOWN_BASE_ANALYZER_IDS` — allow-list of ``baseAnalyzerId`` values. |
| 22 | +""" |
| 23 | + |
| 24 | +from __future__ import annotations |
| 25 | + |
| 26 | +import json |
| 27 | +from pathlib import Path |
| 28 | +from typing import Any, List, Mapping, Optional, Tuple, Union |
| 29 | + |
| 30 | +#: Valid ``baseAnalyzerId`` values for custom analyzers. Only modality-level |
| 31 | +#: prebuilts are accepted by the service for ``baseAnalyzerId``; ``*Search`` |
| 32 | +#: variants and task-specific prebuilts (``prebuilt-invoice``, |
| 33 | +#: ``prebuilt-receipt``) return ``InvalidBaseAnalyzerId`` if used here. See |
| 34 | +#: https://learn.microsoft.com/azure/ai-services/content-understanding/concepts/analyzer-reference#baseanalyzerid |
| 35 | +KNOWN_BASE_ANALYZER_IDS = frozenset( |
| 36 | + { |
| 37 | + "prebuilt-document", |
| 38 | + "prebuilt-audio", |
| 39 | + "prebuilt-video", |
| 40 | + "prebuilt-image", |
| 41 | + } |
| 42 | +) |
| 43 | + |
| 44 | +_ALLOWED_FIELD_TYPES = frozenset( |
| 45 | + {"string", "number", "integer", "boolean", "date", "time", "array", "object"} |
| 46 | +) |
| 47 | + |
| 48 | +_ALLOWED_FIELD_METHODS = frozenset({"extract", "generate", "classify"}) |
| 49 | + |
| 50 | + |
| 51 | +def validate_schema( |
| 52 | + schema: Mapping[str, Any], |
| 53 | +) -> Tuple[bool, List[str]]: |
| 54 | + """Validate a parsed analyzer schema. |
| 55 | +
|
| 56 | + Parameters |
| 57 | + ---------- |
| 58 | + schema: |
| 59 | + The parsed schema (a ``dict`` produced by ``json.load`` or equivalent). |
| 60 | +
|
| 61 | + Returns |
| 62 | + ------- |
| 63 | + tuple |
| 64 | + ``(ok, errors)``. ``ok`` is ``True`` when the schema is structurally |
| 65 | + valid. ``errors`` is the list of human-readable error messages |
| 66 | + (empty when ``ok`` is ``True``). |
| 67 | + """ |
| 68 | + |
| 69 | + errors: List[str] = [] |
| 70 | + |
| 71 | + if not isinstance(schema, Mapping): |
| 72 | + return False, ["schema must be a JSON object at the top level"] |
| 73 | + |
| 74 | + base = schema.get("baseAnalyzerId") |
| 75 | + if base is None: |
| 76 | + errors.append("missing required key: baseAnalyzerId") |
| 77 | + elif not isinstance(base, str): |
| 78 | + errors.append("baseAnalyzerId must be a string") |
| 79 | + elif base not in KNOWN_BASE_ANALYZER_IDS: |
| 80 | + errors.append( |
| 81 | + "unknown baseAnalyzerId: " |
| 82 | + f"{base!r}. Known values: {sorted(KNOWN_BASE_ANALYZER_IDS)}" |
| 83 | + ) |
| 84 | + |
| 85 | + config = schema.get("config") |
| 86 | + if config is not None and not isinstance(config, Mapping): |
| 87 | + errors.append("config, if present, must be an object") |
| 88 | + # Bail out: without a well-typed config we can't tell whether this is |
| 89 | + # a single-type or classify-and-route schema, and falling through |
| 90 | + # would emit a confusing cascade of "missing fieldSchema" errors |
| 91 | + # rooted in the same problem. |
| 92 | + return False, errors |
| 93 | + |
| 94 | + is_classify_route = ( |
| 95 | + isinstance(config, Mapping) and "contentCategories" in config |
| 96 | + ) |
| 97 | + |
| 98 | + if is_classify_route: |
| 99 | + errors.extend(_validate_classify_route(config)) |
| 100 | + if "fieldSchema" in schema: |
| 101 | + errors.append( |
| 102 | + "classify-and-route schemas should not declare fieldSchema at " |
| 103 | + "the top level; field extraction belongs in inner analyzers" |
| 104 | + ) |
| 105 | + else: |
| 106 | + errors.extend(_validate_single_type(schema)) |
| 107 | + |
| 108 | + return (not errors), errors |
| 109 | + |
| 110 | + |
| 111 | +def validate_schema_file(path: Union[str, Path]) -> Tuple[bool, List[str]]: |
| 112 | + """Validate a schema stored in a JSON file. |
| 113 | +
|
| 114 | + Loads the file, then delegates to :func:`validate_schema`. |
| 115 | +
|
| 116 | + Returns the same ``(ok, errors)`` tuple as :func:`validate_schema`. |
| 117 | + """ |
| 118 | + |
| 119 | + p = Path(path) |
| 120 | + try: |
| 121 | + with p.open("r", encoding="utf-8") as fp: |
| 122 | + schema = json.load(fp) |
| 123 | + except FileNotFoundError: |
| 124 | + return False, [f"schema file not found: {p}"] |
| 125 | + except json.JSONDecodeError as exc: |
| 126 | + return False, [f"schema file is not valid JSON ({p}): {exc.msg} at line {exc.lineno}"] |
| 127 | + |
| 128 | + return validate_schema(schema) |
| 129 | + |
| 130 | + |
| 131 | +# --------------------------------------------------------------------------- |
| 132 | +# Internal helpers |
| 133 | +# --------------------------------------------------------------------------- |
| 134 | + |
| 135 | + |
| 136 | +def _validate_single_type(schema: Mapping[str, Any]) -> List[str]: |
| 137 | + """Validate a single-doc-type extraction schema.""" |
| 138 | + |
| 139 | + errors: List[str] = [] |
| 140 | + |
| 141 | + field_schema = schema.get("fieldSchema") |
| 142 | + if field_schema is None: |
| 143 | + errors.append( |
| 144 | + "missing required key: fieldSchema " |
| 145 | + "(single-type schemas must declare fields to extract)" |
| 146 | + ) |
| 147 | + return errors |
| 148 | + |
| 149 | + if not isinstance(field_schema, Mapping): |
| 150 | + errors.append("fieldSchema must be an object") |
| 151 | + return errors |
| 152 | + |
| 153 | + fields = field_schema.get("fields") |
| 154 | + if fields is None: |
| 155 | + errors.append("fieldSchema.fields is required") |
| 156 | + return errors |
| 157 | + |
| 158 | + if not isinstance(fields, Mapping): |
| 159 | + errors.append("fieldSchema.fields must be an object mapping field names to definitions") |
| 160 | + return errors |
| 161 | + |
| 162 | + if not fields: |
| 163 | + errors.append("fieldSchema.fields must declare at least one field") |
| 164 | + |
| 165 | + for name, definition in fields.items(): |
| 166 | + errors.extend(_validate_field_definition(name, definition)) |
| 167 | + |
| 168 | + return errors |
| 169 | + |
| 170 | + |
| 171 | +def _validate_field_definition( |
| 172 | + name: str, definition: Any, *, path: Optional[str] = None |
| 173 | +) -> List[str]: |
| 174 | + errors: List[str] = [] |
| 175 | + prefix = path or f"fieldSchema.fields[{name!r}]" |
| 176 | + |
| 177 | + if not isinstance(definition, Mapping): |
| 178 | + return [f"{prefix} must be an object"] |
| 179 | + |
| 180 | + field_type = definition.get("type") |
| 181 | + if field_type is None: |
| 182 | + errors.append(f"{prefix}.type is required") |
| 183 | + elif field_type not in _ALLOWED_FIELD_TYPES: |
| 184 | + errors.append( |
| 185 | + f"{prefix}.type {field_type!r} is not one of {sorted(_ALLOWED_FIELD_TYPES)}" |
| 186 | + ) |
| 187 | + |
| 188 | + method = definition.get("method") |
| 189 | + if method is not None and method not in _ALLOWED_FIELD_METHODS: |
| 190 | + errors.append( |
| 191 | + f"{prefix}.method {method!r} is not one of {sorted(_ALLOWED_FIELD_METHODS)}" |
| 192 | + ) |
| 193 | + |
| 194 | + description = definition.get("description") |
| 195 | + if description is not None and not isinstance(description, str): |
| 196 | + errors.append(f"{prefix}.description must be a string") |
| 197 | + |
| 198 | + # Recurse into nested object/array shapes so typos in child fields are |
| 199 | + # caught here instead of at the service round-trip. |
| 200 | + if field_type == "object": |
| 201 | + props = definition.get("properties") |
| 202 | + if props is not None: |
| 203 | + if not isinstance(props, Mapping): |
| 204 | + errors.append(f"{prefix}.properties must be an object") |
| 205 | + else: |
| 206 | + for child, child_def in props.items(): |
| 207 | + errors.extend( |
| 208 | + _validate_field_definition( |
| 209 | + child, child_def, path=f"{prefix}.properties[{child!r}]" |
| 210 | + ) |
| 211 | + ) |
| 212 | + elif field_type == "array": |
| 213 | + items = definition.get("items") |
| 214 | + if items is not None: |
| 215 | + if not isinstance(items, Mapping): |
| 216 | + errors.append(f"{prefix}.items must be an object") |
| 217 | + else: |
| 218 | + errors.extend( |
| 219 | + _validate_field_definition( |
| 220 | + "items", items, path=f"{prefix}.items" |
| 221 | + ) |
| 222 | + ) |
| 223 | + |
| 224 | + return errors |
| 225 | + |
| 226 | + |
| 227 | +def _validate_classify_route(config: Mapping[str, Any]) -> List[str]: |
| 228 | + """Validate the classify-and-route portion of a schema.""" |
| 229 | + |
| 230 | + errors: List[str] = [] |
| 231 | + |
| 232 | + enable_segment = config.get("enableSegment") |
| 233 | + if enable_segment is not True: |
| 234 | + errors.append( |
| 235 | + "classify-and-route schemas must set config.enableSegment = true" |
| 236 | + ) |
| 237 | + |
| 238 | + categories = config.get("contentCategories") |
| 239 | + if not isinstance(categories, Mapping): |
| 240 | + errors.append("config.contentCategories must be an object") |
| 241 | + return errors |
| 242 | + |
| 243 | + if not categories: |
| 244 | + errors.append("config.contentCategories must declare at least one category") |
| 245 | + return errors |
| 246 | + |
| 247 | + for name, entry in categories.items(): |
| 248 | + prefix = f"config.contentCategories[{name!r}]" |
| 249 | + if not isinstance(entry, Mapping): |
| 250 | + errors.append(f"{prefix} must be an object") |
| 251 | + continue |
| 252 | + |
| 253 | + description = entry.get("description") |
| 254 | + if not isinstance(description, str) or not description.strip(): |
| 255 | + errors.append(f"{prefix}.description is required and must be a non-empty string") |
| 256 | + |
| 257 | + analyzer_id = entry.get("analyzerId") |
| 258 | + if analyzer_id is not None and not isinstance(analyzer_id, str): |
| 259 | + errors.append(f"{prefix}.analyzerId, if present, must be a string") |
| 260 | + |
| 261 | + return errors |
0 commit comments