File size: 6,795 Bytes
b1984d7 | 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 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import joblib
import yaml
try:
from .hybrid_routing_utils import DEFAULT_TAG_TO_DEPARTMENT
except ImportError: # pragma: no cover
from hybrid_routing_utils import DEFAULT_TAG_TO_DEPARTMENT
DEFAULT_DUPLICATE_THRESHOLD = 0.7623
DEFAULT_ROUTING_CONFIG = {
"global_threshold": 0.35,
"confidence_threshold": 0.45,
"default_department": "Human_Review",
"departments": dict(DEFAULT_TAG_TO_DEPARTMENT),
"priority_escalation": {
"critical": "Escalation",
"high": None,
},
}
def _resolve_base_dir(base_dir: str | Path | None = None) -> Path:
if base_dir is None:
return Path(__file__).resolve().parent
return Path(base_dir).resolve()
def resolve_model_dir(base_dir: str | Path | None = None) -> Path:
root = _resolve_base_dir(base_dir)
candidates = [
root / "Models",
root.parent / "Models",
]
for candidate in candidates:
if candidate.exists():
return candidate
return candidates[0]
def resolve_data_root(base_dir: str | Path | None = None) -> Path:
root = _resolve_base_dir(base_dir)
candidates = [
root / "Datasets",
root.parent / "Datasets",
]
for candidate in candidates:
if candidate.exists():
return candidate
return candidates[0]
def resolve_dataset_file(
base_dir: str | Path | None,
filename: str,
*,
prefer_processed: bool = True,
) -> Path:
data_root = resolve_data_root(base_dir)
ordered = []
if prefer_processed:
ordered.extend(
[
data_root / "Processed" / filename,
data_root / filename,
]
)
else:
ordered.extend(
[
data_root / filename,
data_root / "Processed" / filename,
]
)
for candidate in ordered:
if candidate.exists():
return candidate
raise FileNotFoundError(
f"Dataset '{filename}' not found in deployment bundle. Checked: {ordered}"
)
def load_model_config(base_dir: str | Path | None = None) -> dict[str, Any]:
model_dir = resolve_model_dir(base_dir)
config_path = model_dir / "model_config.pkl"
if not config_path.exists():
return {}
loaded = joblib.load(config_path)
return loaded if isinstance(loaded, dict) else {}
def resolve_model_reference(
model_ref: str | Path | None,
*,
base_dir: str | Path | None = None,
model_dir: str | Path | None = None,
default: str | None = None,
) -> str:
if model_ref in (None, ""):
if default is None:
raise FileNotFoundError("No model reference was provided.")
return str(default)
raw_value = str(model_ref)
# ✅ FIX: Directly return Hugging Face repo IDs
# (format: username/model_name)
if isinstance(raw_value, str) and "/" in raw_value and not raw_value.startswith(("Models", ".", "/")):
return raw_value
raw_path = Path(raw_value)
base_path = _resolve_base_dir(base_dir)
model_path_root = Path(model_dir).resolve() if model_dir is not None else resolve_model_dir(base_path)
candidates: list[Path] = []
if raw_path.is_absolute():
candidates.append(raw_path)
if "Models" in raw_path.parts:
model_idx = raw_path.parts.index("Models")
suffix_parts = raw_path.parts[model_idx + 1:]
if suffix_parts:
candidates.append(model_path_root.joinpath(*suffix_parts))
candidates.append(model_path_root / raw_path.name)
candidates.append(base_path / raw_path.name)
else:
candidates.extend(
[
raw_path,
base_path / raw_path,
model_path_root / raw_path,
model_path_root / raw_path.name,
base_path / raw_path.name,
]
)
seen = set()
for candidate in candidates:
candidate = candidate.resolve() if candidate.exists() else candidate
normalized = str(candidate)
if normalized in seen:
continue
seen.add(normalized)
if candidate.exists():
return str(candidate)
if default is not None:
return str(default)
return raw_value
def _merge_routing_config(loaded: dict[str, Any] | None) -> dict[str, Any]:
merged = {
"global_threshold": DEFAULT_ROUTING_CONFIG["global_threshold"],
"confidence_threshold": DEFAULT_ROUTING_CONFIG["confidence_threshold"],
"default_department": DEFAULT_ROUTING_CONFIG["default_department"],
"departments": dict(DEFAULT_ROUTING_CONFIG["departments"]),
"priority_escalation": dict(DEFAULT_ROUTING_CONFIG["priority_escalation"]),
}
if not isinstance(loaded, dict):
return merged
for key in ("global_threshold", "confidence_threshold", "default_department"):
if key in loaded:
merged[key] = loaded[key]
merged["departments"].update(loaded.get("departments") or {})
merged["priority_escalation"].update(loaded.get("priority_escalation") or {})
return merged
def load_routing_config(
base_dir: str | Path | None = None,
) -> tuple[dict[str, Any], Path | None]:
root = _resolve_base_dir(base_dir)
model_dir = resolve_model_dir(root)
candidates = [
root / "config" / "routing_config.yaml",
model_dir / "routing_config.yaml",
root.parent / "config" / "routing_config.yaml",
]
for candidate in candidates:
if not candidate.exists():
continue
with candidate.open("r", encoding="utf-8") as handle:
return _merge_routing_config(yaml.safe_load(handle)), candidate
return _merge_routing_config(None), None
def load_duplicate_threshold(base_dir: str | Path | None = None) -> float:
model_dir = resolve_model_dir(base_dir)
threshold_path = model_dir / "duplicate_thresholds.pkl"
if threshold_path.exists():
payload = joblib.load(threshold_path)
if isinstance(payload, dict):
try:
return float(payload.get("duplicate_threshold", DEFAULT_DUPLICATE_THRESHOLD))
except (TypeError, ValueError):
pass
return float(DEFAULT_DUPLICATE_THRESHOLD)
def load_metric_artifact(
base_dir: str | Path | None,
filename: str,
) -> dict[str, Any]:
model_dir = resolve_model_dir(base_dir)
artifact_path = model_dir / filename
if not artifact_path.exists():
raise FileNotFoundError(f"Metric artifact not found: {artifact_path}")
with artifact_path.open("r", encoding="utf-8") as handle:
return json.load(handle)
|