Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix: represent unavailable entity confidence as None instead of 1.0 (#1285)
Wei Tao1461969817e7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b6a58baa..430dfce8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -47,6 +47,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **MCP `get_provenance` ignored the advertised `entity_id` argument, so every schema-compliant call failed** (closes #1248) by @csy20 — `GET_PROVENANCE` requires `entity_id` and `tools/list` advertises that key, but `handle_get_provenance` only read `node_id` and always returned `{"error": "node_id is required", "provenance": []}`. The handler now reads `entity_id` first and still accepts `node_id` as a compatibility alias. New `tests/test_mcp_package_get_provenance.py`+### Changed++- **`Entity.confidence` is now `Optional[float]` defaulting to `None`, so "no measurement" is no longer encoded as a perfect score** (closes #1282) by @taoche+ - **Breaking at the type level for a public dataclass.** `semantica.semantic_extract.types.Entity.confidence` was `float = 1.0`; it is now `Optional[float] = None`. The spaCy NER adapter fabricated `1.0` whenever a span exposed no per-entity probability — the normal case for standard spaCy models — so every `ml`-extracted entity claimed perfect confidence, indistinguishable from a backend that genuinely reported 1.0+ - **`extract()` callers are unaffected.** The pipeline scores unknown confidences (heuristic, labeled) *before* filtering, so every entity `extract()` emits still carries a numeric confidence, now with provenance under `metadata[CONFIDENCE_SOURCE_KEY]` (`model` / `heuristic` / `type_similarity` / `unavailable`, constants owned by `types.py`). Measured scores are never overwritten+ - **Callers that construct `Entity` themselves and bypass `extract()` can now see `None` downstream.** `kg/graph_builder.py` copies the field into its graph entity dicts, so `GraphBuilder(...).build([Entity(...)], extract=False)` yields `confidence: None` where it previously yielded `1.0`, and any numeric comparison or sort on that value raises `TypeError`. Nothing in `semantica/` compares it numerically, so this is not a break in-tree+ - `EntityConfidenceScorer` recalculates only when `confidence is None`, instead of treating `== 1.0` as a "recalculate" sentinel — the old test destroyed genuine backend scores of exactly 1.0 rather than merely mislabeling missing ones+ - `calculate_weighted_confidence()` falls back to similarity-only scoring when no measured confidence exists, and stays `None` when the caller explicitly disables similarity weighting. Ensemble voting also averages only measured scores, but that now comes from the clustering rewrite already on `main` (`_numeric_confidence`), not from this PR+ - The standalone filter APIs route unknown values through one policy helper, `meets_confidence_threshold()`: unknown passes, since absence of evidence is not low confidence. This matches the previous behavior, so no entity is newly dropped+ - `ExtractionValidator` reports unscored entities under a separate `unscored` metric and treats unknown as neutral rather than zero+ - `Relation`, `Triplet` and the separate `utils.types.Entity` are untouched; the LLM, HuggingFace, pattern and regex paths always set explicit float scores and are unchanged+ - Docs: `semantica/semantic_extract/semantic_extract_usage.md` and `cookbook/introduction/05_Entity_Extraction.ipynb` (renders unavailable confidence as `N/A`)+## [0.7.0] - 2026-09-07### Changeddiff --git a/cookbook/introduction/05_Entity_Extraction.ipynb b/cookbook/introduction/05_Entity_Extraction.ipynbindex 78cabe22..ebcf3810 100644--- a/cookbook/introduction/05_Entity_Extraction.ipynb+++ b/cookbook/introduction/05_Entity_Extraction.ipynb@@ -106,9 +106,11 @@" # Handle both dict and object formats\n"," entity_text = entity.get('text', entity.get('entity', '')) if isinstance(entity, dict) else entity.text\n"," entity_type = entity.get('type', entity.get('label', 'Unknown')) if isinstance(entity, dict) else entity.label\n",- " confidence = entity.get('confidence', 1.0) if isinstance(entity, dict) else getattr(entity, 'confidence', 1.0)\n",+ " # Confidence is None when the extraction backend provides no per-entity score\n",+ " confidence = entity.get('confidence') if isinstance(entity, dict) else getattr(entity, 'confidence', None)\n",+ " confidence_str = f\"{confidence:.2f}\" if confidence is not None else \"N/A\"\n"," \n",- " print(f\"{i:2d}. {entity_text:30s} | Type: {entity_type:12s} | Confidence: {confidence:.2f}\")\n",+ " print(f\"{i:2d}. {entity_text:30s} | Type: {entity_type:12s} | Confidence: {confidence_str}\")\n","\n","print(\"-\" * 80)"]@@ -127,9 +129,11 @@"| `label/type` | Entity category | \"ORG\" (Organization) |\n","| `start_char` | Starting position | 0 |\n","| `end_char` | Ending position | 10 |\n",- "| `confidence` | Extraction confidence (0-1) | 0.95 |\n",+ "| `confidence` | Extraction confidence (0-1), or `None` when no score is available | 0.95 |\n","| `metadata` | Additional information | {\"method\": \"ml\"} |\n","\n",+ "> **Note on confidence**: standard spaCy models do not expose per-entity probabilities. At the adapter level such entities carry `confidence=None` with `metadata[\"confidence_source\"] = \"unavailable\"` — `None` means *unknown*, not low quality. The `extract()` pipeline then fills unknown values with heuristic scores (labeled `confidence_source=\"heuristic\"`) before filtering, so entities returned by `extract()` always carry a numeric confidence with its provenance. Scores measured by a backend (`confidence_source=\"model\"`) are never overwritten. Rendering code should still handle `None` defensively (shown as `N/A` here) for entities that bypass the pipeline.\n",+ "\n","### Common Entity Types\n","\n","- **PERSON**: People, including fictional characters\n",@@ -297,8 +301,9 @@" for entity in entities:\n"," entity_text = entity.get('text', entity.get('entity', '')) if isinstance(entity, dict) else entity.text\n"," entity_type = entity.get('type', entity.get('label', 'Unknown')) if isinstance(entity, dict) else entity.label\n",- " confidence = entity.get('confidence', 1.0) if isinstance(entity, dict) else getattr(entity, 'confidence', 1.0)\n",- " print(f\" • {entity_text:25s} | {entity_type:10s} | Confidence: {confidence:.2f}\")\n",+ " confidence = entity.get('confidence') if isinstance(entity, dict) else getattr(entity, 'confidence', None)\n",+ " confidence_str = f\"{confidence:.2f}\" if confidence is not None else \"N/A\"\n",+ " print(f\" • {entity_text:25s} | {entity_type:10s} | Confidence: {confidence_str}\")\n","\n","print(f\"\\n Total entities extracted: {len(all_entities)}\")\n","print(\"=\" * 80)"@@ -382,7 +387,8 @@"# Initialize confidence scorer\n","scorer = EntityConfidenceScorer()\n","\n",- "# Score the entities\n",+ "# Score the entities: entities without a backend-provided confidence\n",+ "# (confidence=None) receive a heuristic score; measured scores are preserved\n","scored_entities = scorer.score_entities(all_entities)\n","\n","print(\" Entity Confidence Scoring:\\n\")\n",@@ -392,11 +398,14 @@"high_confidence = []\n","medium_confidence = []\n","low_confidence = []\n",+ "unscored = []\n","\n","for entity in scored_entities:\n",- " confidence = entity.get('confidence', 1.0) if isinstance(entity, dict) else getattr(entity, 'confidence', 1.0)\n",+ " confidence = entity.get('confidence') if isinstance(entity, dict) else getattr(entity, 'confidence', None)\n"," \n",- " if confidence >= 0.8:\n",+ " if confidence is None:\n",+ " unscored.append(entity)\n",+ " elif confidence >= 0.8:\n"," high_confidence.append(entity)\n"," elif confidence >= 0.5:\n"," medium_confidence.append(entity)\n",@@ -406,6 +415,8 @@"print(f\" High Confidence (≥0.8): {len(high_confidence)} entities\")\n","print(f\"️ Medium Confidence (0.5-0.8): {len(medium_confidence)} entities\")\n","print(f\" Low Confidence (<0.5): {len(low_confidence)} entities\")\n",+ "if unscored:\n",+ " print(f\" Unscored (N/A): {len(unscored)} entities\")\n","\n","print(\"\\n Confidence Distribution:\")\n","print(\"-\" * 40)\n",@@ -416,8 +427,9 @@" for entity in high_confidence[:3]:\n"," entity_text = entity.get('text', entity.get('entity', '')) if isinstance(entity, dict) else entity.text\n"," entity_type = entity.get('type', entity.get('label', 'Unknown')) if isinstance(entity, dict) else entity.label\n",- " confidence = entity.get('confidence', 1.0) if isinstance(entity, dict) else getattr(entity, 'confidence', 1.0)\n",- " print(f\" • {entity_text} ({entity_type}) - {confidence:.2f}\")\n",+ " confidence = entity.get('confidence') if isinstance(entity, dict) else getattr(entity, 'confidence', None)\n",+ " confidence_str = f\"{confidence:.2f}\" if confidence is not None else \"N/A\"\n",+ " print(f\" • {entity_text} ({entity_type}) - {confidence_str}\")\n","\n","print(\"\\n\" + \"=\" * 80)"]diff --git a/integrations/agno/kg_toolkit.py b/integrations/agno/kg_toolkit.pyindex c36ea63f..db4ba01e 100644--- a/integrations/agno/kg_toolkit.py+++ b/integrations/agno/kg_toolkit.py@@ -149,11 +149,14 @@ class AgnoKGToolkit(_ToolkitBase): # type: ignore[misc]"""try:raw = self._ner.extract_entities(text) or []+ def _conf(val: Any) -> float:+ return round(float(val), 4) if val is not None else 1.0+entities = [{"name": getattr(e, "name", str(e)),"type": getattr(e, "type", ""),- "confidence": round(float(getattr(e, "confidence", 1.0)), 4),+ "confidence": _conf(getattr(e, "confidence", None)),}for e in raw]diff --git a/semantica/export/report_generator.py b/semantica/export/report_generator.pyindex be9f92be..0a714f81 100644--- a/semantica/export/report_generator.py+++ b/semantica/export/report_generator.py@@ -555,8 +555,10 @@ class ReportGenerator:def _generate_metrics_summary(self, metrics: Dict[str, Any]) -> Dict[str, Any]:"""Generate metrics summary."""+ avg_conf = metrics.get("average_confidence")+ avg_conf_str = f"{avg_conf:.2f}" if avg_conf is not None else "N/A"return {"Total Items": metrics.get("total_items", 0),"Success Rate": f"{metrics.get('success_rate', 0.0):.2%}",- "Average Confidence": f"{metrics.get('average_confidence', 0.0):.2f}",+ "Average Confidence": avg_conf_str,}diff --git a/semantica/semantic_extract/extraction_validator.py b/semantica/semantic_extract/extraction_validator.pyindex be315cd4..c3f6a979 100644--- a/semantica/semantic_extract/extraction_validator.py+++ b/semantica/semantic_extract/extraction_validator.py@@ -55,6 +55,7 @@ from ..utils.exceptions import ProcessingErrorfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_trackerfrom .ner_extractor import Entity+from .types import meets_confidence_thresholdfrom .relation_extractor import Relation@@ -132,7 +133,8 @@ class ExtractionValidator:self.progress_tracker.update_tracking(tracking_id, message="Checking confidence scores...")- low_confidence = [e for e in entities if e.confidence < min_confidence]+ scored = [e for e in entities if e.confidence is not None]+ low_confidence = [e for e in scored if e.confidence < min_confidence]if low_confidence:warnings.append(f"{len(low_confidence)} entities below confidence threshold"@@ -144,20 +146,22 @@ class ExtractionValidator:if empty_entities:errors.append(f"{len(empty_entities)} empty entities found")- # Calculate metrics+ # Calculate metrics (entities with unknown confidence are counted+ # separately and excluded from the score buckets and average)metrics = {"total_entities": len(entities),- "high_confidence": len([e for e in entities if e.confidence >= 0.8]),+ "high_confidence": len([e for e in scored if e.confidence >= 0.8]),"medium_confidence": len(- [e for e in entities if min_confidence <= e.confidence < 0.8]+ [e for e in scored if min_confidence <= e.confidence < 0.8]),"low_confidence": len(low_confidence),+ "unscored": len(entities) - len(scored),"unique_entities": len(set(e.text for e in entities)),"entity_types": len(set(e.label for e in entities)),- "average_confidence": sum(e.confidence for e in entities)- / len(entities)- if entities- else 0.0,+ "average_confidence": sum(e.confidence for e in scored)+ / len(scored)+ if scored+ else None,}# Calculate score@@ -302,9 +306,11 @@ class ExtractionValidator:dup_ratio = metrics.get("duplicates", 0) / metrics.get("total_entities", 1)score *= 1.0 - dup_ratio * 0.3- # Average confidence factor- avg_confidence = metrics.get("average_confidence", 0.0)- score *= 0.5 + avg_confidence * 0.5+ # Average confidence factor (skipped when no entity carries a+ # measured confidence: unknown is neutral, not zero)+ avg_confidence = metrics.get("average_confidence")+ if avg_confidence is not None:+ score *= 0.5 + avg_confidence * 0.5return max(0.0, min(1.0, score))@@ -346,12 +352,16 @@ class ExtractionValidator:min_confidence: Minimum confidence (uses default if None)Returns:- list: Filtered entities+ list: Filtered entities (entities with unknown confidence pass)"""threshold = (min_confidence if min_confidence is not None else self.min_confidence)- return [e for e in entities if e.confidence >= threshold]+ return [+ e+ for e in entities+ if meets_confidence_threshold(e.confidence, threshold)+ ]def filter_relations_by_confidence(self, relations: List[Relation], min_confidence: Optional[float] = Nonediff --git a/semantica/semantic_extract/methods.py b/semantica/semantic_extract/methods.pyindex fa5e5c85..e2697505 100644--- a/semantica/semantic_extract/methods.py+++ b/semantica/semantic_extract/methods.py@@ -122,7 +122,14 @@ from .providers import HuggingFaceModelLoader, create_providerfrom .registry import method_registryfrom .cache import ExtractionCache, InMemoryBackendfrom .config import config-from .types import Entity, Relation, Triplet+from .types import (+ CONFIDENCE_SOURCE_KEY,+ CONFIDENCE_SOURCE_MODEL,+ CONFIDENCE_SOURCE_UNAVAILABLE,+ Entity,+ Relation,+ Triplet,+)try:from .schemas import (@@ -811,27 +818,31 @@ def filter_entities_for_text(def calculate_weighted_confidence(- item_type: str,- original_confidence: float,+ item_type: str,+ original_confidence: Optional[float],valid_types: Optional[List[str]] = None,item_text: Optional[str] = None,weight_method: float = 0.5,weight_similarity: float = 0.5-) -> float:+) -> Optional[float]:"""Calculate weighted confidence score using both Label and Content similarity.Final Score = (weight_method * original_confidence) + (weight_similarity * max(label_sim, content_sim))-+Args:item_type: The extracted type/label/predicate (e.g., "PERSON", "founded_by")- original_confidence: The confidence score from the extraction method (0.0-1.0)+ original_confidence: The confidence score from the extraction method+ (0.0-1.0), or None if the method provided no scorevalid_types: List of valid/preferred types provided by useritem_text: The actual text content extracted (e.g., "Steve Jobs", "acquired")weight_method: Weight for the original method confidence (default 0.5)weight_similarity: Weight for the similarity score (default 0.5)-+Returns:- float: Weighted confidence score (0.0-1.0)+ float or None: Weighted confidence score (0.0-1.0). When+ original_confidence is None, returns the similarity score alone —+ or None (still unknown) if valid_types is empty or the similarity+ weight is disabled (<= 0)."""if not valid_types:return original_confidence@@ -852,11 +863,18 @@ def calculate_weighted_confidence(if total_weight <= 0:return original_confidence+ if original_confidence is None:+ if weight_similarity <= 0:+ # Similarity disabled and no measured confidence: still unknown+ return None+ # No measured confidence to blend; rely on similarity alone+ return max(0.0, min(1.0, best_similarity))+w_m = weight_method / total_weightw_s = weight_similarity / total_weight-+final_score = (w_m * original_confidence) + (w_s * best_similarity)-+return max(0.0, min(1.0, final_score))@@ -980,7 +998,9 @@ def extract_entities_ml(entities = []for ent in doc.ents:- confidence = 1.0+ # Standard spaCy spans expose no per-entity probability. Report the+ # absence explicitly (None) instead of fabricating certainty (1.0).+ confidence = Noneif hasattr(ent, "confidence"):confidence = ent.confidenceelif hasattr(ent, "score"):@@ -997,6 +1017,11 @@ def extract_entities_ml("extraction_method": "ml","model": model,"lemma": ent.lemma_ if hasattr(ent, "lemma_") else ent.text,+ CONFIDENCE_SOURCE_KEY: (+ CONFIDENCE_SOURCE_MODEL+ if confidence is not None+ else CONFIDENCE_SOURCE_UNAVAILABLE+ ),},))diff --git a/semantica/semantic_extract/named_entity_recognizer.py b/semantica/semantic_extract/named_entity_recognizer.pyindex ebe25ed0..28bc20cf 100644--- a/semantica/semantic_extract/named_entity_recognizer.py+++ b/semantica/semantic_extract/named_entity_recognizer.py@@ -52,6 +52,7 @@ from ..utils.exceptions import ProcessingErrorfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_trackerfrom .ner_extractor import Entity, NERExtractor+from .types import CONFIDENCE_SOURCE_HEURISTIC, CONFIDENCE_SOURCE_KEYclass NamedEntityRecognizer:@@ -249,8 +250,12 @@ class EntityClassifier:matching = [c for c in candidates if c.label == entity_type]if matching:- # Return first match with highest confidence- return max(matching, key=lambda e: e.confidence)+ # Return first match with highest confidence; unknown (None)+ # must not outrank measured scores+ return max(+ matching,+ key=lambda e: e.confidence if e.confidence is not None else -1.0,+ )return candidates[0] if candidates else None@@ -295,10 +300,20 @@ class EntityConfidenceScorer:Returns:list: Entities with updated confidence scores++ Note:+ Only entities without a confidence measurement (``None``) are+ scored; a score supplied by an extraction backend — including a+ genuine 1.0 — is preserved."""for entity in entities:- if entity.confidence == 1.0: # Only recalculate if needed+ if entity.confidence is None:entity.confidence = self._calculate_confidence(entity, **options)+ if entity.metadata is None:+ entity.metadata = {}+ entity.metadata[CONFIDENCE_SOURCE_KEY] = (+ CONFIDENCE_SOURCE_HEURISTIC+ )return entitiesdiff --git a/semantica/semantic_extract/ner_extractor.py b/semantica/semantic_extract/ner_extractor.pyindex 242a0f9f..cc3c50e9 100644--- a/semantica/semantic_extract/ner_extractor.py+++ b/semantica/semantic_extract/ner_extractor.py@@ -81,7 +81,12 @@ from ..utils.exceptions import ProcessingErrorfrom ..utils.helpers import safe_importfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_tracker-from .types import Entity+from .types import (+ CONFIDENCE_SOURCE_KEY,+ CONFIDENCE_SOURCE_TYPE_SIMILARITY,+ Entity,+ meets_confidence_threshold,+)spacy, SPACY_AVAILABLE = safe_import("spacy")@@ -720,17 +725,33 @@ class NERExtractor:try:from .methods import calculate_weighted_confidencefor e in entities:+ had_score = e.confidence is not Nonee.confidence = calculate_weighted_confidence(item_type=e.label,original_confidence=e.confidence,valid_types=entity_types,item_text=e.text)+ if not had_score and e.confidence is not None:+ if e.metadata is None:+ e.metadata = {}+ e.metadata[CONFIDENCE_SOURCE_KEY] = (+ CONFIDENCE_SOURCE_TYPE_SIMILARITY+ )except ImportError:pass+ # Score any remaining unknown confidences so filtering,+ # voting and consumers downstream always see measured or+ # heuristic values, never None+ entities = self._fill_unknown_confidence(entities)+# Filter by confidence- filtered = [e for e in entities if e.confidence >= min_confidence]+ filtered = [+ e+ for e in entities+ if meets_confidence_threshold(e.confidence, min_confidence)+ ]if merge_strategy == "fallback":if filtered:@@ -1386,6 +1407,22 @@ class NERExtractor:return classified+ def _fill_unknown_confidence(self, entities: List[Entity]) -> List[Entity]:+ """Assign heuristic scores to entities without a measured confidence.++ Runs inside the extract() pipeline before filtering, so the pipeline+ guarantees every emitted entity carries a numeric confidence —+ callers never have to reason about None. Filled scores are labeled+ confidence_source="heuristic"; measured scores are never touched.+ """+ if all(e.confidence is not None for e in entities):+ return entities+ # Deferred import: named_entity_recognizer imports this module at+ # module level, so a top-level import here would be circular+ from .named_entity_recognizer import EntityConfidenceScorer++ return EntityConfidenceScorer().score_entities(entities)+def filter_by_confidence(self, entities: List[Entity], min_confidence: float) -> List[Entity]:@@ -1397,6 +1434,10 @@ class NERExtractor:min_confidence: Minimum confidence thresholdReturns:- list: Filtered entities+ list: Filtered entities (entities with unknown confidence pass)"""- return [e for e in entities if e.confidence >= min_confidence]+ return [+ e+ for e in entities+ if meets_confidence_threshold(e.confidence, min_confidence)+ ]diff --git a/semantica/semantic_extract/semantic_extract_usage.md b/semantica/semantic_extract/semantic_extract_usage.mdindex 97126f9a..8a128689 100644--- a/semantica/semantic_extract/semantic_extract_usage.md+++ b/semantica/semantic_extract/semantic_extract_usage.md@@ -88,7 +88,11 @@ ner = NamedEntityRecognizer()entities = ner.extract_entities("Apple Inc. was founded by Steve Jobs in 1976.")for entity in entities:- print(f"{entity.text} ({entity.type}) - Confidence: {entity.confidence:.2f}")+ # metadata["confidence_source"] records where the score came from+ # (model/heuristic/...); confidence is None only for entities that+ # bypass the extraction pipeline without a backend score+ confidence = f"{entity.confidence:.2f}" if entity.confidence is not None else "N/A"+ print(f"{entity.text} ({entity.type}) - Confidence: {confidence}")```### Different Entity Extraction Methods@@ -186,19 +190,23 @@ for entity in entities:```pythonfrom semantica.semantic_extract import EntityClassifier, EntityConfidenceScorer+from semantica.semantic_extract.types import Entityclassifier = EntityClassifier()scorer = EntityConfidenceScorer()-entity = {"text": "Apple Inc.", "type": "ORG"}+entity = Entity(text="Apple Inc.", label="ORG", start_char=0, end_char=10)# Classify entity-classification = classifier.classify(entity)+classification = classifier.classify_entity_type(entity)print(f"Classification: {classification}")-# Score confidence-confidence = scorer.score(entity)-print(f"Confidence: {confidence:.2f}")+# Score confidence — score_entities() accepts a list and returns the same list+# with confidence filled in for any entity that had confidence=None+(scored,) = scorer.score_entities([entity])+confidence = scored.confidence+conf_str = f"{confidence:.2f}" if confidence is not None else "N/A"+print(f"Confidence: {conf_str}")```## Relation Extractiondiff --git a/semantica/semantic_extract/types.py b/semantica/semantic_extract/types.pyindex 58e27a3d..fd7f6940 100644--- a/semantica/semantic_extract/types.py+++ b/semantica/semantic_extract/types.py@@ -6,21 +6,50 @@ method dispatchers and extractors can share result models without import cycles."""from dataclasses import dataclass, field-from typing import Any, Dict+from typing import Any, Dict, Optional++# Provenance vocabulary for Entity.confidence, recorded under+# metadata[CONFIDENCE_SOURCE_KEY]. Producers must use these constants so the+# vocabulary stays greppable and typo-proof.+CONFIDENCE_SOURCE_KEY = "confidence_source"+CONFIDENCE_SOURCE_MODEL = "model" # score produced by the extraction backend+CONFIDENCE_SOURCE_HEURISTIC = "heuristic" # filled by EntityConfidenceScorer+CONFIDENCE_SOURCE_TYPE_SIMILARITY = "type_similarity" # from entity_types weighting+CONFIDENCE_SOURCE_UNAVAILABLE = "unavailable" # backend exposes no score@dataclassclass Entity:- """Entity representation."""+ """Entity representation.++ ``confidence`` is ``None`` when no confidence measurement is available+ (e.g. the extraction backend does not expose per-entity probabilities).+ ``None`` is distinct from any numeric score: it means "unknown", not+ "certain". Producers record where a score came from under+ ``metadata[CONFIDENCE_SOURCE_KEY]``, using the ``CONFIDENCE_SOURCE_*``+ constants above.+ """text: strlabel: strstart_char: intend_char: int- confidence: float = 1.0+ confidence: Optional[float] = Nonemetadata: Dict[str, Any] = field(default_factory=dict)+def meets_confidence_threshold(+ confidence: Optional[float], threshold: float+) -> bool:+ """Return True if a confidence value passes a minimum threshold.++ Unknown confidence (``None``) passes: absence of a measurement is not+ evidence of low confidence, and entities must not be silently dropped+ just because their backend exposes no probabilities.+ """+ return confidence is None or confidence >= threshold++@dataclassclass Relation:"""Relation representation."""diff --git a/tests/semantic_extract/test_entity_confidence.py b/tests/semantic_extract/test_entity_confidence.pynew file mode 100644index 00000000..b118cf59--- /dev/null+++ b/tests/semantic_extract/test_entity_confidence.py@@ -0,0 +1,276 @@+"""Regression tests for optional entity confidence (issue #1282).++Unavailable per-entity confidence must be represented explicitly (None)+instead of being fabricated as 1.0, and a genuine backend-provided score+of 1.0 must be distinguishable from "no score available".+"""++import unittest+from types import SimpleNamespace+from unittest.mock import patch++from semantica.semantic_extract.extraction_validator import ExtractionValidator+from semantica.semantic_extract.methods import (+ calculate_weighted_confidence,+ extract_entities_ml,+)+from semantica.semantic_extract.named_entity_recognizer import (+ EntityConfidenceScorer,+)+from semantica.semantic_extract.ner_extractor import NERExtractor+from semantica.semantic_extract.types import (+ CONFIDENCE_SOURCE_HEURISTIC,+ CONFIDENCE_SOURCE_KEY,+ CONFIDENCE_SOURCE_MODEL,+ CONFIDENCE_SOURCE_UNAVAILABLE,+ Entity,+ meets_confidence_threshold,+)+++def _fake_span(text, label, start, end, **extra):+ return SimpleNamespace(+ text=text, label_=label, start_char=start, end_char=end, **extra+ )++++class TestEntityModel(unittest.TestCase):+ def test_default_confidence_is_unknown(self):+ entity = Entity(text="Apple", label="ORG", start_char=0, end_char=5)+ self.assertIsNone(entity.confidence)++ def test_meets_confidence_threshold(self):+ self.assertTrue(meets_confidence_threshold(None, 0.9))+ self.assertTrue(meets_confidence_threshold(0.9, 0.5))+ self.assertFalse(meets_confidence_threshold(0.4, 0.5))+++class TestSpacyAdapter(unittest.TestCase):+ def test_span_without_score_reports_unavailable(self):+ # _fake_span has neither .confidence nor .score, so confidence must be None.+ ents = [_fake_span("Apple Inc.", "ORG", 0, 10)]+ # Patch run_spacy_text (the function extract_entities_ml actually calls)+ # to return a Doc-like object directly, bypassing all spaCy I/O.+ fake_doc = SimpleNamespace(ents=ents)+ with patch(+ "semantica.semantic_extract.methods.SPACY_AVAILABLE", True+ ), patch(+ "semantica.semantic_extract.methods.run_spacy_text",+ return_value=fake_doc,+ ):+ entities = extract_entities_ml("Apple Inc. was founded.")++ self.assertEqual(len(entities), 1)+ self.assertIsNone(entities[0].confidence)+ self.assertEqual(+ entities[0].metadata[CONFIDENCE_SOURCE_KEY],+ CONFIDENCE_SOURCE_UNAVAILABLE,+ )++ def test_backend_provided_score_is_preserved(self):+ # Spans with explicit scores; both must come through unchanged.+ ents = [+ _fake_span("Apple Inc.", "ORG", 0, 10, score=0.83),+ _fake_span("Steve Jobs", "PERSON", 26, 36, confidence=1.0),+ ]+ fake_doc = SimpleNamespace(ents=ents)+ with patch(+ "semantica.semantic_extract.methods.SPACY_AVAILABLE", True+ ), patch(+ "semantica.semantic_extract.methods.run_spacy_text",+ return_value=fake_doc,+ ):+ entities = extract_entities_ml(+ "Apple Inc. was founded by Steve Jobs."+ )++ self.assertEqual(entities[0].confidence, 0.83)+ self.assertEqual(+ entities[0].metadata[CONFIDENCE_SOURCE_KEY], CONFIDENCE_SOURCE_MODEL+ )+ # A genuine 1.0 stays 1.0 and is marked as a real measurement+ self.assertEqual(entities[1].confidence, 1.0)+ self.assertEqual(+ entities[1].metadata[CONFIDENCE_SOURCE_KEY], CONFIDENCE_SOURCE_MODEL+ )+++class TestEntityConfidenceScorer(unittest.TestCase):+ def setUp(self):+ self.scorer = EntityConfidenceScorer()++ def test_unknown_confidence_gets_heuristic_score(self):+ entity = Entity(text="Apple", label="ORG", start_char=0, end_char=5)+ (scored,) = self.scorer.score_entities([entity])+ self.assertIsNotNone(scored.confidence)+ self.assertEqual(+ scored.metadata[CONFIDENCE_SOURCE_KEY], CONFIDENCE_SOURCE_HEURISTIC+ )++ def test_genuine_perfect_score_is_not_recalculated(self):+ # Lowercase ORG text would be penalized by the heuristic, so a+ # surviving 1.0 proves the backend score was preserved+ entity = Entity(+ text="apple",+ label="ORG",+ start_char=0,+ end_char=5,+ confidence=1.0,+ metadata={CONFIDENCE_SOURCE_KEY: CONFIDENCE_SOURCE_MODEL},+ )+ (scored,) = self.scorer.score_entities([entity])+ self.assertEqual(scored.confidence, 1.0)+ self.assertEqual(+ scored.metadata[CONFIDENCE_SOURCE_KEY], CONFIDENCE_SOURCE_MODEL+ )++ def test_backend_score_below_one_is_preserved(self):+ entity = Entity(+ text="Apple", label="ORG", start_char=0, end_char=5, confidence=0.6+ )+ (scored,) = self.scorer.score_entities([entity])+ self.assertEqual(scored.confidence, 0.6)+++class TestConfidenceFiltering(unittest.TestCase):+ def _entities(self):+ return [+ Entity(text="Apple", label="ORG", start_char=0, end_char=5),+ Entity(+ text="Jobs",+ label="PERSON",+ start_char=6,+ end_char=10,+ confidence=0.9,+ ),+ Entity(+ text="maybe",+ label="ORG",+ start_char=11,+ end_char=16,+ confidence=0.2,+ ),+ ]++ def test_validator_filter_passes_unknown_confidence(self):+ validator = ExtractionValidator(min_confidence=0.5)+ filtered = validator.filter_by_confidence(self._entities())+ self.assertEqual([e.text for e in filtered], ["Apple", "Jobs"])++ def test_ner_extractor_filter_passes_unknown_confidence(self):+ extractor = NERExtractor(method="pattern")+ filtered = extractor.filter_by_confidence(self._entities(), 0.5)+ self.assertEqual([e.text for e in filtered], ["Apple", "Jobs"])++ def test_validator_metrics_count_unscored_separately(self):+ validator = ExtractionValidator(min_confidence=0.5)+ result = validator.validate_entities(self._entities())+ metrics = result.metrics+ self.assertEqual(metrics["unscored"], 1)+ self.assertEqual(metrics["high_confidence"], 1)+ self.assertEqual(metrics["low_confidence"], 1)+ self.assertAlmostEqual(metrics["average_confidence"], 0.55)++ def test_vote_averages_only_measured_scores(self):+ extractor = NERExtractor(method="pattern")+ known = Entity(+ text="Apple", label="ORG", start_char=0, end_char=5, confidence=0.8+ )+ unknown = Entity(text="Apple", label="ORG", start_char=0, end_char=5)+ voted = extractor._vote_entities([[known], [unknown]], threshold=0.5)+ self.assertEqual(len(voted), 1)+ # The fabricated 1.0 no longer inflates the average+ self.assertAlmostEqual(voted[0].confidence, 0.8)++ def test_vote_keeps_agreement_without_scores(self):+ extractor = NERExtractor(method="pattern")+ a = Entity(text="Apple", label="ORG", start_char=0, end_char=5)+ b = Entity(text="Apple", label="ORG", start_char=0, end_char=5)+ voted = extractor._vote_entities([[a], [b]], threshold=0.5)+ self.assertEqual(len(voted), 1)+ self.assertIsNone(voted[0].confidence)+++class TestPipelineFillsUnknownConfidence(unittest.TestCase):+ def test_extract_emits_only_scored_entities(self):+ # The extract() pipeline scores unknown confidences before filtering,+ # so consumers of extract() never see None.+ ents = [_fake_span("Apple Inc.", "ORG", 0, 10)]+ fake_doc = SimpleNamespace(ents=ents)+ with patch(+ "semantica.semantic_extract.methods.SPACY_AVAILABLE", True+ ), patch(+ "semantica.semantic_extract.methods.run_spacy_text",+ return_value=fake_doc,+ ):+ extractor = NERExtractor(method="ml")+ entities = extractor.extract("Apple Inc. was founded.")++ self.assertTrue(entities)+ for entity in entities:+ self.assertIsNotNone(entity.confidence)+ self.assertEqual(+ entities[0].metadata[CONFIDENCE_SOURCE_KEY],+ CONFIDENCE_SOURCE_HEURISTIC,+ )++ def test_extract_preserves_measured_scores(self):+ ents = [_fake_span("Apple Inc.", "ORG", 0, 10, score=0.83)]+ fake_doc = SimpleNamespace(ents=ents)+ with patch(+ "semantica.semantic_extract.methods.SPACY_AVAILABLE", True+ ), patch(+ "semantica.semantic_extract.methods.run_spacy_text",+ return_value=fake_doc,+ ):+ entities = NERExtractor(method="ml").extract(+ "Apple Inc. was founded."+ )++ self.assertEqual(entities[0].confidence, 0.83)+ self.assertEqual(+ entities[0].metadata[CONFIDENCE_SOURCE_KEY], CONFIDENCE_SOURCE_MODEL+ )+++class TestWeightedConfidence(unittest.TestCase):+ def test_none_passthrough_without_valid_types(self):+ self.assertIsNone(+ calculate_weighted_confidence("ORG", None, valid_types=None)+ )++ def test_none_uses_similarity_alone(self):+ score = calculate_weighted_confidence(+ "PERSON", None, valid_types=["PERSON"], item_text="Steve Jobs"+ )+ self.assertIsNotNone(score)+ self.assertGreaterEqual(score, 0.0)+ self.assertLessEqual(score, 1.0)++ def test_none_stays_unknown_when_similarity_disabled(self):+ # Similarity explicitly disabled and no measured confidence:+ # the result must remain unknown, not a fabricated similarity score+ self.assertIsNone(+ calculate_weighted_confidence(+ "PERSON",+ None,+ valid_types=["PERSON"],+ item_text="Steve Jobs",+ weight_method=1.0,+ weight_similarity=0.0,+ )+ )+ self.assertIsNone(+ calculate_weighted_confidence(+ "PERSON",+ None,+ valid_types=["PERSON"],+ weight_method=0.0,+ weight_similarity=0.0,+ )+ )+++if __name__ == "__main__":+ unittest.main()