Spaces:
Sleeping
Sleeping
File size: 4,242 Bytes
fdfe81a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | """Load and validate the brand rules rubric from brand_rules.json.
Schema validation is performed at load time using jsonschema. Pydantic v2 models
provide typed access to the rubric contents.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import jsonschema
from pydantic import BaseModel, ConfigDict
_RUBRIC_DIR = Path(__file__).parent
_RULES_FILE = _RUBRIC_DIR / "brand_rules.json"
_SCHEMA_FILE = _RUBRIC_DIR / "schema.json"
# ---------------------------------------------------------------------------
# Pydantic models (extra='forbid' everywhere)
# ---------------------------------------------------------------------------
class RuleExamples(BaseModel):
model_config = ConfigDict(extra="forbid")
do: str | None = None
dont: str | None = None
class RuleMetadata(BaseModel):
model_config = ConfigDict(extra="forbid")
allowed_hex: list[str] | None = None
canonical_text: str | None = None
class BrandRule(BaseModel):
model_config = ConfigDict(extra="forbid")
id: str
category: str
rule_text: str
severity_default: str
detection_type: str
examples: RuleExamples | None = None
source_ref: str
metadata: RuleMetadata | None = None
class MustFlagMarker(BaseModel):
model_config = ConfigDict(extra="forbid")
category: str
severity_default: str
title_template: str
rule_id: str
class RubricTopLevelMetadata(BaseModel):
model_config = ConfigDict(extra="forbid")
must_flag_markers: dict[str, MustFlagMarker]
class Rubric(BaseModel):
model_config = ConfigDict(extra="forbid")
version: str
metadata: RubricTopLevelMetadata
rules: list[BrandRule]
# ---------------------------------------------------------------------------
# Public loader
# ---------------------------------------------------------------------------
def load_rubric(
rules_path: Path | None = None,
schema_path: Path | None = None,
) -> Rubric:
"""Load, JSON-Schema-validate, and Pydantic-parse brand_rules.json.
Parameters
----------
rules_path:
Path to the rubric JSON file. Defaults to the bundled brand_rules.json.
schema_path:
Path to the JSON Schema file. Defaults to the bundled schema.json.
Returns
-------
Rubric
Fully validated and typed rubric object.
Raises
------
FileNotFoundError
If either the rubric or schema file is missing.
jsonschema.ValidationError
If the rubric JSON does not conform to the schema.
pydantic.ValidationError
If the parsed data does not conform to the Pydantic models (should not
happen if schema validation passes, but serves as a belt-and-suspenders
check).
ValueError
If a must_flag_markers entry references a rule_id that does not exist.
"""
rules_path = rules_path or _RULES_FILE
schema_path = schema_path or _SCHEMA_FILE
if not rules_path.exists():
raise FileNotFoundError(f"Rubric file not found: {rules_path}")
if not schema_path.exists():
raise FileNotFoundError(f"Schema file not found: {schema_path}")
raw_data: Any = json.loads(rules_path.read_text(encoding="utf-8"))
schema: Any = json.loads(schema_path.read_text(encoding="utf-8"))
# JSON Schema validation — raises jsonschema.ValidationError on failure
try:
jsonschema.validate(instance=raw_data, schema=schema)
except jsonschema.ValidationError as exc:
raise jsonschema.ValidationError(
f"Rubric schema validation failed: {exc.message}"
) from exc
# Pydantic parse (belt-and-suspenders)
rubric = Rubric.model_validate(raw_data)
# Cross-reference: every must_flag_markers rule_id must resolve to a real rule
existing_ids = {rule.id for rule in rubric.rules}
for marker_key, marker in rubric.metadata.must_flag_markers.items():
if marker.rule_id not in existing_ids:
raise ValueError(
f"must_flag_markers[{marker_key!r}].rule_id={marker.rule_id!r} "
f"does not match any rule id in the rubric. "
f"Existing ids: {sorted(existing_ids)}"
)
return rubric
|