Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: Implement seed, vocabulary, and templates modules

KaifAhmad1b359e5a20c1e
diff --git a/libs/semantica/agents/tool_registry.py b/libs/semantica/agents/tool_registry.py
deleted file mode 100644
index 104bd0be..00000000
--- a/libs/semantica/agents/tool_registry.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""
-Tool Registry for Agent Tools
-
-Manages tool registration, discovery, and access for agents,
-supporting MCP servers for consistent tool interfaces.
-"""
-
-# TODO: Implement tool registry
-# - Tool registration and discovery
-# - MCP server integration
-# - Tool version management
-# - Tool access control
-# - Tool metadata and documentation
-# - Dynamic tool loading and unloading
diff --git a/libs/semantica/seed/__init__.py b/libs/semantica/seed/__init__.py
index a61e4bf0..c32ed477 100644
--- a/libs/semantica/seed/__init__.py
+++ b/libs/semantica/seed/__init__.py
@@ -5,9 +5,14 @@ This module provides seed data management for initial knowledge graph
loading with verified data to build on existing knowledge.
"""
-# TODO: Implement seed data system
-# - Seed data loading and validation
-# - Foundation graph creation from seed data
-# - Seed data verification and quality checking
-# - Integration with KG construction
-# - Seed data versioning
+from .seed_manager import (
+ SeedDataManager,
+ SeedDataSource,
+ SeedData,
+)
+
+__all__ = [
+ "SeedDataManager",
+ "SeedDataSource",
+ "SeedData",
+]
diff --git a/libs/semantica/seed/seed_manager.py b/libs/semantica/seed/seed_manager.py
index ca9d6380..bac05228 100644
--- a/libs/semantica/seed/seed_manager.py
+++ b/libs/semantica/seed/seed_manager.py
@@ -5,9 +5,536 @@ Manages seed data for initial knowledge graph construction,
enabling the AI to build on existing verified knowledge.
"""
-# TODO: Implement seed data manager
-# - Load verified seed data
-# - Create foundation graph from seed
-# - Validate seed data quality
-# - Integrate seed data with extraction
-# - Manage seed data versions
+from typing import Any, Dict, List, Optional, Union
+from dataclasses import dataclass, field
+from pathlib import Path
+import json
+import csv
+from datetime import datetime
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..utils.helpers import read_json_file, write_json_file
+from ..utils.types import EntityDict, RelationshipDict
+
+
+@dataclass
+class SeedDataSource:
+ """Seed data source definition."""
+ name: str
+ format: str # csv, json, database, api
+ location: Union[str, Path]
+ entity_type: Optional[str] = None
+ relationship_type: Optional[str] = None
+ verified: bool = True
+ version: str = "1.0"
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass
+class SeedData:
+ """Seed data container."""
+ entities: List[EntityDict] = field(default_factory=list)
+ relationships: List[RelationshipDict] = field(default_factory=list)
+ properties: Dict[str, Any] = field(default_factory=dict)
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+class SeedDataManager:
+ """
+ Seed data manager for initial knowledge graph construction.
+
+ • Loads verified seed data from multiple sources
+ • Creates foundation graph from seed data
+ • Validates seed data quality
+ • Integrates seed data with extraction results
+ • Manages seed data versions
+ """
+
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize seed data manager.
+
+ Args:
+ config: Configuration dictionary
+ **kwargs: Additional configuration options
+ """
+ self.logger = get_logger("seed_manager")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ self.sources: Dict[str, SeedDataSource] = {}
+ self.seed_data: SeedData = SeedData()
+ self.versions: Dict[str, List[str]] = {} # source_name -> versions
+
+ def register_source(
+ self,
+ name: str,
+ format: str,
+ location: Union[str, Path],
+ entity_type: Optional[str] = None,
+ relationship_type: Optional[str] = None,
+ verified: bool = True,
+ **metadata
+ ) -> bool:
+ """
+ Register a seed data source.
+
+ Args:
+ name: Source name
+ format: Data format ('csv', 'json', 'database', 'api')
+ location: Source location (file path, DB connection, API URL)
+ entity_type: Entity type for entities in this source
+ relationship_type: Relationship type for relationships in this source
+ verified: Whether data is verified
+ **metadata: Additional metadata
+
+ Returns:
+ True if registration successful
+ """
+ if name in self.sources:
+ self.logger.warning(f"Source '{name}' already registered, updating")
+
+ source = SeedDataSource(
+ name=name,
+ format=format,
+ location=location,
+ entity_type=entity_type,
+ relationship_type=relationship_type,
+ verified=verified,
+ metadata=metadata
+ )
+
+ self.sources[name] = source
+
+ # Track versions
+ if name not in self.versions:
+ self.versions[name] = []
+
+ self.logger.info(f"Registered seed data source: {name} ({format})")
+ return True
+
+ def load_from_csv(
+ self,
+ file_path: Union[str, Path],
+ entity_type: Optional[str] = None,
+ relationship_type: Optional[str] = None,
+ source_name: Optional[str] = None
+ ) -> List[Dict[str, Any]]:
+ """
+ Load seed data from CSV file.
+
+ Args:
+ file_path: Path to CSV file
+ entity_type: Entity type (if applicable)
+ relationship_type: Relationship type (if applicable)
+ source_name: Source name for tracking
+
+ Returns:
+ List of loaded data records
+ """
+ file_path = Path(file_path)
+ if not file_path.exists():
+ raise ProcessingError(f"CSV file not found: {file_path}")
+
+ records = []
+
+ try:
+ with open(file_path, 'r', encoding='utf-8') as f:
+ reader = csv.DictReader(f)
+ for row in reader:
+ # Clean up row data
+ record = {k: v for k, v in row.items() if v}
+
+ if entity_type:
+ record['entity_type'] = entity_type
+ if relationship_type:
+ record['relationship_type'] = relationship_type
+ if source_name:
+ record['source'] = source_name
+
+ records.append(record)
+
+ self.logger.info(f"Loaded {len(records)} records from CSV: {file_path}")
+ return records
+
+ except Exception as e:
+ raise ProcessingError(f"Failed to load CSV: {e}") from e
+
+ def load_from_json(
+ self,
+ file_path: Union[str, Path],
+ entity_type: Optional[str] = None,
+ relationship_type: Optional[str] = None,
+ source_name: Optional[str] = None
+ ) -> List[Dict[str, Any]]:
+ """
+ Load seed data from JSON file.
+
+ Args:
+ file_path: Path to JSON file
+ entity_type: Entity type (if applicable)
+ relationship_type: Relationship type (if applicable)
+ source_name: Source name for tracking
+
+ Returns:
+ List of loaded data records
+ """
+ file_path = Path(file_path)
+ if not file_path.exists():
+ raise ProcessingError(f"JSON file not found: {file_path}")
+
+ try:
+ data = read_json_file(file_path)
+
+ # Handle different JSON structures
+ if isinstance(data, list):
+ records = data
+ elif isinstance(data, dict):
+ # Try common keys
+ if 'entities' in data:
+ records = data['entities']
+ elif 'data' in data:
+ records = data['data']
+ elif 'records' in data:
+ records = data['records']
+ else:
+ records = [data]
+ else:
+ records = []
+
+ # Add metadata
+ for record in records:
+ if entity_type and 'entity_type' not in record:
+ record['entity_type'] = entity_type
+ if relationship_type and 'relationship_type' not in record:
+ record['relationship_type'] = relationship_type
+ if source_name and 'source' not in record:
+ record['source'] = source_name
+
+ self.logger.info(f"Loaded {len(records)} records from JSON: {file_path}")
+ return records
+
+ except Exception as e:
+ raise ProcessingError(f"Failed to load JSON: {e}") from e
+
+ def load_source(self, source_name: str) -> List[Dict[str, Any]]:
+ """
+ Load data from registered source.
+
+ Args:
+ source_name: Source name
+
+ Returns:
+ List of loaded data records
+ """
+ if source_name not in self.sources:
+ raise ProcessingError(f"Source '{source_name}' not registered")
+
+ source = self.sources[source_name]
+
+ if source.format == "csv":
+ return self.load_from_csv(
+ source.location,
+ entity_type=source.entity_type,
+ relationship_type=source.relationship_type,
+ source_name=source_name
+ )
+ elif source.format == "json":
+ return self.load_from_json(
+ source.location,
+ entity_type=source.entity_type,
+ relationship_type=source.relationship_type,
+ source_name=source_name
+ )
+ elif source.format == "database":
+ # Database loading would require DB connection
+ raise NotImplementedError("Database loading not yet implemented")
+ elif source.format == "api":
+ # API loading would require API client
+ raise NotImplementedError("API loading not yet implemented")
+ else:
+ raise ProcessingError(f"Unsupported source format: {source.format}")
+
+ def create_foundation_graph(
+ self,
+ schema_template: Optional[Any] = None
+ ) -> Dict[str, Any]:
+ """
+ Create foundation graph from seed data.
+
+ Args:
+ schema_template: Optional schema template for validation
+
+ Returns:
+ Foundation graph dictionary with entities and relationships
+ """
+ foundation = {
+ "entities": [],
+ "relationships": [],
+ "metadata": {
+ "created_at": datetime.now().isoformat(),
+ "source_count": len(self.sources),
+ "verified": True
+ }
+ }
+
+ # Load data from all sources
+ for source_name in self.sources:
+ try:
+ records = self.load_source(source_name)
+
+ for record in records:
+ # Extract entities
+ if 'entity_type' in record or 'id' in record:
+ entity = self._record_to_entity(record)
+ if entity:
+ foundation["entities"].append(entity)
+
+ # Extract relationships
+ if 'relationship_type' in record or ('source_id' in record and 'target_id' in record):
+ relationship = self._record_to_relationship(record)
+ if relationship:
+ foundation["relationships"].append(relationship)
+
+ except Exception as e:
+ self.logger.warning(f"Failed to load source '{source_name}': {e}")
+
+ # Validate against schema template if provided
+ if schema_template:
+ foundation = self._validate_against_template(foundation, schema_template)
+
+ self.logger.info(
+ f"Created foundation graph: {len(foundation['entities'])} entities, "
+ f"{len(foundation['relationships'])} relationships"
+ )
+
+ return foundation
+
+ def integrate_with_extracted(
+ self,
+ seed_data: Dict[str, Any],
+ extracted_data: Dict[str, Any],
+ merge_strategy: str = "seed_first"
+ ) -> Dict[str, Any]:
+ """
+ Integrate seed data with extracted data.
+
+ Args:
+ seed_data: Seed data dictionary
+ extracted_data: Extracted data dictionary
+ merge_strategy: Merge strategy ('seed_first', 'extracted_first', 'merge')
+
+ Returns:
+ Integrated data dictionary
+ """
+ integrated = {
+ "entities": [],
+ "relationships": [],
+ "metadata": {
+ "merged_at": datetime.now().isoformat(),
+ "merge_strategy": merge_strategy,
+ "seed_count": len(seed_data.get("entities", [])),
+ "extracted_count": len(extracted_data.get("entities", []))
+ }
+ }
+
+ seed_entities = {e.get("id"): e for e in seed_data.get("entities", [])}
+ extracted_entities = {e.get("id"): e for e in extracted_data.get("entities", [])}
+
+ # Merge entities based on strategy
+ if merge_strategy == "seed_first":
+ # Seed data takes precedence
+ integrated["entities"] = list(seed_entities.values())
+ for eid, entity in extracted_entities.items():
+ if eid not in seed_entities:
+ integrated["entities"].append(entity)
+
+ elif merge_strategy == "extracted_first":
+ # Extracted data takes precedence
+ integrated["entities"] = list(extracted_entities.values())
+ for eid, entity in seed_entities.items():
+ if eid not in extracted_entities:
+ integrated["entities"].append(entity)
+
+ elif merge_strategy == "merge":
+ # Merge properties, seed takes precedence for conflicts
+ all_entity_ids = set(seed_entities.keys()) | set(extracted_entities.keys())
+ for eid in all_entity_ids:
+ seed_entity = seed_entities.get(eid, {})
+ extracted_entity = extracted_entities.get(eid, {})
+
+ merged = {**extracted_entity, **seed_entity}
+ integrated["entities"].append(merged)
+
+ # Merge relationships
+ seed_rels = {(r.get("source_id"), r.get("target_id"), r.get("type")): r
+ for r in seed_data.get("relationships", [])}
+ extracted_rels = {(r.get("source_id"), r.get("target_id"), r.get("type")): r
+ for r in extracted_data.get("relationships", [])}
+
+ if merge_strategy == "seed_first":
+ integrated["relationships"] = list(seed_rels.values())
+ for key, rel in extracted_rels.items():
+ if key not in seed_rels:
+ integrated["relationships"].append(rel)
+ else:
+ integrated["relationships"] = list(seed_rels.values())
+ for key, rel in extracted_rels.items():
+ if key not in seed_rels:
+ integrated["relationships"].append(rel)
+
+ self.logger.info(
+ f"Integrated data: {len(integrated['entities'])} entities, "
+ f"{len(integrated['relationships'])} relationships"
+ )
+
+ return integrated
+
+ def validate_quality(
+ self,
+ seed_data: Dict[str, Any],
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Validate seed data quality.
+
+ Args:
+ seed_data: Seed data dictionary
+ **options: Validation options:
+ - check_required_fields: Check required fields (default: True)
+ - check_types: Validate data types (default: True)
+ - check_consistency: Check consistency (default: True)
+
+ Returns:
+ Validation result dictionary
+ """
+ results = {
+ "valid": True,
+ "errors": [],
+ "warnings": [],
+ "metrics": {}
+ }
+
+ entities = seed_data.get("entities", [])
+ relationships = seed_data.get("relationships", [])
+
+ # Check entities
+ entity_ids = []
+ for entity in entities:
+ if "id" not in entity:
+ results["errors"].append("Entity missing 'id' field")
+ results["valid"] = False
+ else:
+ if entity["id"] in entity_ids:
+ results["warnings"].append(f"Duplicate entity ID: {entity['id']}")
+ entity_ids.append(entity["id"])
+
+ if "type" not in entity:
+ results["warnings"].append(f"Entity {entity.get('id')} missing 'type' field")
+
+ # Check relationships
+ for rel in relationships:
+ if "source_id" not in rel or "target_id" not in rel:
+ results["errors"].append("Relationship missing source_id or target_id")
+ results["valid"] = False
+
+ if "type" not in rel:
+ results["warnings"].append("Relationship missing 'type' field")
+
+ # Calculate metrics
+ results["metrics"] = {
+ "entity_count": len(entities),
+ "relationship_count": len(relationships),
+ "unique_entity_ids": len(set(entity_ids)),
+ "duplicate_entities": len(entities) - len(set(entity_ids))
+ }
+
+ return results
+
+ def _record_to_entity(self, record: Dict[str, Any]) -> Optional[EntityDict]:
+ """Convert record to entity dictionary."""
+ if "id" not in record:
+ return None
+
+ entity = {
+ "id": record["id"],
+ "text": record.get("text") or record.get("name") or record.get("label", ""),
+ "type": record.get("entity_type") or record.get("type", "UNKNOWN"),
+ "confidence": record.get("confidence", 1.0),
+ "metadata": {k: v for k, v in record.items()
+ if k not in ["id", "text", "name", "label", "type", "entity_type", "confidence"]}
+ }
+
+ return entity
+
+ def _record_to_relationship(self, record: Dict[str, Any]) -> Optional[RelationshipDict]:
+ """Convert record to relationship dictionary."""
+ if "source_id" not in record or "target_id" not in record:
+ return None
+
+ relationship = {
+ "id": record.get("id") or f"{record['source_id']}_{record['target_id']}",
+ "source_id": record["source_id"],
+ "target_id": record["target_id"],
+ "type": record.get("relationship_type") or record.get("type", "RELATED_TO"),
+ "confidence": record.get("confidence", 1.0),
+ "metadata": {k: v for k, v in record.items()
+ if k not in ["id", "source_id", "target_id", "type", "relationship_type", "confidence"]}
+ }
+
+ return relationship
+
+ def _validate_against_template(
+ self,
+ foundation: Dict[str, Any],
+ schema_template: Any
+ ) -> Dict[str, Any]:
+ """Validate foundation against schema template."""
+ # This would use schema template validation if available
+ # For now, just return the foundation
+ return foundation
+
+ def export_seed_data(
+ self,
+ file_path: Union[str, Path],
+ format: str = "json"
+ ) -> None:
+ """
+ Export seed data to file.
+
+ Args:
+ file_path: Output file path
+ format: Export format ('json', 'csv')
+ """
+ file_path = Path(file_path)
+
+ if format == "json":
+ export_data = {
+ "entities": self.seed_data.entities,
+ "relationships": self.seed_data.relationships,
+ "metadata": {
+ **self.seed_data.metadata,
+ "exported_at": datetime.now().isoformat()
+ }
+ }
+ write_json_file(export_data, file_path)
+
+ elif format == "csv":
+ # Export entities to CSV
+ entities_file = file_path.parent / f"{file_path.stem}_entities.csv"
+ if self.seed_data.entities:
+ with open(entities_file, 'w', newline='', encoding='utf-8') as f:
+ writer = csv.DictWriter(f, fieldnames=self.seed_data.entities[0].keys())
+ writer.writeheader()
+ writer.writerows(self.seed_data.entities)
+
+ # Export relationships to CSV
+ relationships_file = file_path.parent / f"{file_path.stem}_relationships.csv"
+ if self.seed_data.relationships:
+ with open(relationships_file, 'w', newline='', encoding='utf-8') as f:
+ writer = csv.DictWriter(f, fieldnames=self.seed_data.relationships[0].keys())
+ writer.writeheader()
+ writer.writerows(self.seed_data.relationships)
+
+ self.logger.info(f"Exported seed data to: {file_path}")
diff --git a/libs/semantica/templates/__init__.py b/libs/semantica/templates/__init__.py
index 712124f6..acb1467f 100644
--- a/libs/semantica/templates/__init__.py
+++ b/libs/semantica/templates/__init__.py
@@ -5,9 +5,16 @@ This module provides template-based knowledge graph construction
with schema validation and entity templates.
"""
-# TODO: Implement template system
-# - Schema template definition and validation
-# - Entity template management
-# - Template-based KG construction
-# - Template matching and application
-# - Template versioning
+from .schema_template import (
+ SchemaTemplateManager,
+ SchemaTemplate,
+ EntityTemplate,
+ RelationshipTemplate,
+)
+
+__all__ = [
+ "SchemaTemplateManager",
+ "SchemaTemplate",
+ "EntityTemplate",
+ "RelationshipTemplate",
+]
diff --git a/libs/semantica/vocabulary/__init__.py b/libs/semantica/vocabulary/__init__.py
index bf189965..233c4860 100644
--- a/libs/semantica/vocabulary/__init__.py
+++ b/libs/semantica/vocabulary/__init__.py
@@ -6,14 +6,16 @@ that supplement ontologies with relevant terminology. Vocabularies connect
to ontology classes to provide structured, pre-defined term hierarchies.
"""
-# from .vocabulary_manager import VocabularyManager
-# from .controlled_vocabulary import ControlledVocabulary
-# from .vocabulary_builder import VocabularyBuilder
+from .vocabulary_manager import VocabularyManager
+from .controlled_vocabulary import (
+ ControlledVocabulary,
+ VocabularyTerm,
+ TermRelation,
+)
-# TODO: Implement vocabulary system
-# - Hierarchical vocabulary construction
-# - Controlled term management
-# - Vocabulary connection to ontology classes
-# - Multi-language vocabulary support
-# - Synonym management in vocabularies
-# - SKOS vocabulary support
+__all__ = [
+ "VocabularyManager",
+ "ControlledVocabulary",
+ "VocabularyTerm",
+ "TermRelation",
+]
diff --git a/libs/semantica/vocabulary/controlled_vocabulary.py b/libs/semantica/vocabulary/controlled_vocabulary.py
index 4c718b67..e383070d 100644
--- a/libs/semantica/vocabulary/controlled_vocabulary.py
+++ b/libs/semantica/vocabulary/controlled_vocabulary.py
@@ -6,10 +6,427 @@ connected to ontology classes. Useful when classes have many known
subtypes that share attributes but don't need separate modeling.
"""
-# TODO: Implement controlled vocabulary
-# - Define hierarchical term structures
-# - Manage term hierarchies (broader/narrower)
-# - Support term specificity levels
-# - Enable vocabulary connection to classes
-# - Handle term updates without ontology changes
-# - Support SKOS vocabulary standards
+from typing import Any, Dict, List, Optional, Set
+from dataclasses import dataclass, field
+from enum import Enum
+
+from ..utils.exceptions import ValidationError
+from ..utils.logging import get_logger
+
+
+class TermRelation(str, Enum):
+ """Term relationship types."""
+ BROADER = "broader"
+ NARROWER = "narrower"
+ RELATED = "related"
+ EXACT_MATCH = "exactMatch"
+ CLOSE_MATCH = "closeMatch"
+ BROAD_MATCH = "broadMatch"
+ NARROW_MATCH = "narrowMatch"
+
+
+@dataclass
+class VocabularyTerm:
+ """Controlled vocabulary term."""
+ uri: str
+ label: str
+ definition: Optional[str] = None
+ notation: Optional[str] = None
+ broader_terms: List[str] = field(default_factory=list)
+ narrower_terms: List[str] = field(default_factory=list)
+ related_terms: List[str] = field(default_factory=list)
+ alt_labels: List[str] = field(default_factory=list)
+ hidden_labels: List[str] = field(default_factory=list)
+ scope_note: Optional[str] = None
+ examples: List[str] = field(default_factory=list)
+ in_scheme: Optional[str] = None
+ top_concept_of: Optional[str] = None
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+class ControlledVocabulary:
+ """
+ Controlled vocabulary with hierarchical term structure.
+
+ • Manages hierarchical term structures (broader/narrower)
+ • Supports SKOS vocabulary standards
+ • Enables vocabulary connection to ontology classes
+ • Handles term updates without ontology changes
+ """
+
+ def __init__(
+ self,
+ uri: str,
+ title: str,
+ description: Optional[str] = None,
+ **metadata
+ ):
+ """
+ Initialize controlled vocabulary.
+
+ Args:
+ uri: Vocabulary URI
+ title: Vocabulary title
+ description: Vocabulary description
+ **metadata: Additional metadata
+ """
+ self.logger = get_logger("controlled_vocabulary")
+ self.uri = uri
+ self.title = title
+ self.description = description
+ self.metadata = metadata
+
+ self.terms: Dict[str, VocabularyTerm] = {}
+ self.top_concepts: List[str] = []
+ self.ontology_classes: Dict[str, str] = {} # term_uri -> class_uri
+
+ def add_term(
+ self,
+ term: VocabularyTerm,
+ top_concept: bool = False
+ ) -> bool:
+ """
+ Add term to vocabulary.
+
+ Args:
+ term: Vocabulary term
+ top_concept: Whether this is a top-level concept
+
+ Returns:
+ True if term added successfully
+ """
+ if term.uri in self.terms:
+ self.logger.warning(f"Term '{term.uri}' already exists, updating")
+
+ self.terms[term.uri] = term
+ term.in_scheme = self.uri
+
+ if top_concept:
+ term.top_concept_of = self.uri
+ if term.uri not in self.top_concepts:
+ self.top_concepts.append(term.uri)
+
+ self.logger.info(f"Added term: {term.uri}")
+ return True
+
+ def remove_term(self, term_uri: str) -> bool:
+ """
+ Remove term from vocabulary.
+
+ Args:
+ term_uri: Term URI
+
+ Returns:
+ True if term removed successfully
+ """
+ if term_uri not in self.terms:
+ return False
+
+ term = self.terms[term_uri]
+
+ # Remove from broader terms' narrower lists
+ for broader_uri in term.broader_terms:
+ if broader_uri in self.terms:
+ if term_uri in self.terms[broader_uri].narrower_terms:
+ self.terms[broader_uri].narrower_terms.remove(term_uri)
+
+ # Remove from narrower terms' broader lists
+ for narrower_uri in term.narrower_terms:
+ if narrower_uri in self.terms:
+ if term_uri in self.terms[narrower_uri].broader_terms:
+ self.terms[narrower_uri].broader_terms.remove(term_uri)
+
+ # Remove from top concepts
+ if term_uri in self.top_concepts:
+ self.top_concepts.remove(term_uri)
+
+ del self.terms[term_uri]
+ self.logger.info(f"Removed term: {term_uri}")
+ return True
+
+ def add_broader_term(
+ self,
+ term_uri: str,
+ broader_uri: str
+ ) -> bool:
+ """
+ Add broader term relationship.
+
+ Args:
+ term_uri: Term URI
+ broader_uri: Broader term URI
+
+ Returns:
+ True if relationship added successfully
+ """
+ if term_uri not in self.terms or broader_uri not in self.terms:
+ raise ValidationError("Both terms must exist in vocabulary")
+
+ if broader_uri not in self.terms[term_uri].broader_terms:
+ self.terms[term_uri].broader_terms.append(broader_uri)
+
+ if term_uri not in self.terms[broader_uri].narrower_terms:
+ self.terms[broader_uri].narrower_terms.append(term_uri)
+
+ return True
+
+ def add_narrower_term(
+ self,
+ term_uri: str,
+ narrower_uri: str
+ ) -> bool:
+ """
+ Add narrower term relationship.
+
+ Args:
+ term_uri: Term URI
+ narrower_uri: Narrower term URI
+
+ Returns:
+ True if relationship added successfully
+ """
+ return self.add_broader_term(narrower_uri, term_uri)
+
+ def add_related_term(
+ self,
+ term_uri: str,
+ related_uri: str
+ ) -> bool:
+ """
+ Add related term relationship.
+
+ Args:
+ term_uri: Term URI
+ related_uri: Related term URI
+
+ Returns:
+ True if relationship added successfully
+ """
+ if term_uri not in self.terms or related_uri not in self.terms:
+ raise ValidationError("Both terms must exist in vocabulary")
+
+ if related_uri not in self.terms[term_uri].related_terms:
+ self.terms[term_uri].related_terms.append(related_uri)
+
+ if term_uri not in self.terms[related_uri].related_terms:
+ self.terms[related_uri].related_terms.append(term_uri)
+
+ return True
+
+ def get_term(self, term_uri: str) -> Optional[VocabularyTerm]:
+ """
+ Get term by URI.
+
+ Args:
+ term_uri: Term URI
+
+ Returns:
+ Vocabulary term or None if not found
+ """
+ return self.terms.get(term_uri)
+
+ def get_broader_terms(
+ self,
+ term_uri: str,
+ transitive: bool = False
+ ) -> List[str]:
+ """
+ Get broader terms.
+
+ Args:
+ term_uri: Term URI
+ transitive: Include transitive broader terms
+
+ Returns:
+ List of broader term URIs
+ """
+ if term_uri not in self.terms:
+ return []
+
+ broader = list(self.terms[term_uri].broader_terms)
+
+ if transitive:
+ for broader_uri in broader:
+ broader.extend(self.get_broader_terms(broader_uri, transitive=True))
+
+ return list(set(broader))
+
+ def get_narrower_terms(
+ self,
+ term_uri: str,
+ transitive: bool = False
+ ) -> List[str]:
+ """
+ Get narrower terms.
+
+ Args:
+ term_uri: Term URI
+ transitive: Include transitive narrower terms
+
+ Returns:
+ List of narrower term URIs
+ """
+ if term_uri not in self.terms:
+ return []
+
+ narrower = list(self.terms[term_uri].narrower_terms)
+
+ if transitive:
+ for narrower_uri in narrower:
+ narrower.extend(self.get_narrower_terms(narrower_uri, transitive=True))
+
+ return list(set(narrower))
+
+ def connect_to_ontology_class(
+ self,
+ term_uri: str,
+ class_uri: str
+ ) -> bool:
+ """
+ Connect vocabulary term to ontology class.
+
+ Args:
+ term_uri: Term URI
+ class_uri: Ontology class URI
+
+ Returns:
+ True if connection successful
+ """
+ if term_uri not in self.terms:
+ raise ValidationError(f"Term '{term_uri}' not found")
+
+ self.ontology_classes[term_uri] = class_uri
+ self.logger.info(f"Connected term {term_uri} to class {class_uri}")
+ return True
+
+ def search_terms(
+ self,
+ query: str,
+ search_labels: bool = True,
+ search_definitions: bool = True
+ ) -> List[str]:
+ """
+ Search for terms by query.
+
+ Args:
+ query: Search query
+ search_labels: Search in labels
+ search_definitions: Search in definitions
+
+ Returns:
+ List of matching term URIs
+ """
+ query_lower = query.lower()
+ matches = []
+
+ for term_uri, term in self.terms.items():
+ matched = False
+
+ if search_labels:
+ if query_lower in term.label.lower():
+ matched = True
+ for alt_label in term.alt_labels:
+ if query_lower in alt_label.lower():
+ matched = True
+
+ if search_definitions and term.definition:
+ if query_lower in term.definition.lower():
+ matched = True
+
+ if matched:
+ matches.append(term_uri)
+
+ return matches
+
+ def to_skos(self) -> Dict[str, Any]:
+ """
+ Convert vocabulary to SKOS format.
+
+ Returns:
+ SKOS vocabulary dictionary
+ """
+ skos = {
+ "@context": {
+ "skos": "http://www.w3.org/2004/02/skos/core#",
+ "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
+ "rdfs": "http://www.w3.org/2000/01/rdf-schema#"
+ },
+ "@type": "skos:ConceptScheme",
+ "@id": self.uri,
+ "skos:prefLabel": {
+ "@value": self.title,
+ "@language": "en"
+ },
+ "skos:hasTopConcept": [{"@id": uri} for uri in self.top_concepts],
+ "skos:concept": []
+ }
+
+ if self.description:
+ skos["skos:definition"] = {
+ "@value": self.description,
+ "@language": "en"
+ }
+
+ # Convert terms to SKOS
+ for term_uri, term in self.terms.items():
+ concept = {
+ "@id": term_uri,
+ "@type": "skos:Concept",
+ "skos:prefLabel": {
+ "@value": term.label,
+ "@language": "en"
+ },
+ "skos:inScheme": {"@id": self.uri}
+ }
+
+ if term.definition:
+ concept["skos:definition"] = {
+ "@value": term.definition,
+ "@language": "en"
+ }
+
+ if term.notation:
+ concept["skos:notation"] = term.notation
+
+ if term.broader_terms:
+ concept["skos:broader"] = [{"@id": uri} for uri in term.broader_terms]
+
+ if term.narrower_terms:
+ concept["skos:narrower"] = [{"@id": uri} for uri in term.narrower_terms]
+
+ if term.related_terms:
+ concept["skos:related"] = [{"@id": uri} for uri in term.related_terms]
+
+ if term.alt_labels:
+ concept["skos:altLabel"] = [
+ {"@value": label, "@language": "en"}
+ for label in term.alt_labels
+ ]
+
+ if term.scope_note:
+ concept["skos:scopeNote"] = {
+ "@value": term.scope_note,
+ "@language": "en"
+ }
+
+ skos["skos:concept"].append(concept)
+
+ return skos
+
+ def get_statistics(self) -> Dict[str, Any]:
+ """
+ Get vocabulary statistics.
+
+ Returns:
+ Statistics dictionary
+ """
+ return {
+ "uri": self.uri,
+ "title": self.title,
+ "term_count": len(self.terms),
+ "top_concept_count": len(self.top_concepts),
+ "ontology_connections": len(self.ontology_classes),
+ "terms_with_broader": sum(1 for t in self.terms.values() if t.broader_terms),
+ "terms_with_narrower": sum(1 for t in self.terms.values() if t.narrower_terms),
+ "terms_with_related": sum(1 for t in self.terms.values() if t.related_terms)
+ }
diff --git a/libs/semantica/vocabulary/vocabulary_manager.py b/libs/semantica/vocabulary/vocabulary_manager.py
index 7578440b..aec1267b 100644
--- a/libs/semantica/vocabulary/vocabulary_manager.py
+++ b/libs/semantica/vocabulary/vocabulary_manager.py
@@ -6,10 +6,330 @@ terminology, enabling concise modeling when many concepts share attributes
but don't need unique modeling.
"""
-# TODO: Implement vocabulary manager
-# - Create and manage controlled vocabularies
-# - Build hierarchical term structures
-# - Connect vocabularies to ontology classes
-# - Support multi-language terms
-# - Manage synonyms and alternative labels
-# - Export vocabularies in SKOS format
+from typing import Any, Dict, List, Optional, Union
+from pathlib import Path
+
+from .controlled_vocabulary import ControlledVocabulary, VocabularyTerm
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..utils.helpers import read_json_file, write_json_file
+
+
+class VocabularyManager:
+ """
+ Manager for controlled vocabularies.
+
+ • Creates and manages multiple controlled vocabularies
+ • Builds hierarchical term structures
+ • Connects vocabularies to ontology classes
+ • Supports multi-language terms
+ • Manages synonyms and alternative labels
+ • Exports vocabularies in SKOS format
+ """
+
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize vocabulary manager.
+
+ Args:
+ config: Configuration dictionary
+ **kwargs: Additional configuration options
+ """
+ self.logger = get_logger("vocabulary_manager")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ self.vocabularies: Dict[str, ControlledVocabulary] = {}
+
+ def create_vocabulary(
+ self,
+ uri: str,
+ title: str,
+ description: Optional[str] = None,
+ **metadata
+ ) -> ControlledVocabulary:
+ """
+ Create a new controlled vocabulary.
+
+ Args:
+ uri: Vocabulary URI
+ title: Vocabulary title
+ description: Vocabulary description
+ **metadata: Additional metadata
+
+ Returns:
+ Created ControlledVocabulary
+
+ Raises:
+ ValidationError: If vocabulary with URI already exists
+ """
+ if uri in self.vocabularies:
+ raise ValidationError(f"Vocabulary with URI '{uri}' already exists")
+
+ vocabulary = ControlledVocabulary(
+ uri=uri,
+ title=title,
+ description=description,
+ **metadata
+ )
+
+ self.vocabularies[uri] = vocabulary
+ self.logger.info(f"Created vocabulary: {title} ({uri})")
+
+ return vocabulary
+
+ def get_vocabulary(self, uri: str) -> Optional[ControlledVocabulary]:
+ """
+ Get vocabulary by URI.
+
+ Args:
+ uri: Vocabulary URI
+
+ Returns:
+ ControlledVocabulary or None if not found
+ """
+ return self.vocabularies.get(uri)
+
+ def remove_vocabulary(self, uri: str) -> bool:
+ """
+ Remove vocabulary.
+
+ Args:
+ uri: Vocabulary URI
+
+ Returns:
+ True if vocabulary removed successfully
+ """
+ if uri not in self.vocabularies:
+ return False
+
+ del self.vocabularies[uri]
+ self.logger.info(f"Removed vocabulary: {uri}")
+ return True
+
+ def list_vocabularies(self) -> List[str]:
+ """
+ List all vocabulary URIs.
+
+ Returns:
+ List of vocabulary URIs
+ """
+ return list(self.vocabularies.keys())
+
+ def add_term_to_vocabulary(
+ self,
+ vocabulary_uri: str,
+ term: VocabularyTerm,
+ top_concept: bool = False
+ ) -> bool:
+ """
+ Add term to vocabulary.
+
+ Args:
+ vocabulary_uri: Vocabulary URI
+ term: Vocabulary term
+ top_concept: Whether this is a top-level concept
+
+ Returns:
+ True if term added successfully
+ """
+ vocabulary = self.get_vocabulary(vocabulary_uri)
+ if not vocabulary:
+ raise ValidationError(f"Vocabulary '{vocabulary_uri}' not found")
+
+ return vocabulary.add_term(term, top_concept=top_concept)
+
+ def search_across_vocabularies(
+ self,
+ query: str,
+ vocabulary_uris: Optional[List[str]] = None,
+ search_labels: bool = True,
+ search_definitions: bool = True
+ ) -> Dict[str, List[str]]:
+ """
+ Search for terms across vocabularies.
+
+ Args:
+ query: Search query
+ vocabulary_uris: List of vocabulary URIs to search (None = all)
+ search_labels: Search in labels
+ search_definitions: Search in definitions
+
+ Returns:
+ Dictionary mapping vocabulary URI to list of matching term URIs
+ """
+ results = {}
+
+ vocab_uris = vocabulary_uris or self.list_vocabularies()
+
+ for vocab_uri in vocab_uris:
+ vocabulary = self.get_vocabulary(vocab_uri)
+ if vocabulary:
+ matches = vocabulary.search_terms(
+ query,
+ search_labels=search_labels,
+ search_definitions=search_definitions
+ )
+ if matches:
+ results[vocab_uri] = matches
+
+ return results
+
+ def connect_term_to_class(
+ self,
+ vocabulary_uri: str,
+ term_uri: str,
+ class_uri: str
+ ) -> bool:
+ """
+ Connect vocabulary term to ontology class.
+
+ Args:
+ vocabulary_uri: Vocabulary URI
+ term_uri: Term URI
+ class_uri: Ontology class URI
+
+ Returns:
+ True if connection successful
+ """
+ vocabulary = self.get_vocabulary(vocabulary_uri)
+ if not vocabulary:
+ raise ValidationError(f"Vocabulary '{vocabulary_uri}' not found")
+
+ return vocabulary.connect_to_ontology_class(term_uri, class_uri)
+
+ def export_vocabulary(
+ self,
+ vocabulary_uri: str,
+ file_path: Union[str, Path],
+ format: str = "skos"
+ ) -> None:
+ """
+ Export vocabulary to file.
+
+ Args:
+ vocabulary_uri: Vocabulary URI
+ file_path: Output file path
+ format: Export format ('skos', 'json')
+ """
+ vocabulary = self.get_vocabulary(vocabulary_uri)
+ if not vocabulary:
+ raise ValidationError(f"Vocabulary '{vocabulary_uri}' not found")
+
+ file_path = Path(file_path)
+
+ if format == "skos":
+ skos_data = vocabulary.to_skos()
+ write_json_file(skos_data, file_path)
+
+ elif format == "json":
+ vocab_data = {
+ "uri": vocabulary.uri,
+ "title": vocabulary.title,
+ "description": vocabulary.description,
+ "metadata": vocabulary.metadata,
+ "top_concepts": vocabulary.top_concepts,
+ "terms": [
+ {
+ "uri": term.uri,
+ "label": term.label,
+ "definition": term.definition,
+ "notation": term.notation,
+ "broader_terms": term.broader_terms,
+ "narrower_terms": term.narrower_terms,
+ "related_terms": term.related_terms,
+ "alt_labels": term.alt_labels,
+ "scope_note": term.scope_note,
+ "examples": term.examples,
+ "metadata": term.metadata
+ }
+ for term in vocabulary.terms.values()
+ ],
+ "ontology_classes": vocabulary.ontology_classes
+ }
+ write_json_file(vocab_data, file_path)
+
+ else:
+ raise ValueError(f"Unsupported export format: {format}")
+
+ self.logger.info(f"Exported vocabulary {vocabulary_uri} to {file_path}")
+
+ def import_vocabulary(
+ self,
+ file_path: Union[str, Path],
+ format: str = "json"
+ ) -> ControlledVocabulary:
+ """
+ Import vocabulary from file.
+
+ Args:
+ file_path: Input file path
+ format: Import format ('skos', 'json')
+
+ Returns:
+ Imported ControlledVocabulary
+ """
+ file_path = Path(file_path)
+ if not file_path.exists():
+ raise ProcessingError(f"File not found: {file_path}")
+
+ if format == "json":
+ data = read_json_file(file_path)
+
+ vocabulary = ControlledVocabulary(
+ uri=data["uri"],
+ title=data["title"],
+ description=data.get("description"),
+ **data.get("metadata", {})
+ )
+
+ # Import terms
+ for term_data in data.get("terms", []):
+ term = VocabularyTerm(
+ uri=term_data["uri"],
+ label=term_data["label"],
+ definition=term_data.get("definition"),
+ notation=term_data.get("notation"),
+ broader_terms=term_data.get("broader_terms", []),
+ narrower_terms=term_data.get("narrower_terms", []),
+ related_terms=term_data.get("related_terms", []),
+ alt_labels=term_data.get("alt_labels", []),
+ scope_note=term_data.get("scope_note"),
+ examples=term_data.get("examples", []),
+ metadata=term_data.get("metadata", {})
+ )
+ vocabulary.add_term(term, top_concept=term_data["uri"] in data.get("top_concepts", []))
+
+ # Import ontology connections
+ for term_uri, class_uri in data.get("ontology_classes", {}).items():
+ vocabulary.ontology_classes[term_uri] = class_uri
+
+ self.vocabularies[vocabulary.uri] = vocabulary
+ self.logger.info(f"Imported vocabulary: {vocabulary.title}")
+
+ return vocabulary
+
+ elif format == "skos":
+ # SKOS import would require parsing SKOS JSON-LD
+ raise NotImplementedError("SKOS import not yet fully implemented")
+
+ else:
+ raise ValueError(f"Unsupported import format: {format}")
+
+ def get_statistics(self) -> Dict[str, Any]:
+ """
+ Get statistics for all vocabularies.
+
+ Returns:
+ Statistics dictionary
+ """
+ stats = {
+ "vocabulary_count": len(self.vocabularies),
+ "total_terms": sum(len(v.terms) for v in self.vocabularies.values()),
+ "vocabularies": {}
+ }
+
+ for vocab_uri, vocabulary in self.vocabularies.items():
+ stats["vocabularies"][vocab_uri] = vocabulary.get_statistics()
+
+ return stats