Coverage for narrative_harm_classifier/classifier/factory.py: 100%
25 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-07-20 13:25 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-07-20 13:25 +0000
1"""
2classifier/factory.py — Shared construction of engine/tracker/runner/validator.
4Every API route and every CLI command previously rebuilt "load taxonomy +
5build Azure client + build ClassificationEngine" independently (six
6near-identical copies across api/routes/*.py and cli.py). Centralizing it
7here means a change to how the engine is constructed (e.g. adding
8dog-whistle lexicon loading) happens once.
9"""
11from narrative_harm_classifier.core.config import Settings
12from narrative_harm_classifier.classifier.taxonomy.loader import load_taxonomy, TaxonomyConfig
13from narrative_harm_classifier.classifier.rules.engine import ClassificationEngine
14from narrative_harm_classifier.classifier.rules.azure_nlp import AzureNLPClient
15from narrative_harm_classifier.classifier.rules.dogwhistles import load_dogwhistles, DogwhistleLexicon
16from narrative_harm_classifier.classifier.tracking.store import get_store, TrackingStore
17from narrative_harm_classifier.classifier.tracking.tracker import EscalationTracker
18from narrative_harm_classifier.classifier.validators.benchmark import BenchmarkRunner
19from narrative_harm_classifier.classifier.validators.performance import PerformanceValidator
22def build_taxonomy(settings: Settings) -> TaxonomyConfig:
23 return load_taxonomy(settings.taxonomy_config_path)
26def build_azure_client(settings: Settings) -> AzureNLPClient:
27 return AzureNLPClient(
28 endpoint=settings.azure_text_analytics_endpoint,
29 key=settings.azure_text_analytics_key,
30 )
33def build_dogwhistle_lexicon(settings: Settings) -> DogwhistleLexicon:
34 return load_dogwhistles(settings.dogwhistles_path)
37def build_engine(settings: Settings) -> ClassificationEngine:
38 return ClassificationEngine(
39 taxonomy=build_taxonomy(settings),
40 azure_client=build_azure_client(settings),
41 patterns_dir=settings.patterns_dir,
42 dogwhistles=build_dogwhistle_lexicon(settings),
43 )
46def build_tracker(settings: Settings) -> EscalationTracker:
47 store: TrackingStore = get_store(settings.effective_tracking_db_url)
48 return EscalationTracker(engine=build_engine(settings), store=store)
51def build_benchmark_runner(settings: Settings) -> BenchmarkRunner:
52 taxonomy = build_taxonomy(settings)
53 return BenchmarkRunner(
54 engine=build_engine(settings),
55 taxonomy_version=taxonomy.version,
56 templates_path=settings.benchmark_templates_path,
57 )
60def build_validator(settings: Settings) -> PerformanceValidator:
61 return PerformanceValidator(engine=build_engine(settings), taxonomy=build_taxonomy(settings))