Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

refactor(export): enhance documentation and code quality for all export modules

KaifAhmad1d253dc28ddf9
diff --git a/semantica/export/__init__.py b/semantica/export/__init__.py
index b929871c..e81ee2b6 100644
--- a/semantica/export/__init__.py
+++ b/semantica/export/__init__.py
@@ -1,15 +1,36 @@
"""
Export and Reporting Module
-This module provides comprehensive export and reporting capabilities.
+This module provides comprehensive export and reporting capabilities for the
+Semantica framework, supporting multiple formats and use cases.
-Exports:
- - RDFExporter: RDF format export
- - JSONExporter: JSON format export
- - CSVExporter: CSV format export
- - GraphExporter: Graph format export
+Key Features:
+ - Multiple export formats (RDF, JSON, CSV, Graph, YAML, OWL, Vector)
+ - Knowledge graph export
+ - Report generation (HTML, Markdown, JSON, Text)
+ - Vector store integration
+ - Batch export processing
+ - Metadata and provenance tracking
+
+Main Classes:
+ - RDFExporter: RDF format export (Turtle, RDF/XML, JSON-LD)
+ - JSONExporter: JSON and JSON-LD format export
+ - CSVExporter: CSV format export for tabular data
+ - GraphExporter: Graph format export (GraphML, GEXF, DOT)
- YAMLExporter: YAML format export for semantic networks
- - ReportGenerator: Report generation
+ - OWLExporter: OWL format export for ontologies
+ - VectorExporter: Vector embedding export for vector stores
+ - ReportGenerator: Report generation (HTML, Markdown, JSON, Text)
+
+Example Usage:
+ >>> from semantica.export import JSONExporter, CSVExporter
+ >>> json_exporter = JSONExporter()
+ >>> json_exporter.export_knowledge_graph(kg, "output.json")
+ >>> csv_exporter = CSVExporter()
+ >>> csv_exporter.export_entities(entities, "entities.csv")
+
+Author: Semantica Contributors
+License: MIT
"""
from .rdf_exporter import (
diff --git a/semantica/export/csv_exporter.py b/semantica/export/csv_exporter.py
index e61bd8c3..6213db7b 100644
--- a/semantica/export/csv_exporter.py
+++ b/semantica/export/csv_exporter.py
@@ -1,8 +1,26 @@
"""
-CSV exporter for Semantica framework.
+CSV Exporter Module
-This module provides CSV export capabilities
-for tabular data and structured information.
+This module provides comprehensive CSV export capabilities for the Semantica
+framework, enabling tabular data export for entities, relationships, and
+knowledge graphs.
+
+Key Features:
+ - CSV export for entities and relationships
+ - Knowledge graph export to multiple CSV files
+ - Configurable delimiters and encoding
+ - Metadata serialization
+ - Batch export processing
+ - Custom field name support
+
+Example Usage:
+ >>> from semantica.export import CSVExporter
+ >>> exporter = CSVExporter(delimiter=",", encoding="utf-8")
+ >>> exporter.export_entities(entities, "entities.csv")
+ >>> exporter.export_knowledge_graph(kg, "kg_base")
+
+Author: Semantica Contributors
+License: MIT
"""
from typing import Any, Dict, List, Optional, Union
@@ -19,66 +37,129 @@ class CSVExporter:
"""
CSV exporter for knowledge graphs and structured data.
- • CSV export functionality
- • Tabular data serialization
- • Metadata and schema export
- • Performance optimization
- • Error handling and recovery
- • Advanced CSV features
+ This class provides comprehensive CSV export functionality for entities,
+ relationships, and knowledge graphs. Supports configurable delimiters,
+ encoding, and custom field names.
+
+ Features:
+ - Entity and relationship export
+ - Knowledge graph export to multiple CSV files
+ - Configurable delimiters and encoding
+ - Metadata serialization as JSON strings
+ - Custom field name support
+ - Header row inclusion control
+
+ Example Usage:
+ >>> exporter = CSVExporter(
+ ... delimiter=",",
+ ... encoding="utf-8",
+ ... include_header=True
+ ... )
+ >>> exporter.export_entities(entities, "entities.csv")
+ >>> exporter.export_knowledge_graph(kg, "output_base")
"""
- def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ def __init__(
+ self,
+ delimiter: str = ",",
+ encoding: str = "utf-8",
+ include_header: bool = True,
+ config: Optional[Dict[str, Any]] = None,
+ **kwargs
+ ):
"""
Initialize CSV exporter.
+ Sets up the exporter with specified CSV formatting options.
+
Args:
- config: Configuration dictionary
- **kwargs: Additional configuration options:
- - delimiter: CSV delimiter (default: ',')
- - encoding: File encoding (default: 'utf-8')
- - include_header: Include header row (default: True)
+ delimiter: CSV field delimiter (default: ',')
+ encoding: File encoding for output (default: 'utf-8')
+ include_header: Whether to include header row in CSV (default: True)
+ config: Optional configuration dictionary (merged with kwargs)
+ **kwargs: Additional configuration options
"""
self.logger = get_logger("csv_exporter")
self.config = config or {}
self.config.update(kwargs)
- self.delimiter = self.config.get("delimiter", ",")
- self.encoding = self.config.get("encoding", "utf-8")
- self.include_header = self.config.get("include_header", True)
+ # CSV configuration
+ self.delimiter = delimiter
+ self.encoding = encoding
+ self.include_header = include_header
+
+ self.logger.debug(
+ f"CSV exporter initialized: delimiter='{delimiter}', "
+ f"encoding={encoding}, include_header={include_header}"
+ )
def export(
self,
data: Union[List[Dict[str, Any]], Dict[str, Any]],
file_path: Union[str, Path],
+ fieldnames: Optional[List[str]] = None,
+ mode: str = "w",
**options
) -> None:
"""
- Export data to CSV file.
+ Export data to CSV file(s).
+
+ This method handles both single CSV file export (from list) and multiple
+ CSV file export (from dictionary with multiple keys).
Args:
- data: Data to export (list of dicts or dict with keys as separate files)
- file_path: Output file path
- **options: Additional options:
- - fieldnames: Custom field names
- - mode: Write mode ('w' or 'a')
+ data: Data to export:
+ - List of dicts: Exports to single CSV file
+ - Dict with list values: Exports each key as separate CSV file
+ file_path: Output file path (base path for dict exports)
+ fieldnames: Custom field names for CSV columns (default: auto-detect)
+ mode: Write mode - 'w' (write) or 'a' (append) (default: 'w')
+ **options: Additional options passed to _write_csv()
+
+ Raises:
+ ValidationError: If data type is unsupported
+
+ Example:
+ >>> # Single CSV file
+ >>> exporter.export([{"id": 1, "name": "A"}], "data.csv")
+ >>> # Multiple CSV files
+ >>> exporter.export(
+ ... {"entities": [...], "relationships": [...]},
+ ... "output_base"
+ ... )
"""
file_path = Path(file_path)
ensure_directory(file_path.parent)
+ self.logger.debug(f"Exporting data to CSV: {file_path}")
+
# Handle different data structures
if isinstance(data, dict):
# Export each key as separate CSV file
+ exported_files = []
for key, value in data.items():
if isinstance(value, list):
output_path = file_path.parent / f"{file_path.stem}_{key}.csv"
- self._write_csv(value, output_path, **options)
+ self._write_csv(value, output_path, fieldnames=fieldnames, mode=mode, **options)
+ exported_files.append(output_path)
+ else:
+ self.logger.warning(
+ f"Skipping key '{key}': value is not a list (type: {type(value)})"
+ )
+
+ self.logger.info(
+ f"Exported {len(exported_files)} CSV file(s) from dictionary: "
+ f"{', '.join(str(f) for f in exported_files)}"
+ )
elif isinstance(data, list):
# Single CSV file
- self._write_csv(data, file_path, **options)
+ self._write_csv(data, file_path, fieldnames=fieldnames, mode=mode, **options)
+ self.logger.info(f"Exported CSV to: {file_path}")
else:
- raise ValidationError(f"Unsupported data type: {type(data)}")
-
- self.logger.info(f"Exported CSV to: {file_path}")
+ raise ValidationError(
+ f"Unsupported data type: {type(data)}. "
+ "Expected list of dicts or dict with list values."
+ )
def export_entities(
self,
@@ -87,35 +168,79 @@ class CSVExporter:
**options
) -> None:
"""
- Export entities to CSV.
+ Export entities to CSV file.
+
+ This method normalizes entity data to a consistent format and exports
+ to CSV. Handles various entity field name variations and serializes
+ metadata as JSON strings.
+
+ Normalized Fields:
+ - id: Entity identifier
+ - text: Entity text/label/name
+ - type: Entity type
+ - confidence: Confidence score
+ - start: Start offset/position
+ - end: End offset/position
+ - metadata: Metadata as JSON string (if present)
Args:
- entities: List of entity dictionaries
- file_path: Output file path
- **options: Additional options
+ entities: List of entity dictionaries with various field names
+ file_path: Output CSV file path
+ **options: Additional options passed to _write_csv()
+
+ Raises:
+ ValidationError: If entities list is empty
+
+ Example:
+ >>> entities = [
+ ... {"id": "e1", "text": "Entity 1", "type": "PERSON"},
+ ... {"id": "e2", "label": "Entity 2", "entity_type": "ORG"}
+ ... ]
+ >>> exporter.export_entities(entities, "entities.csv")
"""
if not entities:
- raise ValidationError("No entities to export")
+ raise ValidationError("No entities to export. Entities list is empty.")
- # Normalize entity data
+ self.logger.debug(f"Exporting {len(entities)} entity(ies) to CSV")
+
+ # Normalize entity data to consistent format
normalized_entities = []
- for entity in entities:
+ for i, entity in enumerate(entities):
+ if not isinstance(entity, dict):
+ self.logger.warning(f"Entity {i} is not a dictionary, skipping")
+ continue
+
normalized = {
"id": entity.get("id") or entity.get("entity_id", ""),
- "text": entity.get("text") or entity.get("label") or entity.get("name", ""),
+ "text": (
+ entity.get("text") or
+ entity.get("label") or
+ entity.get("name") or
+ ""
+ ),
"type": entity.get("type") or entity.get("entity_type", ""),
"confidence": entity.get("confidence", ""),
"start": entity.get("start") or entity.get("start_offset", ""),
"end": entity.get("end") or entity.get("end_offset", ""),
}
- # Add metadata as JSON string
+ # Add metadata as JSON string if present
if "metadata" in entity:
import json
- normalized["metadata"] = json.dumps(entity["metadata"])
+ try:
+ normalized["metadata"] = json.dumps(entity["metadata"])
+ except (TypeError, ValueError) as e:
+ self.logger.warning(
+ f"Failed to serialize metadata for entity {i}: {e}. "
+ "Skipping metadata."
+ )
normalized_entities.append(normalized)
+ self.logger.debug(
+ f"Normalized {len(normalized_entities)} entity(ies) for CSV export"
+ )
+
self._write_csv(normalized_entities, file_path, **options)
def export_relationships(
@@ -125,19 +250,47 @@ class CSVExporter:
**options
) -> None:
"""
- Export relationships to CSV.
+ Export relationships to CSV file.
+
+ This method normalizes relationship data to a consistent format and exports
+ to CSV. Handles various relationship field name variations and serializes
+ metadata as JSON strings.
+
+ Normalized Fields:
+ - id: Relationship identifier
+ - source_id: Source entity identifier
+ - target_id: Target entity identifier
+ - type: Relationship type
+ - confidence: Confidence score
+ - metadata: Metadata as JSON string (if present)
Args:
- relationships: List of relationship dictionaries
- file_path: Output file path
- **options: Additional options
+ relationships: List of relationship dictionaries with various field names
+ file_path: Output CSV file path
+ **options: Additional options passed to _write_csv()
+
+ Raises:
+ ValidationError: If relationships list is empty
+
+ Example:
+ >>> relationships = [
+ ... {"id": "r1", "source_id": "e1", "target_id": "e2", "type": "RELATED_TO"},
+ ... {"source": "e2", "target": "e3", "relationship_type": "CONTAINS"}
+ ... ]
+ >>> exporter.export_relationships(relationships, "relationships.csv")
"""
if not relationships:
- raise ValidationError("No relationships to export")
+ raise ValidationError("No relationships to export. Relationships list is empty.")
+
+ self.logger.debug(f"Exporting {len(relationships)} relationship(s) to CSV")
- # Normalize relationship data
+ # Normalize relationship data to consistent format
normalized_rels = []
- for rel in relationships:
+ for i, rel in enumerate(relationships):
+ if not isinstance(rel, dict):
+ self.logger.warning(f"Relationship {i} is not a dictionary, skipping")
+ continue
+
normalized = {
"id": rel.get("id", ""),
"source_id": rel.get("source_id") or rel.get("source", ""),
@@ -146,13 +299,23 @@ class CSVExporter:
"confidence": rel.get("confidence", ""),
}
- # Add metadata as JSON string
+ # Add metadata as JSON string if present
if "metadata" in rel:
import json
- normalized["metadata"] = json.dumps(rel["metadata"])
+ try:
+ normalized["metadata"] = json.dumps(rel["metadata"])
+ except (TypeError, ValueError) as e:
+ self.logger.warning(
+ f"Failed to serialize metadata for relationship {i}: {e}. "
+ "Skipping metadata."
+ )
normalized_rels.append(normalized)
+ self.logger.debug(
+ f"Normalized {len(normalized_rels)} relationship(s) for CSV export"
+ )
+
self._write_csv(normalized_rels, file_path, **options)
def export_knowledge_graph(
@@ -162,58 +325,131 @@ class CSVExporter:
**options
) -> None:
"""
- Export knowledge graph to CSV files.
+ Export knowledge graph to multiple CSV files.
+
+ This method exports a knowledge graph to separate CSV files for entities,
+ relationships, nodes, and edges. Each component is exported to its own
+ file with a naming pattern: `{base_path}_entities.csv`, etc.
+
+ Exported Files:
+ - {base_path}_entities.csv: Entity data
+ - {base_path}_relationships.csv: Relationship data
+ - {base_path}_nodes.csv: Node data (if present)
+ - {base_path}_edges.csv: Edge data (if present)
Args:
- knowledge_graph: Knowledge graph dictionary
- base_path: Base path for output files
- **options: Additional options
+ knowledge_graph: Knowledge graph dictionary containing:
+ - entities: List of entity dictionaries
+ - relationships: List of relationship dictionaries
+ - nodes: List of node dictionaries (optional)
+ - edges: List of edge dictionaries (optional)
+ base_path: Base path for output files (without extension)
+ **options: Additional options passed to export methods
+
+ Example:
+ >>> kg = {
+ ... "entities": [...],
+ ... "relationships": [...],
+ ... "nodes": [...],
+ ... "edges": [...]
+ ... }
+ >>> exporter.export_knowledge_graph(kg, "output_base")
+ >>> # Creates: output_base_entities.csv, output_base_relationships.csv, etc.
"""
base_path = Path(base_path)
+ self.logger.debug(f"Exporting knowledge graph to CSV files: base_path={base_path}")
+
+ exported_files = []
+
# Export entities
entities = knowledge_graph.get("entities", [])
if entities:
entities_path = base_path.parent / f"{base_path.stem}_entities.csv"
self.export_entities(entities, entities_path, **options)
+ exported_files.append(entities_path)
+ self.logger.debug(f"Exported {len(entities)} entity(ies) to {entities_path}")
+ else:
+ self.logger.debug("No entities found in knowledge graph")
# Export relationships
relationships = knowledge_graph.get("relationships", [])
if relationships:
rels_path = base_path.parent / f"{base_path.stem}_relationships.csv"
self.export_relationships(relationships, rels_path, **options)
+ exported_files.append(rels_path)
+ self.logger.debug(f"Exported {len(relationships)} relationship(s) to {rels_path}")
+ else:
+ self.logger.debug("No relationships found in knowledge graph")
# Export nodes if available
nodes = knowledge_graph.get("nodes", [])
if nodes:
nodes_path = base_path.parent / f"{base_path.stem}_nodes.csv"
self._write_csv(nodes, nodes_path, **options)
+ exported_files.append(nodes_path)
+ self.logger.debug(f"Exported {len(nodes)} node(s) to {nodes_path}")
# Export edges if available
edges = knowledge_graph.get("edges", [])
if edges:
edges_path = base_path.parent / f"{base_path.stem}_edges.csv"
self._write_csv(edges, edges_path, **options)
+ exported_files.append(edges_path)
+ self.logger.debug(f"Exported {len(edges)} edge(s) to {edges_path}")
+
+ if exported_files:
+ self.logger.info(
+ f"Exported knowledge graph to {len(exported_files)} CSV file(s): "
+ f"{', '.join(str(f) for f in exported_files)}"
+ )
+ else:
+ self.logger.warning("No data found in knowledge graph to export")
def _write_csv(
self,
data: List[Dict[str, Any]],
file_path: Path,
+ fieldnames: Optional[List[str]] = None,
+ mode: str = "w",
**options
) -> None:
- """Write data to CSV file."""
+ """
+ Write data to CSV file.
+
+ This internal method handles the actual CSV file writing, including
+ field name detection, header writing, and value conversion.
+
+ Args:
+ data: List of dictionaries to write as CSV rows
+ file_path: Output CSV file path
+ fieldnames: Custom field names (default: auto-detect from data)
+ mode: Write mode - 'w' (write) or 'a' (append) (default: 'w')
+ **options: Unused (for compatibility)
+
+ Raises:
+ ValidationError: If data list is empty
+ ProcessingError: If file writing fails
+ """
if not data:
- raise ValidationError("No data to write")
+ raise ValidationError("No data to write. Data list is empty.")
- fieldnames = options.get("fieldnames")
+ # Determine field names
if not fieldnames:
- # Get all unique keys from data
- fieldnames = set()
+ # Auto-detect: get all unique keys from data
+ fieldnames_set = set()
for item in data:
- fieldnames.update(item.keys())
- fieldnames = sorted(list(fieldnames))
+ if isinstance(item, dict):
+ fieldnames_set.update(item.keys())
+ fieldnames = sorted(list(fieldnames_set))
- mode = options.get("mode", "w")
+ if not fieldnames:
+ raise ValidationError("No field names found in data")
+
+ self.logger.debug(
+ f"Writing CSV: {len(data)} row(s), {len(fieldnames)} column(s), "
+ f"mode={mode}, file={file_path}"
+ )
try:
with open(file_path, mode, newline='', encoding=self.encoding) as f:
@@ -221,14 +457,20 @@ class CSVExporter:
f,
fieldnames=fieldnames,
delimiter=self.delimiter,
- extrasaction='ignore'
+ extrasaction='ignore' # Ignore extra fields not in fieldnames
)
+ # Write header if requested and in write mode
if self.include_header and mode == 'w':
writer.writeheader()
- for row in data:
- # Convert values to strings
+ # Write data rows
+ for i, row in enumerate(data):
+ if not isinstance(row, dict):
+ self.logger.warning(f"Row {i} is not a dictionary, skipping")
+ continue
+
+ # Convert values to strings (CSV requires string values)
row_str = {
k: str(v) if v is not None else ""
for k, v in row.items()
@@ -236,5 +478,13 @@ class CSVExporter:
}
writer.writerow(row_str)
+ except IOError as e:
+ error_msg = f"Failed to write CSV file {file_path}: {e}"
+ self.logger.error(error_msg)
+ raise ProcessingError(error_msg) from e
except Exception as e:
- raise ProcessingError(f"Failed to write CSV file: {e}") from e
+ error_msg = f"Unexpected error writing CSV file: {e}"
+ self.logger.error(error_msg)
+ raise ProcessingError(error_msg) from e
+
+ self.logger.debug(f"Successfully wrote CSV file: {file_path}")
diff --git a/semantica/export/graph_exporter.py b/semantica/export/graph_exporter.py
index b767241c..252dae4b 100644
--- a/semantica/export/graph_exporter.py
+++ b/semantica/export/graph_exporter.py
@@ -1,8 +1,25 @@
"""
-Graph exporter for Semantica framework.
+Graph Exporter Module
-This module provides graph format export capabilities
-for knowledge graphs and network data.
+This module provides comprehensive graph format export capabilities for the
+Semantica framework, enabling knowledge graph export to various graph formats
+for visualization and analysis tools.
+
+Key Features:
+ - Multiple graph format support (GraphML, GEXF, DOT, JSON)
+ - Knowledge graph to graph format conversion
+ - Node and edge attribute support
+ - Graph visualization export
+ - Configurable attribute inclusion
+
+Example Usage:
+ >>> from semantica.export import GraphExporter
+ >>> exporter = GraphExporter(format="graphml", include_attributes=True)
+ >>> exporter.export_knowledge_graph(kg, "graph.graphml")
+ >>> exporter.export(graph_data, "graph.gexf", format="gexf")
+
+Author: Semantica Contributors
+License: MIT
"""
from typing import Any, Dict, List, Optional, Union
@@ -18,30 +35,57 @@ class GraphExporter:
"""
Graph exporter for knowledge graphs and network data.
- • Graph format export functionality
- • Network data serialization
- • Graph visualization export
- • Performance optimization
- • Error handling and recovery
- • Advanced graph features
+ This class provides comprehensive graph format export functionality for
+ knowledge graphs, supporting multiple graph formats for visualization
+ and analysis tools.
+
+ Features:
+ - Multiple graph format support (GraphML, GEXF, DOT, JSON)
+ - Knowledge graph to graph format conversion
+ - Node and edge attribute support
+ - Graph visualization export
+ - Configurable attribute inclusion
+
+ Example Usage:
+ >>> exporter = GraphExporter(
+ ... format="graphml",
+ ... include_attributes=True
+ ... )
+ >>> exporter.export_knowledge_graph(kg, "graph.graphml")
"""
- def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ def __init__(
+ self,
+ format: str = "json",
+ include_attributes: bool = True,
+ config: Optional[Dict[str, Any]] = None,
+ **kwargs
+ ):
"""
Initialize graph exporter.
+ Sets up the exporter with specified graph format and attribute options.
+
Args:
- config: Configuration dictionary
- **kwargs: Additional configuration options:
- - format: Export format ('graphml', 'gexf', 'json', 'dot')
- - include_attributes: Include node/edge attributes (default: True)
+ format: Default export format - 'graphml', 'gexf', 'json', or 'dot'
+ (default: 'json')
+ include_attributes: Whether to include node/edge attributes in export
+ (default: True)
+ config: Optional configuration dictionary (merged with kwargs)
+ **kwargs: Additional configuration options
"""
self.logger = get_logger("graph_exporter")
self.config = config or {}
self.config.update(kwargs)
- self.format = self.config.get("format", "json")
- self.include_attributes = self.config.get("include_attributes", True)
+ # Graph export configuration
+ self.format = format
+ self.include_attributes = include_attributes
+
+ self.logger.debug(
+ f"Graph exporter initialized: format={format}, "
+ f"include_attributes={include_attributes}"
+ )
def export(
self,
@@ -51,19 +95,49 @@ class GraphExporter:
**options
) -> None:
"""
- Export graph to file.
+ Export graph data to file in specified format.
+
+ This method exports graph data (nodes and edges) to various graph formats
+ supported by visualization and analysis tools.
+
+ Supported Formats:
+ - "json": JSON format (default)
+ - "graphml": GraphML format (XML-based, for Cytoscape, yEd, etc.)
+ - "gexf": GEXF format (for Gephi)
+ - "dot": DOT format (for Graphviz)
Args:
- graph_data: Graph data dictionary
+ graph_data: Graph data dictionary containing:
+ - nodes: List of node dictionaries with id, label, type, attributes
+ - edges: List of edge dictionaries with source, target, type, attributes
+ - metadata: Metadata dictionary (optional)
file_path: Output file path
- format: Export format ('graphml', 'gexf', 'json', 'dot')
- **options: Additional options
+ format: Export format - 'graphml', 'gexf', 'json', or 'dot'
+ (default: self.format)
+ **options: Additional format-specific options
+
+ Raises:
+ ValidationError: If format is unsupported
+
+ Example:
+ >>> graph_data = {
+ ... "nodes": [{"id": "n1", "label": "Node 1"}],
+ ... "edges": [{"source": "n1", "target": "n2", "type": "RELATED"}]
+ ... }
+ >>> exporter.export(graph_data, "graph.graphml", format="graphml")
"""
file_path = Path(file_path)
ensure_directory(file_path.parent)
export_format = format or self.format
+ self.logger.debug(
+ f"Exporting graph to {export_format}: {file_path}, "
+ f"nodes={len(graph_data.get('nodes', []))}, "
+ f"edges={len(graph_data.get('edges', []))}"
+ )
+
+ # Export based on format
if export_format == "json":
self._export_json(graph_data, file_path, **options)
elif export_format == "graphml":
@@ -73,7 +147,10 @@ class GraphExporter:
elif export_format == "dot":
self._export_dot(graph_data, file_path, **options)
else:
- raise ValidationError(f"Unsupported graph format: {export_format}")
+ raise ValidationError(
+ f"Unsupported graph format: {export_format}. "
+ f"Supported formats: json, graphml, gexf, dot"
+ )
self.logger.info(f"Exported graph ({export_format}) to: {file_path}")
@@ -98,7 +175,25 @@ class GraphExporter:
self.export(graph_data, file_path, format=format, **options)
def _convert_kg_to_graph(self, kg: Dict[str, Any]) -> Dict[str, Any]:
- """Convert knowledge graph to graph format."""
+ """
+ Convert knowledge graph to graph format.
+
+ This method converts a knowledge graph (entities and relationships) to
+ a graph structure (nodes and edges) suitable for graph format export.
+
+ Conversion:
+ - Entities -> Nodes (with id, label, type, attributes)
+ - Relationships -> Edges (with source, target, type, attributes)
+
+ Args:
+ kg: Knowledge graph dictionary containing:
+ - entities: List of entity dictionaries
+ - relationships: List of relationship dictionaries
+ - metadata: Metadata dictionary (optional)
+
+ Returns:
+ Dictionary with nodes, edges, and metadata in graph format
+ """
nodes = []
edges = []
@@ -107,10 +202,16 @@ class GraphExporter:
for entity in entities:
node = {
"id": entity.get("id") or entity.get("entity_id"),
- "label": entity.get("text") or entity.get("label") or entity.get("name", ""),
+ "label": (
+ entity.get("text") or
+ entity.get("label") or
+ entity.get("name") or
+ ""
+ ),
"type": entity.get("type") or entity.get("entity_type", "entity")
}
+ # Add attributes if requested
if self.include_attributes:
node["attributes"] = {
"confidence": entity.get("confidence", 1.0),
@@ -128,6 +229,7 @@ class GraphExporter:
"type": rel.get("type") or rel.get("relationship_type", "related_to")
}
+ # Add attributes if requested
if self.include_attributes:
edge["attributes"] = {
"confidence": rel.get("confidence", 1.0),
@@ -136,20 +238,53 @@ class GraphExporter:
edges.append(edge)
+ self.logger.debug(
+ f"Converted knowledge graph: {len(nodes)} node(s), {len(edges)} edge(s)"
+ )
+
return {
"nodes": nodes,
"edges": edges,
"metadata": kg.get("metadata", {})
}
- def _export_json(self, graph_data: Dict[str, Any], file_path: Path, **options) -> None:
- """Export to JSON format."""
+ def _export_json(
+ self,
+ graph_data: Dict[str, Any],
+ file_path: Path,
+ **options
+ ) -> None:
+ """
+ Export graph to JSON format.
+
+ This method exports graph data to JSON format using the helper function.
+
+ Args:
+ graph_data: Graph data dictionary with nodes and edges
+ file_path: Output JSON file path
+ **options: Additional options (unused)
+ """
from ..utils.helpers import write_json_file
write_json_file(graph_data, file_path, indent=2)
- def _export_graphml(self, graph_data: Dict[str, Any], file_path: Path, **options) -> None:
- """Export to GraphML format."""
+ def _export_graphml(
+ self,
+ graph_data: Dict[str, Any],
+ file_path: Path,
+ **options
+ ) -> None:
+ """
+ Export graph to GraphML format.
+
+ GraphML is an XML-based format for graph data, widely supported by
+ graph visualization tools like Cytoscape, yEd, and Gephi.
+
+ Args:
+ graph_data: Graph data dictionary with nodes and edges
+ file_path: Output GraphML file path
+ **options: Additional options (unused)
+ """
lines = ['<?xml version="1.0" encoding="UTF-8"?>']
lines.append('<graphml xmlns="http://graphml.graphdrawing.org/xmlns"')
lines.append(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
@@ -157,16 +292,16 @@ class GraphExporter:
lines.append(' http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">')
lines.append("")
- # Define attributes
+ # Define attribute keys
lines.append(' <key id="type" for="node" attr.name="type" attr.type="string"/>')
lines.append(' <key id="confidence" for="node" attr.name="confidence" attr.type="double"/>')
lines.append("")
- # Graph
+ # Graph declaration (directed graph)
lines.append(' <graph id="G" edgedefault="directed">')
lines.append("")
- # Nodes
+ # Export nodes
nodes = graph_data.get("nodes", [])
for node in nodes:
node_id = node.get("id", "")
@@ -177,6 +312,7 @@ class GraphExporter:
lines.append(f' <data key="label">{label}</data>')
lines.append(f' <data key="type">{node_type}</data>')
+ # Add attributes if requested
if self.include_attributes and "attributes" in node:
attrs = node["attributes"]
if "confidence" in attrs:
@@ -186,7 +322,7 @@ class GraphExporter:
lines.append("")
- # Edges
+ # Export edges
edges = graph_data.get("edges", [])
for edge in edges:
source = edge.get("source", "")
@@ -196,6 +332,7 @@ class GraphExporter:
lines.append(f' <edge source="{source}" target="{target}">')
lines.append(f' <data key="label">{edge_type}</data>')
+ # Add attributes if requested
if self.include_attributes and "attributes" in edge:
attrs = edge["attributes"]
if "confidence" in attrs:
@@ -206,17 +343,37 @@ class GraphExporter:
lines.append(" </graph>")
lines.append("</graphml>")
+ # Write GraphML file
with open(file_path, "w", encoding="utf-8") as f:
f.write("\n".join(lines))
+
+ self.logger.debug(
+ f"Exported GraphML: {len(nodes)} node(s), {len(edges)} edge(s)"
+ )
- def _export_gexf(self, graph_data: Dict[str, Any], file_path: Path, **options) -> None:
- """Export to GEXF format."""
+ def _export_gexf(
+ self,
+ graph_data: Dict[str, Any],
+ file_path: Path,
+ **options
+ ) -> None:
+ """
+ Export graph to GEXF format.
+
+ GEXF (Graph Exchange XML Format) is an XML-based format primarily used
+ by Gephi for graph visualization and analysis.
+
+ Args:
+ graph_data: Graph data dictionary with nodes and edges
+ file_path: Output GEXF file path
+ **options: Additional options (unused)
+ """
lines = ['<?xml version="1.0" encoding="UTF-8"?>']
lines.append('<gexf xmlns="http://www.gexf.net/1.2draft" version="1.2">')
lines.append(' <graph mode="static" defaultedgetype="directed">')
lines.append(" <nodes>")
- # Nodes
+ # Export nodes
nodes = graph_data.get("nodes", [])
for node in nodes:
node_id = node.get("id", "")
@@ -224,6 +381,7 @@ class GraphExporter:
lines.append(f' <node id="{node_id}" label="{label}">')
+ # Add attributes if requested
if self.include_attributes and "attributes" in node:
lines.append(" <attvalues>")
attrs = node["attributes"]
@@ -236,15 +394,18 @@ class GraphExporter:
lines.append(" </nodes>")
lines.append(" <edges>")
- # Edges
+ # Export edges
edges = graph_data.get("edges", [])
for i, edge in enumerate(edges):
source = edge.get("source", "")
target = edge.get("target", "")
edge_type = edge.get("type", "")
- lines.append(f' <edge id="{i}" source="{source}" target="{target}" label="{edge_type}">')
+ lines.append(
+ f' <edge id="{i}" source="{source}" target="{target}" label="{edge_type}">'
+ )
+ # Add attributes if requested
if self.include_attributes and "attributes" in edge:
lines.append(" <attvalues>")
attrs = edge["attributes"]
@@ -258,22 +419,44 @@ class GraphExporter:
lines.append(" </graph>")
lines.append("</gexf>")
+ # Write GEXF file
with open(file_path, "w", encoding="utf-8") as f:
f.write("\n".join(lines))
+
+ self.logger.debug(
+ f"Exported GEXF: {len(nodes)} node(s), {len(edges)} edge(s)"
+ )
- def _export_dot(self, graph_data: Dict[str, Any], file_path: Path, **options) -> None:
- """Export to DOT format (Graphviz)."""
- lines = ["digraph G {"]
- lines.append(" rankdir=LR;")
+ def _export_dot(
+ self,
+ graph_data: Dict[str, Any],
+ file_path: Path,
+ **options
+ ) -> None:
+ """
+ Export graph to DOT format (Graphviz).
+
+ DOT is a graph description language used by Graphviz for graph
+ visualization. This format is human-readable and widely supported.
+
+ Args:
+ graph_data: Graph data dictionary with nodes and edges
+ file_path: Output DOT file path
+ **options: Additional options (unused)
+ """
+ lines = ["digraph G {"] # Directed graph
+ lines.append(" rankdir=LR;") # Left-to-right layout
lines.append("")
- # Nodes
+ # Export nodes
nodes = graph_data.get("nodes", [])
for node in nodes:
+ # Escape quotes in IDs and labels
node_id = node.get("id", "").replace('"', '\\"')
label = node.get("label", "").replace('"', '\\"')
node_type = node.get("type", "")
+ # Build node attributes
attributes = [f'label="{label}"']
if node_type:
attributes.append(f'type="{node_type}"')
@@ -283,18 +466,25 @@ class GraphExporter:
lines.append("")
- # Edges
+ # Export edges
edges = graph_data.get("edges", [])
for edge in edges:
+ # Escape quotes in source, target, and type
source = edge.get("source", "").replace('"', '\\"')
target = edge.get("target", "").replace('"', '\\"')
edge_type = edge.get("type", "").replace('"', '\\"')
+ # Build edge attributes
attributes = [f'label="{edge_type}"']
attrs_str = ", ".join(attributes)
lines.append(f' "{source}" -> "{target}" [{attrs_str}];')
lines.append("}")
+ # Write DOT file
with open(file_path, "w", encoding="utf-8") as f:
f.write("\n".join(lines))
+
+ self.logger.debug(
+ f"Exported DOT: {len(nodes)} node(s), {len(edges)} edge(s)"
+ )
diff --git a/semantica/export/json_exporter.py b/semantica/export/json_exporter.py
index a8041b9e..eeddae9d 100644
--- a/semantica/export/json_exporter.py
+++ b/semantica/export/json_exporter.py
@@ -1,8 +1,26 @@
"""
-JSON exporter for Semantica framework.
+JSON Exporter Module
-This module provides JSON and JSON-LD export capabilities
-for knowledge graphs and semantic data.
+This module provides comprehensive JSON and JSON-LD export capabilities for the
+Semantica framework, enabling structured data export for knowledge graphs and
+semantic information.
+
+Key Features:
+ - JSON and JSON-LD format export
+ - Knowledge graph serialization
+ - Entity and relationship export
+ - Metadata and provenance tracking
+ - Configurable indentation and encoding
+ - JSON-LD context management
+
+Example Usage:
+ >>> from semantica.export import JSONExporter
+ >>> exporter = JSONExporter(indent=2, format="json-ld")
+ >>> exporter.export_knowledge_graph(kg, "output.json")
+ >>> exporter.export_entities(entities, "entities.json")
+
+Author: Semantica Contributors
+License: MIT
"""
from typing import Any, Dict, List, Optional, Union
@@ -19,61 +37,118 @@ class JSONExporter:
"""
JSON exporter for knowledge graphs and semantic data.
- • JSON and JSON-LD export functionality
- • Knowledge graph serialization
- • Metadata and provenance export
- • Performance optimization
- • Error handling and recovery
- • Advanced JSON features
+ This class provides comprehensive JSON and JSON-LD export functionality for
+ entities, relationships, and knowledge graphs. Supports both standard JSON
+ and JSON-LD formats with configurable formatting.
+
+ Features:
+ - JSON and JSON-LD format export
+ - Knowledge graph serialization
+ - Entity and relationship export
+ - Metadata and provenance tracking
+ - Configurable indentation and encoding
+ - JSON-LD context management
+
+ Example Usage:
+ >>> exporter = JSONExporter(
+ ... indent=2,
+ ... ensure_ascii=False,
+ ... format="json-ld"
+ ... )
+ >>> exporter.export_knowledge_graph(kg, "output.json")
"""
- def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ def __init__(
+ self,
+ indent: int = 2,
+ ensure_ascii: bool = False,
+ format: str = "json",
+ config: Optional[Dict[str, Any]] = None,
+ **kwargs
+ ):
"""
Initialize JSON exporter.
+ Sets up the exporter with specified JSON formatting options.
+
Args:
- config: Configuration dictionary
- **kwargs: Additional configuration options:
- - indent: JSON indentation (default: 2)
- - ensure_ascii: Ensure ASCII encoding (default: False)
- - format: Export format ('json', 'json-ld')
+ indent: JSON indentation level (default: 2)
+ ensure_ascii: Whether to escape non-ASCII characters (default: False)
+ format: Export format - 'json' or 'json-ld' (default: 'json')
+ config: Optional configuration dictionary (merged with kwargs)
+ **kwargs: Additional configuration options
"""
self.logger = get_logger("json_exporter")
self.config = config or {}
self.config.update(kwargs)
- self.indent = self.config.get("indent", 2)
- self.ensure_ascii = self.config.get("ensure_ascii", False)
- self.format = self.config.get("format", "json")
+ # JSON configuration
+ self.indent = indent
+ self.ensure_ascii = ensure_ascii
+ self.format = format
+
+ self.logger.debug(
+ f"JSON exporter initialized: indent={indent}, "
+ f"ensure_ascii={ensure_ascii}, format={format}"
+ )
def export(
self,
data: Any,
file_path: Union[str, Path],
format: Optional[str] = None,
+ include_metadata: bool = True,
+ include_provenance: bool = True,
**options
) -> None:
"""
Export data to JSON file.
+ This method exports data to JSON or JSON-LD format, with optional
+ metadata and provenance information.
+
Args:
- data: Data to export
- file_path: Output file path
- format: Export format ('json', 'json-ld')
- **options: Additional options:
- - include_metadata: Include metadata (default: True)
- - include_provenance: Include provenance (default: True)
+ data: Data to export (dict, list, or any JSON-serializable value)
+ file_path: Output JSON file path
+ format: Export format - 'json' or 'json-ld' (default: self.format)
+ include_metadata: Whether to include metadata in export (default: True)
+ include_provenance: Whether to include provenance information (default: True)
+ **options: Additional options passed to conversion methods
+
+ Example:
+ >>> exporter.export(
+ ... {"entities": [...], "relationships": [...]},
+ ... "output.json",
+ ... format="json-ld"
+ ... )
"""
file_path = Path(file_path)
ensure_directory(file_path.parent)
export_format = format or self.format
+ self.logger.debug(
+ f"Exporting data to JSON ({export_format}): {file_path}, "
+ f"include_metadata={include_metadata}, include_provenance={include_provenance}"
+ )
+
+ # Convert data to appropriate format
if export_format == "json-ld":
- json_data = self._convert_to_jsonld(data, **options)
+ json_data = self._convert_to_jsonld(
+ data,
+ include_metadata=include_metadata,
+ include_provenance=include_provenance,
+ **options
+ )
else:
- json_data = self._convert_to_json(data, **options)
+ json_data = self._convert_to_json(
+ data,
+ include_metadata=include_metadata,
+ include_provenance=include_provenance,
+ **options
+ )
+ # Write JSON file
write_json_file(
json_data,
file_path,
@@ -81,7 +156,7 @@ class JSONExporter:
ensure_ascii=self.ensure_ascii
)
- self.logger.info(f"Exported JSON to: {file_path}")
+ self.logger.info(f"Exported JSON ({export_format}) to: {file_path}")
def export_knowledge_graph(
self,
@@ -91,21 +166,44 @@ class JSONExporter:
**options
) -> None:
"""
- Export knowledge graph to JSON/JSON-LD.
+ Export knowledge graph to JSON or JSON-LD format.
+
+ This method exports a complete knowledge graph with entities, relationships,
+ nodes, edges, and metadata to JSON or JSON-LD format.
Args:
- knowledge_graph: Knowledge graph dictionary
- file_path: Output file path
- format: Export format ('json', 'json-ld')
- **options: Additional options
+ knowledge_graph: Knowledge graph dictionary containing:
+ - entities: List of entity dictionaries
+ - relationships: List of relationship dictionaries
+ - nodes: List of node dictionaries (optional)
+ - edges: List of edge dictionaries (optional)
+ - metadata: Metadata dictionary (optional)
+ - statistics: Statistics dictionary (optional)
+ file_path: Output JSON file path
+ format: Export format - 'json' or 'json-ld' (default: self.format)
+ **options: Additional options passed to conversion methods
+
+ Example:
+ >>> kg = {
+ ... "entities": [...],
+ ... "relationships": [...],
+ ... "metadata": {...}
+ ... }
+ >>> exporter.export_knowledge_graph(kg, "kg.json", format="json-ld")
"""
export_format = format or self.format
+ self.logger.debug(
+ f"Exporting knowledge graph to {export_format}: {file_path}"
+ )
+
+ # Convert knowledge graph to appropriate format
if export_format == "json-ld":
json_data = self._convert_kg_to_jsonld(knowledge_graph, **options)
else:
json_data = self._convert_kg_to_json(knowledge_graph, **options)
+ # Export using main export method
self.export(json_data, file_path, format=export_format, **options)
def export_entities(
@@ -115,13 +213,30 @@ class JSONExporter:
**options
) -> None:
"""
- Export entities to JSON.
+ Export entities to JSON file.
+
+ This method exports a list of entities to JSON format with JSON-LD context
+ and metadata including export timestamp and entity count.
Args:
- entities: List of entity dictionaries
- file_path: Output file path
- **options: Additional options
+ entities: List of entity dictionaries to export
+ file_path: Output JSON file path
+ **options: Additional options:
+ - metadata: Additional metadata to include in export
+
+ Example:
+ >>> entities = [
+ ... {"id": "e1", "text": "Entity 1", "type": "PERSON"},
+ ... {"id": "e2", "text": "Entity 2", "type": "ORG"}
+ ... ]
+ >>> exporter.export_entities(entities, "entities.json")
"""
+ if not entities:
+ self.logger.warning("No entities provided for export")
+
+ self.logger.debug(f"Exporting {len(entities)} entity(ies) to JSON")
+
+ # Build JSON data with JSON-LD context
json_data = {
"@context": {
"@vocab": "https://semantica.dev/vocab/",
@@ -172,16 +287,39 @@ class JSONExporter:
self.export(json_data, file_path, **options)
- def _convert_to_json(self, data: Any, **options) -> Dict[str, Any]:
- """Convert data to JSON format."""
+ def _convert_to_json(
+ self,
+ data: Any,
+ include_metadata: bool = True,
+ include_provenance: bool = True,
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Convert data to JSON format.
+
+ This method converts various data types to a standardized JSON structure
+ with optional metadata and provenance information.
+
+ Args:
+ data: Data to convert (dict, list, or any value)
+ include_metadata: Whether to include metadata (default: True)
+ include_provenance: Whether to include provenance (default: True)
+ **options: Additional options:
+ - metadata: Additional metadata to include
+
+ Returns:
+ Dictionary in JSON format with data and optional metadata
+ """
if isinstance(data, dict):
result = dict(data)
# Add metadata if requested
- if options.get("include_metadata", True):
+ if include_metadata:
if "metadata" not in result:
result["metadata"] = {}
result["metadata"]["exported_at"] = datetime.now().isoformat()
+ if include_provenance:
+ result["metadata"]["format"] = "json"
return result
elif isinstance(data, list):
@@ -190,14 +328,42 @@ class JSONExporter:
"count": len(data),
"metadata": {
"exported_at": datetime.now().isoformat(),
+ "format": "json" if include_provenance else None,
**options.get("metadata", {})
}
}
else:
- return {"value": data}
+ # Single value
+ return {
+ "value": data,
+ "metadata": {
+ "exported_at": datetime.now().isoformat()
+ } if include_metadata else {}
+ }
- def _convert_to_jsonld(self, data: Any, **options) -> Dict[str, Any]:
- """Convert data to JSON-LD format."""
+ def _convert_to_jsonld(
+ self,
+ data: Any,
+ include_metadata: bool = True,
+ include_provenance: bool = True,
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Convert data to JSON-LD format.
+
+ This method converts various data types to JSON-LD format with proper
+ context, graph structure, and metadata.
+
+ Args:
+ data: Data to convert (dict, list, or any value)
+ include_metadata: Whether to include metadata (default: True)
+ include_provenance: Whether to include provenance (default: True)
+ **options: Additional options passed to knowledge graph conversion
+
+ Returns:
+ Dictionary in JSON-LD format with @context, @graph/@value, and metadata
+ """
+ # Initialize JSON-LD structure with context
jsonld = {
"@context": {
"@vocab": "https://semantica.dev/vocab/",
@@ -205,26 +371,55 @@ class JSONExporter:
}
}
+ # Convert data based on type
if isinstance(data, dict):
if "entities" in data or "relationships" in data:
- # Knowledge graph structure
+ # Knowledge graph structure - use specialized conversion
jsonld.update(self._convert_kg_to_jsonld(data, **options))
else:
- # Generic data
+ # Generic dictionary - wrap in @graph
jsonld["@graph"] = [data]
elif isinstance(data, list):
+ # List - use @graph
jsonld["@graph"] = data
else:
+ # Single value - use @value
jsonld["@value"] = data
- # Add metadata
- jsonld["@id"] = f"https://semantica.dev/data/{datetime.now().isoformat()}"
- jsonld["semantica:exportedAt"] = datetime.now().isoformat()
+ # Add metadata and provenance if requested
+ if include_metadata:
+ jsonld["@id"] = f"https://semantica.dev/data/{datetime.now().isoformat()}"
+ if include_provenance:
+ jsonld["semantica:exportedAt"] = datetime.now().isoformat()
+ jsonld["semantica:format"] = "json-ld"
return jsonld
- def _convert_kg_to_json(self, kg: Dict[str, Any], **options) -> Dict[str, Any]:
- """Convert knowledge graph to JSON."""
+ def _convert_kg_to_json(
+ self,
+ kg: Dict[str, Any],
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Convert knowledge graph to JSON format.
+
+ This method converts a knowledge graph dictionary to a standardized JSON
+ structure with entities, relationships, nodes, edges, metadata, and statistics.
+
+ Args:
+ kg: Knowledge graph dictionary containing:
+ - entities: List of entity dictionaries
+ - relationships: List of relationship dictionaries
+ - nodes: List of node dictionaries (optional)
+ - edges: List of edge dictionaries (optional)
+ - metadata: Metadata dictionary (optional)
+ - statistics: Statistics dictionary (optional)
+ **options: Additional options:
+ - metadata: Additional metadata to merge
+
+ Returns:
+ Dictionary in JSON format with all knowledge graph components
+ """
result = {
"entities": kg.get("entities", []),
"relationships": kg.get("relationships", []),
@@ -243,8 +438,28 @@ class JSONExporter:
return result
- def _convert_kg_to_jsonld(self, kg: Dict[str, Any], **options) -> Dict[str, Any]:
- """Convert knowledge graph to JSON-LD."""
+ def _convert_kg_to_jsonld(
+ self,
+ kg: Dict[str, Any],
+ **options
+ ) -> Dict[str, Any]:
+ """
+ Convert knowledge graph to JSON-LD format.
+
+ This method converts a knowledge graph to JSON-LD format with proper
+ RDF context, entity and relationship conversion, and metadata.
+
+ Args:
+ kg: Knowledge graph dictionary containing:
+ - entities: List of entity dictionaries
+ - relationships: List of relationship dictionaries
+ - metadata: Metadata dictionary (optional)
+ **options: Additional options (unused)
+
+ Returns:
+ Dictionary in JSON-LD format with @context, @id, @type, and graph data
+ """
+ # Initialize JSON-LD structure with RDF context
jsonld = {
"@context": {
"@vocab": "https://semantica.dev/vocab/",
@@ -256,19 +471,21 @@ class JSONExporter:
"@type": "semantica:KnowledgeGraph"
}
- # Convert entities
+ # Convert entities to JSON-LD format
entities = kg.get("entities", [])
if entities:
jsonld["semantica:entities"] = [
self._entity_to_jsonld(e) for e in entities
]
+ self.logger.debug(f"Converted {len(entities)} entity(ies) to JSON-LD")
- # Convert relationships
+ # Convert relationships to JSON-LD format
relationships = kg.get("relationships", [])
if relationships:
jsonld["semantica:relationships"] = [
self._relationship_to_jsonld(r) for r in relationships
]
+ self.logger.debug(f"Converted {len(relationships)} relationship(s) to JSON-LD")
# Add metadata
jsonld["semantica:exportedAt"] = datetime.now().isoformat()
@@ -278,23 +495,70 @@ class JSONExporter:
return jsonld
def _entity_to_jsonld(self, entity: Dict[str, Any]) -> Dict[str, Any]:
- """Convert entity to JSON-LD format."""
+ """
+ Convert entity to JSON-LD format.
+
+ This method converts an entity dictionary to JSON-LD format with proper
+ @id, @type, and semantic properties.
+
+ Args:
+ entity: Entity dictionary with fields:
+ - id: Entity identifier (optional)
+ - text/label: Entity text/label
+ - type: Entity type (optional)
+ - confidence: Confidence score (optional)
+ - metadata: Metadata dictionary (optional)
+
+ Returns:
+ Dictionary in JSON-LD format representing the entity
+ """
+ # Generate @id if not provided
+ entity_id = entity.get("id")
+ if not entity_id:
+ entity_text = entity.get("text") or entity.get("label", "unknown")
+ entity_id = f"semantica:entity/{entity_text}"
+
jsonld = {
- "@id": entity.get("id") or f"semantica:entity/{entity.get('text', 'unknown')}",
+ "@id": entity_id,
"@type": entity.get("type") or "semantica:Entity",
"semantica:text": entity.get("text") or entity.get("label", ""),
"semantica:confidence": entity.get("confidence", 1.0)
}
+ # Add metadata if present
if "metadata" in entity:
jsonld["semantica:metadata"] = entity["metadata"]
return jsonld
def _relationship_to_jsonld(self, rel: Dict[str, Any]) -> Dict[str, Any]:
- """Convert relationship to JSON-LD format."""
+ """
+ Convert relationship to JSON-LD format.
+
+ This method converts a relationship dictionary to JSON-LD format with
+ proper @id, @type, source, target, and semantic properties.
+
+ Args:
+ rel: Relationship dictionary with fields:
+ - id: Relationship identifier (optional)
+ - source_id/source: Source entity identifier
+ - target_id/target: Target entity identifier
+ - type: Relationship type (optional)
+ - confidence: Confidence score (optional)
+ - metadata: Metadata dictionary (optional)
+
+ Returns:
+ Dictionary in JSON-LD format representing the relationship
+ """
+ # Generate @id if not provided
+ rel_id = rel.get("id")
+ if not rel_id:
+ source_id = rel.get("source_id") or rel.get("source", "")
+ target_id = rel.get("target_id") or rel.get("target", "")
+ rel_id = f"semantica:rel/{source_id}_{target_id}"
+
jsonld = {
- "@id": rel.get("id") or f"semantica:rel/{rel.get('source_id')}_{rel.get('target_id')}",
+ "@id": rel_id,
"@type": "semantica:Relationship",
"semantica:type": rel.get("type", "related_to"),
"semantica:source": {
@@ -306,6 +570,7 @@ class JSONExporter:
"semantica:confidence": rel.get("confidence", 1.0)
}
+ # Add metadata if present
if "metadata" in rel:
jsonld["semantica:metadata"] = rel["metadata"]
diff --git a/semantica/export/owl_exporter.py b/semantica/export/owl_exporter.py
index f4934218..48fff0ea 100644
--- a/semantica/export/owl_exporter.py
+++ b/semantica/export/owl_exporter.py
@@ -1,8 +1,25 @@
"""
-OWL Exporter for Semantic Modeling
+OWL Exporter Module
-Exports ontologies and knowledge graphs to OWL (Web Ontology Language) format
-for semantic modeling and ontology representation.
+This module provides comprehensive OWL (Web Ontology Language) export capabilities
+for the Semantica framework, enabling ontology export for semantic modeling.
+
+Key Features:
+ - OWL/OWL-XML format export
+ - Turtle format export
+ - Class definition and hierarchy export
+ - Object and data property export
+ - OWL 2.0 feature support
+ - Ontology validation
+
+Example Usage:
+ >>> from semantica.export import OWLExporter
+ >>> exporter = OWLExporter(ontology_uri="http://example.org/ontology#")
+ >>> exporter.export(ontology, "ontology.owl", format="owl-xml")
+ >>> exporter.export_classes(classes, "classes.owl")
+
+Author: Semantica Contributors
+License: MIT
"""
from typing import Any, Dict, List, Optional, Union
@@ -16,64 +33,129 @@ from ..utils.helpers import ensure_directory
class OWLExporter:
"""
- OWL exporter for semantic modeling.
+ OWL exporter for semantic modeling and ontology representation.
- • Exports ontologies to OWL/OWL-XML format
- • Handles class definitions and hierarchies
- • Manages object and data properties
- • Supports OWL 2.0 features
- • Generates OWL-XML serialization
- • Validates OWL structure
+ This class provides comprehensive OWL export functionality for ontologies,
+ including class definitions, hierarchies, and property definitions.
+
+ Features:
+ - OWL/OWL-XML format export
+ - Turtle format export
+ - Class definition and hierarchy export
+ - Object and data property export
+ - OWL 2.0 feature support
+ - Ontology validation
+
+ Example Usage:
+ >>> exporter = OWLExporter(
+ ... ontology_uri="http://example.org/ontology#",
+ ... version="1.0",
+ ... format="owl-xml"
+ ... )
+ >>> exporter.export(ontology, "ontology.owl")
"""
- def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ def __init__(
+ self,
+ ontology_uri: str = "https://semantica.dev/ontology/",
+ version: str = "1.0",
+ format: str = "owl-xml",
+ config: Optional[Dict[str, Any]] = None,
+ **kwargs
+ ):
"""
Initialize OWL exporter.
+ Sets up the exporter with ontology URI, version, and format configuration.
+
Args:
- config: Configuration dictionary
- **kwargs: Additional configuration options:
- - ontology_uri: Base ontology URI
- - version: Ontology version
- - format: Export format ('owl-xml', 'turtle')
+ ontology_uri: Base URI for the ontology (default: "https://semantica.dev/ontology/")
+ version: Ontology version string (default: "1.0")
+ format: Default export format - 'owl-xml' or 'turtle' (default: 'owl-xml')
+ config: Optional configuration dictionary (merged with kwargs)
+ **kwargs: Additional configuration options
"""
self.logger = get_logger("owl_exporter")
self.config = config or {}
self.config.update(kwargs)
- self.ontology_uri = self.config.get("ontology_uri", "https://semantica.dev/ontology/")
- self.version = self.config.get("version", "1.0")
- self.format = self.config.get("format", "owl-xml")
+ # OWL configuration
+ self.ontology_uri = ontology_uri
+ self.version = version
+ self.format = format
+
+ self.logger.debug(
+ f"OWL exporter initialized: uri={ontology_uri}, "
+ f"version={version}, format={format}"
+ )
def export(
self,
ontology: Dict[str, Any],
file_path: Union[str, Path],
format: Optional[str] = None,
+ encoding: str = "utf-8",
**options
) -> None:
"""
- Export ontology to OWL format.
+ Export ontology to OWL format file.
+
+ This method exports a complete ontology (classes, properties, etc.) to
+ OWL format in either OWL-XML or Turtle serialization.
+
+ Supported Formats:
+ - "owl-xml": OWL-XML format (RDF/XML-based)
+ - "turtle": Turtle format (human-readable)
Args:
- ontology: Ontology dictionary with classes, properties, etc.
- file_path: Output file path
- format: Export format ('owl-xml', 'turtle')
- **options: Additional options
+ ontology: Ontology dictionary containing:
+ - uri: Ontology URI (optional, uses self.ontology_uri if not provided)
+ - name: Ontology name
+ - description: Ontology description (optional)
+ - version: Ontology version (optional)
+ - classes: List of class definitions
+ - object_properties: List of object property definitions
+ - data_properties: List of data property definitions
+ file_path: Output OWL file path
+ format: Export format - 'owl-xml' or 'turtle' (default: self.format)
+ encoding: File encoding (default: 'utf-8')
+ **options: Additional export options
+
+ Raises:
+ ValidationError: If format is unsupported
+
+ Example:
+ >>> ontology = {
+ ... "name": "MyOntology",
+ ... "classes": [...],
+ ... "object_properties": [...]
+ ... }
+ >>> exporter.export(ontology, "ontology.owl", format="owl-xml")
"""
file_path = Path(file_path)
ensure_directory(file_path.parent)
export_format = format or self.format
+ self.logger.debug(
+ f"Exporting ontology to {export_format}: {file_path}, "
+ f"classes={len(ontology.get('classes', []))}, "
+ f"object_properties={len(ontology.get('object_properties', []))}, "
+ f"data_properties={len(ontology.get('data_properties', []))}"
+ )
+
+ # Generate OWL content based on format
if export_format == "owl-xml":
owl_content = self._export_owl_xml(ontology, **options)
elif export_format == "turtle":
owl_content = self._export_owl_turtle(ontology, **options)
else:
- raise ValidationError(f"Unsupported OWL format: {export_format}")
+ raise ValidationError(
+ f"Unsupported OWL format: {export_format}. "
+ "Supported formats: owl-xml, turtle"
+ )
- encoding = options.get("encoding", "utf-8")
+ # Write OWL file
with open(file_path, "w", encoding=encoding) as f:
f.write(owl_content)
@@ -95,8 +177,24 @@ class OWLExporter:
"""
self.export(ontology, file_path, **options)
- def _export_owl_xml(self, ontology: Dict[str, Any], **options) -> str:
- """Export to OWL-XML format."""
+ def _export_owl_xml(
+ self,
+ ontology: Dict[str, Any],
+ **options
+ ) -> str:
+ """
+ Export ontology to OWL-XML format.
+
+ OWL-XML is the RDF/XML-based serialization of OWL ontologies. This method
+ generates OWL-XML syntax with proper RDF/XML structure.
+
+ Args:
+ ontology: Ontology dictionary with classes, properties, etc.
+ **options: Additional export options (unused)
+
+ Returns:
+ String containing OWL-XML serialization
+ """
ontology_uri = ontology.get("uri") or self.ontology_uri
ontology_name = ontology.get("name", "SemanticaOntology")
version = ontology.get("version") or self.version
@@ -203,8 +301,24 @@ class OWLExporter:
lines.append("</rdf:RDF>")
return "\n".join(lines)
- def _export_owl_turtle(self, ontology: Dict[str, Any], **options) -> str:
- """Export to OWL Turtle format."""
+ def _export_owl_turtle(
+ self,
+ ontology: Dict[str, Any],
+ **options
+ ) -> str:
+ """
+ Export ontology to OWL Turtle format.
+
+ Turtle is a human-readable RDF serialization format. This method generates
+ OWL ontology in Turtle syntax with namespace declarations and OWL constructs.
+
+ Args:
+ ontology: Ontology dictionary with classes, properties, etc.
+ **options: Additional export options (unused)
+
+ Returns:
+ String containing OWL Turtle serialization
+ """
ontology_uri = ontology.get("uri") or self.ontology_uri
ontology_name = ontology.get("name", "SemanticaOntology")
version = ontology.get("version") or self.version
@@ -285,20 +399,39 @@ class OWLExporter:
self,
classes: List[Dict[str, Any]],
file_path: Union[str, Path],
+ ontology_uri: Optional[str] = None,
+ ontology_name: str = "SemanticaOntology",
**options
) -> None:
"""
- Export classes to OWL format.
+ Export class definitions to OWL format.
+
+ This method exports a list of class definitions to OWL format, creating
+ a minimal ontology containing only the classes.
Args:
- classes: List of class definitions
- file_path: Output file path
- **options: Additional options
+ classes: List of class definition dictionaries with fields:
+ - uri/id: Class URI/identifier
+ - name/label: Class name/label
+ - comment: Class description (optional)
+ - subClassOf: Parent class URI (optional)
+ - equivalentClass: Equivalent class URI (optional)
+ file_path: Output OWL file path
+ ontology_uri: Ontology URI (default: self.ontology_uri)
+ ontology_name: Ontology name (default: "SemanticaOntology")
+ **options: Additional options passed to export()
+
+ Example:
+ >>> classes = [
+ ... {"uri": "http://example.org/Person", "name": "Person"},
+ ... {"uri": "http://example.org/Organization", "name": "Organization"}
+ ... ]
+ >>> exporter.export_classes(classes, "classes.owl")
"""
ontology = {
"classes": classes,
- "uri": options.get("ontology_uri", self.ontology_uri),
- "name": options.get("ontology_name", "SemanticaOntology")
+ "uri": ontology_uri or self.ontology_uri,
+ "name": ontology_name
}
self.export(ontology, file_path, **options)
@@ -307,22 +440,55 @@ class OWLExporter:
properties: List[Dict[str, Any]],
file_path: Union[str, Path],
property_type: str = "object",
+ ontology_uri: Optional[str] = None,
+ ontology_name: str = "SemanticaOntology",
**options
) -> None:
"""
- Export properties to OWL format.
+ Export property definitions to OWL format.
+
+ This method exports a list of property definitions (object or data properties)
+ to OWL format, creating a minimal ontology containing only the properties.
Args:
- properties: List of property definitions
- file_path: Output file path
- property_type: Property type ('object', 'data')
- **options: Additional options
+ properties: List of property definition dictionaries with fields:
+ - uri/id: Property URI/identifier
+ - name/label: Property name/label
+ - comment: Property description (optional)
+ - domain: Domain class URI(s) (optional)
+ - range: Range class URI or datatype (optional)
+ file_path: Output OWL file path
+ property_type: Property type - 'object' or 'data' (default: 'object')
+ ontology_uri: Ontology URI (default: self.ontology_uri)
+ ontology_name: Ontology name (default: "SemanticaOntology")
+ **options: Additional options passed to export()
+
+ Raises:
+ ValidationError: If property_type is invalid
+
+ Example:
+ >>> properties = [
+ ... {
+ ... "uri": "http://example.org/hasName",
+ ... "name": "hasName",
+ ... "domain": "http://example.org/Person",
+ ... "range": "http://www.w3.org/2001/XMLSchema#string"
+ ... }
+ ... ]
+ >>> exporter.export_properties(properties, "properties.owl", property_type="data")
"""
+ if property_type not in ["object", "data"]:
+ raise ValidationError(
+ f"Invalid property_type: {property_type}. "
+ "Must be 'object' or 'data'."
+ )
+
ontology = {
- "uri": options.get("ontology_uri", self.ontology_uri),
- "name": options.get("ontology_name", "SemanticaOntology")
+ "uri": ontology_uri or self.ontology_uri,
+ "name": ontology_name
}
+ # Add properties based on type
if property_type == "object":
ontology["object_properties"] = properties
else:
diff --git a/semantica/export/rdf_exporter.py b/semantica/export/rdf_exporter.py
index 2a1b0471..7b2cbe78 100644
--- a/semantica/export/rdf_exporter.py
+++ b/semantica/export/rdf_exporter.py
@@ -1,20 +1,32 @@
"""
RDF Export Module
-Handles export of data to RDF formats.
+This module provides comprehensive RDF (Resource Description Framework) export
+capabilities for the Semantica framework, supporting multiple RDF serialization
+formats and validation.
Key Features:
+ - Multiple RDF format support (Turtle, RDF/XML, JSON-LD, N-Triples, N3)
- RDF serialization and export
- - Multiple RDF format support
- - Namespace management
+ - Namespace management and conflict resolution
- RDF validation and quality checking
- Batch RDF export processing
+ - Knowledge graph to RDF conversion
Main Classes:
- RDFExporter: Main RDF export class
- RDFSerializer: RDF serialization engine
- RDFValidator: RDF validation engine
- NamespaceManager: RDF namespace management
+
+Example Usage:
+ >>> from semantica.export import RDFExporter
+ >>> exporter = RDFExporter()
+ >>> exporter.export(data, "output.ttl", format="turtle")
+ >>> validation = exporter.validate_rdf(data)
+
+Author: Semantica Contributors
+License: MIT
"""
from typing import Any, Dict, List, Optional, Set, Union
@@ -29,22 +41,36 @@ class NamespaceManager:
"""
RDF namespace management engine.
- • Manages RDF namespaces
- • Handles namespace declarations
- • Processes namespace conflicts
- • Manages namespace metadata
+ This class manages RDF namespaces, handles namespace declarations, resolves
+ conflicts, and generates namespace declarations for various RDF formats.
+
+ Features:
+ - Namespace registration and management
+ - Namespace declaration generation
+ - Namespace conflict resolution
+ - Format-specific namespace formatting
+
+ Example Usage:
+ >>> manager = NamespaceManager()
+ >>> declarations = manager.generate_namespace_declarations(
+ ... {"ex": "http://example.org/ns#"},
+ ... format="turtle"
+ ... )
"""
def __init__(self, **config):
"""
Initialize namespace manager.
- • Setup namespace handling
- • Configure namespace resolution
- • Initialize conflict resolution
- • Setup metadata management
+ Sets up the namespace manager with standard RDF namespaces and
+ configuration options.
+
+ Args:
+ **config: Configuration options (currently unused)
"""
self.logger = get_logger("namespace_manager")
+
+ # Standard RDF namespaces
self.namespaces: Dict[str, str] = {
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
@@ -53,15 +79,32 @@ class NamespaceManager:
"semantica": "https://semantica.dev/ns#"
}
self.config = config or {}
+
+ self.logger.debug(
+ f"Namespace manager initialized with {len(self.namespaces)} namespace(s)"
+ )
def extract_namespaces(self, rdf_data: Dict[str, Any]) -> Dict[str, str]:
"""
Extract namespaces from RDF data.
- • Identify namespace usage
- • Extract namespace declarations
- • Analyze namespace requirements
- • Return namespace information
+ This method identifies and extracts namespace declarations from RDF data,
+ particularly from JSON-LD @context or other namespace declarations.
+
+ Args:
+ rdf_data: RDF data dictionary that may contain namespace information
+
+ Returns:
+ Dictionary mapping namespace prefixes to URIs
+
+ Example:
+ >>> rdf_data = {
+ ... "@context": {
+ ... "ex": "http://example.org/ns#",
+ ... "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ ... }
+ ... }
+ >>> namespaces = manager.extract_namespaces(rdf_data)
"""
extracted = {}
@@ -70,53 +113,96 @@ class NamespaceManager:
context = rdf_data["@context"]
if isinstance(context, dict):
for prefix, uri in context.items():
+ # Skip JSON-LD keywords (starting with @)
if not prefix.startswith("@"):
extracted[prefix] = uri
+ self.logger.debug(f"Extracted namespace: {prefix} -> {uri}")
return extracted
- def generate_namespace_declarations(self, namespaces: Dict[str, str], format: str = "turtle") -> str:
+ def generate_namespace_declarations(
+ self,
+ namespaces: Dict[str, str],
+ format: str = "turtle"
+ ) -> str:
"""
- Generate namespace declarations.
+ Generate namespace declarations for specified RDF format.
+
+ This method creates namespace declarations in the appropriate syntax
+ for the specified RDF format.
+
+ Supported Formats:
+ - "turtle": Turtle format (@prefix prefix: <uri> .)
+ - "rdfxml": RDF/XML format (xmlns:prefix="uri")
+ - "jsonld": JSON-LD format (returns empty, handled via @context)
+
+ Args:
+ namespaces: Dictionary mapping namespace prefixes to URIs
+ format: RDF format - 'turtle', 'rdfxml', or 'jsonld' (default: 'turtle')
+
+ Returns:
+ String containing namespace declarations in format-specific syntax
- • Create namespace declarations
- • Handle namespace formatting
- • Optimize namespace usage
- • Return namespace declarations
+ Example:
+ >>> namespaces = {"ex": "http://example.org/ns#"}
+ >>> decls = manager.generate_namespace_declarations(namespaces, "turtle")
+ >>> # Returns: "@prefix ex: <http://example.org/ns#> ."
"""
declarations = []
if format == "turtle":
+ # Turtle format: @prefix prefix: <uri> .
for prefix, uri in namespaces.items():
declarations.append(f"@prefix {prefix}: <{uri}> .")
elif format == "rdfxml":
+ # RDF/XML format: xmlns:prefix="uri"
for prefix, uri in namespaces.items():
declarations.append(f'xmlns:{prefix}="{uri}"')
elif format == "jsonld":
- # JSON-LD uses @context
- return "" # Handled separately
+ # JSON-LD uses @context, not separate declarations
+ return "" # Handled separately in JSON-LD serialization
return "\n".join(declarations)
- def resolve_namespace_conflicts(self, namespaces: Dict[str, str]) -> Dict[str, str]:
+ def resolve_namespace_conflicts(
+ self,
+ namespaces: Dict[str, str]
+ ) -> Dict[str, str]:
"""
Resolve namespace conflicts.
- • Identify namespace conflicts
- • Apply conflict resolution
- • Handle namespace mapping
- • Return resolved namespaces
+ This method identifies namespace conflicts where multiple prefixes map
+ to the same URI, or the same prefix maps to multiple URIs. Logs warnings
+ for conflicts but allows them (first prefix wins).
+
+ Args:
+ namespaces: Dictionary mapping namespace prefixes to URIs
+
+ Returns:
+ Dictionary with resolved namespaces (conflicts logged but preserved)
+
+ Example:
+ >>> namespaces = {
+ ... "ex": "http://example.org/ns#",
+ ... "ex2": "http://example.org/ns#" # Same URI, different prefix
+ ... }
+ >>> resolved = manager.resolve_namespace_conflicts(namespaces)
+ >>> # Logs warning about conflict, returns both mappings
"""
resolved = {}
- seen_uris = {}
+ seen_uris = {} # Track which prefix was first for each URI
for prefix, uri in namespaces.items():
if uri in seen_uris:
- # Conflict - use existing prefix or create new one
+ # Conflict: same URI, different prefix
existing_prefix = seen_uris[uri]
resolved[prefix] = uri
if prefix != existing_prefix:
- self.logger.warning(f"Namespace conflict: {prefix} and {existing_prefix} map to {uri}")
+ self.logger.warning(
+ f"Namespace conflict: prefixes '{prefix}' and "
+ f"'{existing_prefix}' both map to URI '{uri}'. "
+ "Using first prefix."
+ )
else:
resolved[prefix] = uri
seen_uris[uri] = prefix
@@ -128,74 +214,134 @@ class RDFSerializer:
"""
RDF serialization engine.
- • Serializes RDF data to various formats
- • Handles format-specific serialization
- • Manages RDF encoding
- • Processes RDF metadata
+ This class provides RDF serialization to various formats including Turtle,
+ RDF/XML, and JSON-LD. Handles format-specific syntax and encoding.
+
+ Features:
+ - Multiple RDF format serialization
+ - Format-specific syntax handling
+ - Namespace management integration
+ - Entity and relationship conversion
+
+ Example Usage:
+ >>> serializer = RDFSerializer()
+ >>> turtle = serializer.serialize_to_turtle(rdf_data)
+ >>> jsonld = serializer.serialize_to_jsonld(rdf_data)
"""
def __init__(self, **config):
"""
Initialize RDF serializer.
- • Setup serialization engines
- • Configure format handlers
- • Initialize encoding tools
- • Setup metadata processing
+ Sets up the serializer with namespace management and configuration.
+
+ Args:
+ **config: Configuration options (currently unused)
"""
self.logger = get_logger("rdf_serializer")
self.config = config or {}
self.namespace_manager = NamespaceManager()
+
+ self.logger.debug("RDF serializer initialized")
- def serialize_to_turtle(self, rdf_data: Dict[str, Any], **options) -> str:
+ def serialize_to_turtle(
+ self,
+ rdf_data: Dict[str, Any],
+ **options
+ ) -> str:
"""
Serialize RDF to Turtle format.
- • Convert RDF to Turtle syntax
- • Handle Turtle-specific formatting
- • Optimize Turtle output
- • Return Turtle serialization
+ Turtle is a compact, human-readable RDF serialization format. This method
+ converts RDF data (entities and relationships) to Turtle syntax with
+ namespace declarations and RDF triples.
+
+ Args:
+ rdf_data: RDF data dictionary containing:
+ - entities: List of entity dictionaries
+ - relationships: List of relationship dictionaries
+ - @context: Optional JSON-LD context for namespaces
+ **options: Additional serialization options (unused)
+
+ Returns:
+ String containing Turtle-format RDF serialization
+
+ Example:
+ >>> rdf_data = {
+ ... "entities": [{"id": "e1", "text": "Entity 1", "type": "Person"}],
+ ... "relationships": [{"source_id": "e1", "target_id": "e2", "type": "knows"}]
+ ... }
+ >>> turtle = serializer.serialize_to_turtle(rdf_data)
"""
lines = []
# Generate namespace declarations
namespaces = self.namespace_manager.extract_namespaces(rdf_data)
if namespaces:
- ns_declarations = self.namespace_manager.generate_namespace_declarations(namespaces, "turtle")
+ ns_declarations = self.namespace_manager.generate_namespace_declarations(
+ namespaces,
+ "turtle"
+ )
lines.append(ns_declarations)
lines.append("")
- # Convert entities to triples
+ # Convert entities to RDF triples
entities = rdf_data.get("entities", [])
for entity in entities:
- entity_id = entity.get("id") or f"semantica:entity_{hash(entity.get('text', ''))}"
+ # Generate entity ID if not provided
+ entity_id = entity.get("id")
+ if not entity_id:
+ entity_text = entity.get("text", "")
+ entity_id = f"semantica:entity_{hash(entity_text)}"
+
entity_type = entity.get("type", "semantica:Entity")
text = entity.get("text") or entity.get("label", "")
+ confidence = entity.get("confidence", 1.0)
+ # Turtle triple syntax: subject predicate object .
lines.append(f"<{entity_id}> a <{entity_type}> ;")
lines.append(f' semantica:text "{text}" ;')
- lines.append(f' semantica:confidence {entity.get("confidence", 1.0)} .')
+ lines.append(f' semantica:confidence {confidence} .')
lines.append("")
- # Convert relationships to triples
+ # Convert relationships to RDF triples
relationships = rdf_data.get("relationships", [])
for rel in relationships:
source_id = rel.get("source_id") or rel.get("source")
target_id = rel.get("target_id") or rel.get("target")
rel_type = rel.get("type", "semantica:related_to")
+ # Simple triple: subject predicate object .
lines.append(f"<{source_id}> <{rel_type}> <{target_id}> .")
return "\n".join(lines)
- def serialize_to_rdfxml(self, rdf_data: Dict[str, Any], **options) -> str:
+ def serialize_to_rdfxml(
+ self,
+ rdf_data: Dict[str, Any],
+ **options
+ ) -> str:
"""
Serialize RDF to RDF/XML format.
- • Convert RDF to RDF/XML syntax
- • Handle XML-specific formatting
- • Optimize XML structure
- • Return RDF/XML serialization
+ RDF/XML is the XML-based RDF serialization format, standardized by W3C.
+ This method converts RDF data to RDF/XML syntax with proper XML structure.
+
+ Args:
+ rdf_data: RDF data dictionary containing:
+ - entities: List of entity dictionaries
+ - relationships: List of relationship dictionaries
+ **options: Additional serialization options (unused)
+
+ Returns:
+ String containing RDF/XML-format RDF serialization
+
+ Example:
+ >>> rdf_data = {
+ ... "entities": [{"id": "e1", "text": "Entity 1"}],
+ ... "relationships": [{"source_id": "e1", "target_id": "e2"}]
+ ... }
+ >>> rdfxml = serializer.serialize_to_rdfxml(rdf_data)
"""
lines = ['<?xml version="1.0" encoding="UTF-8"?>']
lines.append('<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"')
@@ -203,27 +349,35 @@ class RDFSerializer:
lines.append(' xmlns:semantica="https://semantica.dev/ns#">')
lines.append("")
- # Convert entities
+ # Convert entities to RDF/XML
entities = rdf_data.get("entities", [])
for entity in entities:
- entity_id = entity.get("id") or f"semantica:entity_{hash(entity.get('text', ''))}"
+ # Generate entity ID if not provided
+ entity_id = entity.get("id")
+ if not entity_id:
+ entity_text = entity.get("text", "")
+ entity_id = f"semantica:entity_{hash(entity_text)}"
+
entity_type = entity.get("type", "semantica:Entity")
text = entity.get("text") or entity.get("label", "")
+ confidence = entity.get("confidence", 1.0)
+ # RDF/XML syntax: rdf:Description with rdf:about
lines.append(f' <rdf:Description rdf:about="{entity_id}">')
lines.append(f' <rdf:type rdf:resource="{entity_type}"/>')
lines.append(f' <semantica:text>{text}</semantica:text>')
- lines.append(f' <semantica:confidence>{entity.get("confidence", 1.0)}</semantica:confidence>')
+ lines.append(f' <semantica:confidence>{confidence}</semantica:confidence>')
lines.append(" </rdf:Description>")
lines.append("")
- # Convert relationships
+ # Convert relationships to RDF/XML
relationships = rdf_data.get("relationships", [])
for rel in relationships:
source_id = rel.get("source_id") or rel.get("source")
target_id = rel.get("target_id") or rel.get("target")
rel_type = rel.get("type", "semantica:related_to")
+ # Relationship as property on source entity
lines.append(f' <rdf:Description rdf:about="{source_id}">')
lines.append(f' <{rel_type} rdf:resource="{target_id}"/>')
lines.append(" </rdf:Description>")
@@ -232,17 +386,38 @@ class RDFSerializer:
lines.append("</rdf:RDF>")
return "\n".join(lines)
- def serialize_to_jsonld(self, rdf_data: Dict[str, Any], **options) -> str:
+ def serialize_to_jsonld(
+ self,
+ rdf_data: Dict[str, Any],
+ **options
+ ) -> str:
"""
Serialize RDF to JSON-LD format.
- • Convert RDF to JSON-LD syntax
- • Handle JSON-specific formatting
- • Optimize JSON structure
- • Return JSON-LD serialization
+ JSON-LD is a JSON-based RDF serialization format that uses @context for
+ namespace management and @graph for RDF data. This method converts RDF
+ data to JSON-LD syntax.
+
+ Args:
+ rdf_data: RDF data dictionary containing:
+ - entities: List of entity dictionaries
+ - relationships: List of relationship dictionaries
+ - @context: Optional existing context (merged)
+ **options: Additional serialization options (unused)
+
+ Returns:
+ String containing JSON-LD-format RDF serialization (pretty-printed JSON)
+
+ Example:
+ >>> rdf_data = {
+ ... "entities": [{"id": "e1", "text": "Entity 1"}],
+ ... "relationships": [{"source_id": "e1", "target_id": "e2"}]
+ ... }
+ >>> jsonld = serializer.serialize_to_jsonld(rdf_data)
"""
import json
+ # Initialize JSON-LD structure with context
jsonld = {
"@context": {
"@vocab": "https://semantica.dev/vocab/",
@@ -253,24 +428,41 @@ class RDFSerializer:
"@graph": []
}
- # Convert entities
+ # Merge existing context if present
+ if "@context" in rdf_data:
+ jsonld["@context"].update(rdf_data["@context"])
+
+ # Convert entities to JSON-LD
entities = rdf_data.get("entities", [])
for entity in entities:
+ # Generate @id if not provided
+ entity_id = entity.get("id")
+ if not entity_id:
+ entity_text = entity.get("text", "")
+ entity_id = f"semantica:entity/{entity_text}"
+
jsonld["@graph"].append({
- "@id": entity.get("id") or f"semantica:entity/{entity.get('text', '')}",
+ "@id": entity_id,
"@type": entity.get("type", "semantica:Entity"),
"semantica:text": entity.get("text") or entity.get("label", ""),
"semantica:confidence": entity.get("confidence", 1.0)
})
- # Convert relationships
+ # Convert relationships to JSON-LD
relationships = rdf_data.get("relationships", [])
for rel in relationships:
+ # Generate @id if not provided
+ rel_id = rel.get("id")
+ if not rel_id:
+ source_id = rel.get("source_id", "")
+ target_id = rel.get("target_id", "")
+ rel_id = f"semantica:rel/{source_id}_{target_id}"
+
jsonld["@graph"].append({
- "@id": rel.get("id") or f"semantica:rel/{rel.get('source_id')}_{rel.get('target_id')}",
+ "@id": rel_id,
"@type": "semantica:Relationship",
- "semantica:source": {"@id": rel.get("source_id")},
- "semantica:target": {"@id": rel.get("target_id")},
+ "semantica:source": {"@id": rel.get("source_id") or rel.get("source")},
+ "semantica:target": {"@id": rel.get("target_id") or rel.get("target")},
"semantica:type": rel.get("type", "related_to")
})
@@ -281,32 +473,64 @@ class RDFValidator:
"""
RDF validation engine.
- • Validates RDF data quality
- • Checks RDF syntax and structure
- • Validates namespace usage
- • Handles RDF consistency checking
+ This class provides RDF data validation including syntax checking, structure
+ validation, namespace usage validation, and consistency checking.
+
+ Features:
+ - RDF syntax validation
+ - Structure and format validation
+ - Namespace usage validation
+ - Consistency checking (entity references, etc.)
+
+ Example Usage:
+ >>> validator = RDFValidator()
+ >>> result = validator.validate_rdf_syntax(rdf_data, format="turtle")
+ >>> consistency = validator.check_rdf_consistency(rdf_data)
"""
def __init__(self, **config):
"""
Initialize RDF validator.
- • Setup validation rules
- • Configure syntax checkers
- • Initialize consistency checkers
- • Setup quality assessment
+ Sets up the validator with configuration options.
+
+ Args:
+ **config: Configuration options (currently unused)
"""
self.logger = get_logger("rdf_validator")
self.config = config or {}
+
+ self.logger.debug("RDF validator initialized")
- def validate_rdf_syntax(self, rdf_data: Dict[str, Any], format: str = "turtle") -> Dict[str, Any]:
+ def validate_rdf_syntax(
+ self,
+ rdf_data: Dict[str, Any],
+ format: str = "turtle"
+ ) -> Dict[str, Any]:
"""
Validate RDF syntax for specified format.
- • Check syntax correctness
- • Validate format-specific rules
- • Handle syntax errors
- • Return validation results
+ This method performs syntax and structure validation on RDF data,
+ checking for required fields, correct data types, and format-specific
+ requirements.
+
+ Args:
+ rdf_data: RDF data dictionary to validate
+ format: RDF format being validated (default: "turtle")
+ (currently unused, but reserved for format-specific checks)
+
+ Returns:
+ Dictionary containing:
+ - valid: Boolean indicating if validation passed
+ - errors: List of error messages
+ - warnings: List of warning messages
+
+ Example:
+ >>> result = validator.validate_rdf_syntax(rdf_data, format="turtle")
+ >>> if result["valid"]:
+ ... print("RDF syntax is valid")
+ ... else:
+ ... print(f"Errors: {result['errors']}")
"""
errors = []
warnings = []
@@ -318,42 +542,85 @@ class RDFValidator:
# Check for required fields
if "entities" not in rdf_data and "relationships" not in rdf_data:
- warnings.append("No entities or relationships found in RDF data")
+ warnings.append(
+ "No entities or relationships found in RDF data. "
+ "RDF data may be empty."
+ )
# Validate entities
entities = rdf_data.get("entities", [])
for i, entity in enumerate(entities):
if not isinstance(entity, dict):
- errors.append(f"Entity {i} is not a dictionary")
+ errors.append(f"Entity {i} is not a dictionary (type: {type(entity)})")
continue
+ # Check for required fields (at least id or text)
if "id" not in entity and "text" not in entity:
- warnings.append(f"Entity {i} missing 'id' or 'text'")
+ warnings.append(
+ f"Entity {i} missing both 'id' and 'text' fields. "
+ "Entity may not be properly identifiable."
+ )
# Validate relationships
relationships = rdf_data.get("relationships", [])
for i, rel in enumerate(relationships):
if not isinstance(rel, dict):
- errors.append(f"Relationship {i} is not a dictionary")
+ errors.append(
+ f"Relationship {i} is not a dictionary (type: {type(rel)})"
+ )
continue
- if "source_id" not in rel and "target_id" not in rel:
- errors.append(f"Relationship {i} missing 'source_id' or 'target_id'")
+ # Check for required fields
+ if "source_id" not in rel and "source" not in rel:
+ errors.append(
+ f"Relationship {i} missing 'source_id' or 'source' field"
+ )
+ if "target_id" not in rel and "target" not in rel:
+ errors.append(
+ f"Relationship {i} missing 'target_id' or 'target' field"
+ )
+
+ is_valid = len(errors) == 0
+
+ if is_valid:
+ self.logger.debug(
+ f"RDF syntax validation passed: {len(entities)} entity(ies), "
+ f"{len(relationships)} relationship(s)"
+ )
+ else:
+ self.logger.warning(
+ f"RDF syntax validation failed: {len(errors)} error(s), "
+ f"{len(warnings)} warning(s)"
+ )
return {
- "valid": len(errors) == 0,
+ "valid": is_valid,
"errors": errors,
"warnings": warnings
}
- def validate_namespace_usage(self, rdf_data: Dict[str, Any]) -> Dict[str, Any]:
+ def validate_namespace_usage(
+ self,
+ rdf_data: Dict[str, Any]
+ ) -> Dict[str, Any]:
"""
Validate RDF namespace usage.
- • Check namespace declarations
- • Validate namespace references
- • Handle namespace conflicts
- • Return namespace validation
+ This method validates namespace declarations and usage in RDF data,
+ particularly for JSON-LD format which uses @context.
+
+ Args:
+ rdf_data: RDF data dictionary to validate
+
+ Returns:
+ Dictionary containing:
+ - valid: Boolean indicating if namespace usage is valid
+ - issues: List of namespace-related issues
+
+ Example:
+ >>> result = validator.validate_namespace_usage(rdf_data)
+ >>> if not result["valid"]:
+ ... print(f"Namespace issues: {result['issues']}")
"""
issues = []
@@ -361,41 +628,92 @@ class RDFValidator:
if "@context" in rdf_data:
context = rdf_data["@context"]
if not isinstance(context, dict):
- issues.append("@context must be a dictionary")
+ issues.append(
+ "@context must be a dictionary, got: {type(context)}"
+ )
+ else:
+ # Validate context entries
+ for prefix, uri in context.items():
+ if not isinstance(prefix, str):
+ issues.append(f"Context prefix must be string: {prefix}")
+ if not isinstance(uri, str):
+ issues.append(f"Context URI must be string: {uri}")
+
+ is_valid = len(issues) == 0
+
+ if is_valid:
+ self.logger.debug("Namespace usage validation passed")
+ else:
+ self.logger.warning(
+ f"Namespace usage validation found {len(issues)} issue(s)"
+ )
return {
- "valid": len(issues) == 0,
+ "valid": is_valid,
"issues": issues
}
- def check_rdf_consistency(self, rdf_data: Dict[str, Any]) -> Dict[str, Any]:
+ def check_rdf_consistency(
+ self,
+ rdf_data: Dict[str, Any]
+ ) -> Dict[str, Any]:
"""
Check RDF consistency and coherence.
- • Analyze RDF structure
- • Check logical consistency
- • Validate RDF relationships
- • Return consistency report
+ This method performs consistency checks on RDF data, including validation
+ of relationship references to ensure they point to existing entities.
+
+ Args:
+ rdf_data: RDF data dictionary to check
+
+ Returns:
+ Dictionary containing:
+ - consistent: Boolean indicating if data is consistent
+ - issues: List of consistency issues found
+
+ Example:
+ >>> result = validator.check_rdf_consistency(rdf_data)
+ >>> if not result["consistent"]:
+ ... print(f"Consistency issues: {result['issues']}")
"""
issues = []
- # Check relationship references
- relationships = rdf_data.get("relationships", [])
+ # Build set of entity IDs for reference checking
entities = rdf_data.get("entities", [])
entity_ids = {e.get("id") for e in entities if e.get("id")}
- for rel in relationships:
- source_id = rel.get("source_id")
- target_id = rel.get("target_id")
+ # Check relationship references
+ relationships = rdf_data.get("relationships", [])
+ for i, rel in enumerate(relationships):
+ source_id = rel.get("source_id") or rel.get("source")
+ target_id = rel.get("target_id") or rel.get("target")
+ # Check if source entity exists
if source_id and source_id not in entity_ids:
- issues.append(f"Relationship references non-existent source entity: {source_id}")
+ issues.append(
+ f"Relationship {i} references non-existent source entity: {source_id}"
+ )
+ # Check if target entity exists
if target_id and target_id not in entity_ids:
- issues.append(f"Relationship references non-existent target entity: {target_id}")
+ issues.append(
+ f"Relationship {i} references non-existent target entity: {target_id}"
+ )
+
+ is_consistent = len(issues) == 0
+
+ if is_consistent:
+ self.logger.debug(
+ f"RDF consistency check passed: {len(entities)} entity(ies), "
+ f"{len(relationships)} relationship(s)"
+ )
+ else:
+ self.logger.warning(
+ f"RDF consistency check found {len(issues)} issue(s)"
+ )
return {
- "consistent": len(issues) == 0,
+ "consistent": is_consistent,
"issues": issues
}
@@ -404,53 +722,96 @@ class RDFExporter:
"""
RDF export and serialization handler.
- • Exports data to RDF formats
- • Handles RDF serialization
- • Manages RDF namespaces
- • Validates RDF output
- • Supports multiple RDF formats
- • Handles batch RDF export
+ This class provides comprehensive RDF export functionality, combining
+ serialization, validation, and namespace management for multiple RDF formats.
+
+ Features:
+ - Multiple RDF format export (Turtle, RDF/XML, JSON-LD, N-Triples, N3)
+ - RDF serialization and validation
+ - Namespace management
+ - Knowledge graph to RDF conversion
+ - Batch export processing
+
+ Example Usage:
+ >>> exporter = RDFExporter()
+ >>> exporter.export(data, "output.ttl", format="turtle")
+ >>> validation = exporter.validate_rdf(data)
"""
- def __init__(self, config=None, **kwargs):
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
"""
Initialize RDF exporter.
- • Setup RDF serialization
- • Configure export formats
- • Initialize validation tools
- • Setup namespace management
- • Configure batch processing
+ Sets up the exporter with serialization, validation, and namespace
+ management components.
+
+ Args:
+ config: Optional configuration dictionary (merged with kwargs)
+ **kwargs: Additional configuration options
"""
self.logger = get_logger("rdf_exporter")
self.config = config or {}
self.config.update(kwargs)
+ # Initialize components
self.serializer = RDFSerializer()
self.validator = RDFValidator()
self.namespace_manager = NamespaceManager()
+ # Supported RDF formats
self.supported_formats = ["turtle", "rdfxml", "jsonld", "ntriples", "n3"]
+
+ self.logger.debug(
+ f"RDF exporter initialized with {len(self.supported_formats)} format(s)"
+ )
- def export_to_rdf(self, data: Dict[str, Any], format: str = "turtle", **options) -> str:
+ def export_to_rdf(
+ self,
+ data: Dict[str, Any],
+ format: str = "turtle",
+ **options
+ ) -> str:
"""
- Export data to RDF format.
+ Export data to RDF format string.
+
+ This method converts RDF data to a string in the specified RDF format.
+ Performs validation before serialization and handles format-specific
+ serialization.
+
+ Args:
+ data: RDF data dictionary containing entities and relationships
+ format: RDF format - 'turtle', 'rdfxml', or 'jsonld' (default: 'turtle')
+ **options: Additional serialization options
+
+ Returns:
+ String containing RDF serialization in specified format
+
+ Raises:
+ ValidationError: If format is unsupported or not implemented
- • Convert data to RDF
- • Apply format-specific serialization
- • Handle namespace declarations
- • Validate RDF output
- • Return RDF export
+ Example:
+ >>> rdf_string = exporter.export_to_rdf(data, format="turtle")
+ >>> print(rdf_string)
"""
if format not in self.supported_formats:
- raise ValidationError(f"Unsupported RDF format: {format}")
+ raise ValidationError(
+ f"Unsupported RDF format: {format}. "
+ f"Supported formats: {', '.join(self.supported_formats)}"
+ )
+
+ self.logger.debug(f"Exporting to RDF format: {format}")
- # Validate input
+ # Validate input data
validation = self.validator.validate_rdf_syntax(data, format)
if not validation["valid"]:
- self.logger.warning(f"RDF validation issues: {validation['errors']}")
+ self.logger.warning(
+ f"RDF validation issues found: {validation['errors']}. "
+ "Continuing with export, but data may be invalid."
+ )
+ if validation["warnings"]:
+ self.logger.debug(f"RDF validation warnings: {validation['warnings']}")
- # Serialize
+ # Serialize based on format
if format == "turtle":
return self.serializer.serialize_to_turtle(data, **options)
elif format == "rdfxml":
@@ -458,31 +819,45 @@ class RDFExporter:
elif format == "jsonld":
return self.serializer.serialize_to_jsonld(data, **options)
else:
- raise ValidationError(f"Format {format} not yet implemented")
+ raise ValidationError(
+ f"Format '{format}' not yet implemented. "
+ f"Implemented formats: turtle, rdfxml, jsonld"
+ )
def export(
self,
data: Dict[str, Any],
file_path: Union[str, Path],
format: str = "turtle",
+ encoding: str = "utf-8",
**options
) -> None:
"""
Export data to RDF file.
+ This method exports RDF data to a file in the specified format, handling
+ directory creation and file writing.
+
Args:
- data: Data to export
- file_path: Output file path
- format: RDF format ('turtle', 'rdfxml', 'jsonld')
- **options: Additional options
+ data: RDF data dictionary to export
+ file_path: Output RDF file path
+ format: RDF format - 'turtle', 'rdfxml', or 'jsonld' (default: 'turtle')
+ encoding: File encoding (default: 'utf-8')
+ **options: Additional options passed to export_to_rdf()
+
+ Example:
+ >>> exporter.export(rdf_data, "output.ttl", format="turtle")
+ >>> exporter.export(rdf_data, "output.rdf", format="rdfxml")
"""
file_path = Path(file_path)
ensure_directory(file_path.parent)
- rdf_content = self.export_to_rdf(data, format=format, **options)
+ self.logger.debug(f"Exporting RDF to file: {file_path}, format={format}")
- encoding = options.get("encoding", "utf-8")
+ # Generate RDF content
+ rdf_content = self.export_to_rdf(data, format=format, **options)
+ # Write to file
with open(file_path, "w", encoding=encoding) as f:
f.write(rdf_content)
@@ -499,40 +874,92 @@ class RDFExporter:
"""
return self.export_to_rdf(rdf_data, format=format, **options)
- def validate_rdf(self, rdf_data: Dict[str, Any], **options) -> Dict[str, Any]:
+ def validate_rdf(
+ self,
+ rdf_data: Dict[str, Any],
+ **options
+ ) -> Dict[str, Any]:
"""
Validate RDF data quality and structure.
- • Check RDF syntax and structure
- • Validate namespace usage
- • Check RDF consistency
- • Return validation results
- """
+ This method performs comprehensive validation of RDF data including
+ syntax validation, namespace usage validation, and consistency checking.
+
+ Args:
+ rdf_data: RDF data dictionary to validate
+ **options: Additional validation options (unused)
+
+ Returns:
+ Dictionary containing validation results:
+ - syntax: Syntax validation results
+ - namespaces: Namespace validation results
+ - consistency: Consistency check results
+ - overall_valid: Boolean indicating if all validations passed
+
+ Example:
+ >>> result = exporter.validate_rdf(rdf_data)
+ >>> if result["overall_valid"]:
+ ... print("RDF data is valid")
+ ... else:
+ ... print(f"Syntax errors: {result['syntax']['errors']}")
+ """
+ # Perform all validation checks
syntax_validation = self.validator.validate_rdf_syntax(rdf_data)
namespace_validation = self.validator.validate_namespace_usage(rdf_data)
consistency_check = self.validator.check_rdf_consistency(rdf_data)
+ # Determine overall validity
+ overall_valid = (
+ syntax_validation["valid"] and
+ namespace_validation["valid"] and
+ consistency_check["consistent"]
+ )
+
+ if overall_valid:
+ self.logger.info("RDF validation passed all checks")
+ else:
+ self.logger.warning(
+ f"RDF validation failed: "
+ f"syntax={syntax_validation['valid']}, "
+ f"namespaces={namespace_validation['valid']}, "
+ f"consistency={consistency_check['consistent']}"
+ )
+
return {
"syntax": syntax_validation,
"namespaces": namespace_validation,
"consistency": consistency_check,
- "overall_valid": (
- syntax_validation["valid"] and
- namespace_validation["valid"] and
- consistency_check["consistent"]
- )
+ "overall_valid": overall_valid
}
- def manage_namespaces(self, rdf_data: Dict[str, Any], **namespaces: str) -> Dict[str, Any]:
+ def manage_namespaces(
+ self,
+ rdf_data: Dict[str, Any],
+ **namespaces: str
+ ) -> Dict[str, Any]:
"""
Manage RDF namespaces and declarations.
- • Extract namespace requirements
- • Generate namespace declarations
- • Handle namespace conflicts
- • Return namespace management results
- """
- # Extract existing namespaces
+ This method extracts namespaces from RDF data, merges with provided
+ namespaces, resolves conflicts, and generates namespace declarations.
+
+ Args:
+ rdf_data: RDF data dictionary that may contain namespace information
+ **namespaces: Additional namespaces to add (prefix=uri format)
+
+ Returns:
+ Dictionary containing:
+ - namespaces: Resolved namespace dictionary (prefix -> URI)
+ - declarations: Namespace declarations string (Turtle format)
+
+ Example:
+ >>> result = exporter.manage_namespaces(
+ ... rdf_data,
+ ... ex="http://example.org/ns#"
+ ... )
+ >>> print(result["declarations"])
+ """
+ # Extract existing namespaces from data
extracted = self.namespace_manager.extract_namespaces(rdf_data)
# Merge with provided namespaces
@@ -541,7 +968,17 @@ class RDFExporter:
# Resolve conflicts
resolved = self.namespace_manager.resolve_namespace_conflicts(all_namespaces)
+ # Generate declarations
+ declarations = self.namespace_manager.generate_namespace_declarations(
+ resolved,
+ "turtle"
+ )
+
+ self.logger.debug(
+ f"Managed {len(resolved)} namespace(s): {list(resolved.keys())}"
+ )
+
return {
"namespaces": resolved,
- "declarations": self.namespace_manager.generate_namespace_declarations(resolved, "turtle")
+ "declarations": declarations
}
diff --git a/semantica/export/report_generator.py b/semantica/export/report_generator.py
index 8d53eb6b..3d8c7031 100644
--- a/semantica/export/report_generator.py
+++ b/semantica/export/report_generator.py
@@ -1,8 +1,26 @@
"""
-Report generator for Semantica framework.
+Report Generator Module
-This module provides report generation capabilities
-for analysis results and framework metrics.
+This module provides comprehensive report generation capabilities for the
+Semantica framework, enabling formatted reports for analysis results,
+quality metrics, and framework statistics.
+
+Key Features:
+ - Multiple report formats (HTML, Markdown, JSON, Text)
+ - Quality assurance reports
+ - Analysis reports
+ - Metrics reports
+ - Custom report templates
+ - Chart/visualization support
+
+Example Usage:
+ >>> from semantica.export import ReportGenerator
+ >>> generator = ReportGenerator(format="html")
+ >>> generator.generate_report(data, "report.html")
+ >>> generator.generate_quality_report(metrics, "quality.md", format="markdown")
+
+Author: Semantica Contributors
+License: MIT
"""
from typing import Any, Dict, List, Optional, Union
@@ -19,54 +37,119 @@ class ReportGenerator:
"""
Report generator for analysis results and metrics.
- • Report generation functionality
- • Analysis result formatting
- • Framework metrics reporting
- • Performance optimization
- • Error handling and recovery
- • Advanced reporting features
+ This class provides comprehensive report generation functionality for
+ various data types including quality metrics, analysis results, and
+ framework statistics.
+
+ Features:
+ - Multiple report formats (HTML, Markdown, JSON, Text)
+ - Quality assurance reports
+ - Analysis reports
+ - Metrics reports
+ - Custom report templates
+ - Chart/visualization support
+
+ Example Usage:
+ >>> generator = ReportGenerator(
+ ... format="html",
+ ... include_charts=True
+ ... )
+ >>> generator.generate_report(data, "report.html")
"""
- def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ def __init__(
+ self,
+ format: str = "markdown",
+ include_charts: bool = False,
+ template: Optional[str] = None,
+ config: Optional[Dict[str, Any]] = None,
+ **kwargs
+ ):
"""
Initialize report generator.
+ Sets up the generator with specified format, chart inclusion, and template options.
+
Args:
- config: Configuration dictionary
- **kwargs: Additional configuration options:
- - format: Report format ('html', 'markdown', 'json', 'text')
- - include_charts: Include charts/visualizations (default: False)
- - template: Custom report template
+ format: Default report format - 'html', 'markdown', 'json', or 'text'
+ (default: 'markdown')
+ include_charts: Whether to include charts/visualizations (default: False)
+ template: Custom report template path or identifier (default: None)
+ config: Optional configuration dictionary (merged with kwargs)
+ **kwargs: Additional configuration options
"""
self.logger = get_logger("report_generator")
self.config = config or {}
self.config.update(kwargs)
- self.format = self.config.get("format", "markdown")
- self.include_charts = self.config.get("include_charts", False)
- self.template = self.config.get("template")
+ # Report configuration
+ self.format = format
+ self.include_charts = include_charts
+ self.template = template
+
+ self.logger.debug(
+ f"Report generator initialized: format={format}, "
+ f"include_charts={include_charts}"
+ )
def generate_report(
self,
data: Dict[str, Any],
file_path: Optional[Union[str, Path]] = None,
format: Optional[str] = None,
+ encoding: str = "utf-8",
**options
- ) -> Union[str, None]:
+ ) -> Optional[str]:
"""
Generate report from data.
+ This method generates a formatted report from data dictionary in the
+ specified format. Can write to file or return as string.
+
+ Supported Formats:
+ - "markdown": Markdown format (default)
+ - "html": HTML format with styling
+ - "json": JSON format
+ - "text": Plain text format
+
Args:
- data: Report data dictionary
- file_path: Optional output file path
- format: Report format ('html', 'markdown', 'json', 'text')
- **options: Additional options
-
+ data: Report data dictionary containing:
+ - title: Report title
+ - generated_at: Generation timestamp (optional, auto-added)
+ - summary: Summary dictionary or string (optional)
+ - metrics: Metrics dictionary (optional)
+ - analysis: Analysis results dictionary (optional)
+ file_path: Optional output file path. If None, returns report as string.
+ format: Report format - 'html', 'markdown', 'json', or 'text'
+ (default: self.format)
+ encoding: File encoding (default: 'utf-8')
+ **options: Additional format-specific options
+
Returns:
- Report string if file_path not provided, None otherwise
+ Report string if file_path is None, None if file was written
+
+ Raises:
+ ValidationError: If format is unsupported
+
+ Example:
+ >>> data = {
+ ... "title": "Analysis Report",
+ ... "metrics": {"total": 100, "success": 95}
+ ... }
+ >>> # Write to file
+ >>> generator.generate_report(data, "report.html", format="html")
+ >>> # Get as string
+ >>> report = generator.generate_report(data, format="markdown")
"""
report_format = format or self.format
+ self.logger.debug(
+ f"Generating report ({report_format}): "
+ f"title={data.get('title', 'Report')}, "
+ f"file_path={file_path}"
+ )
+
+ # Generate report based on format
if report_format == "markdown":
report = self._generate_markdown(data, **options)
elif report_format == "html":
@@ -76,19 +159,23 @@ class ReportGenerator:
elif report_format == "text":
report = self._generate_text(data, **options)
else:
- raise ValidationError(f"Unsupported report format: {report_format}")
+ raise ValidationError(
+ f"Unsupported report format: {report_format}. "
+ "Supported formats: markdown, html, json, text"
+ )
+ # Write to file if path provided
if file_path:
file_path = Path(file_path)
ensure_directory(file_path.parent)
- encoding = options.get("encoding", "utf-8")
with open(file_path, "w", encoding=encoding) as f:
f.write(report)
self.logger.info(f"Generated report ({report_format}) to: {file_path}")
return None
+ # Return report string
return report
def generate_quality_report(
@@ -96,18 +183,37 @@ class ReportGenerator:
quality_metrics: Dict[str, Any],
file_path: Optional[Union[str, Path]] = None,
**options
- ) -> Union[str, None]:
+ ) -> Optional[str]:
"""
Generate quality assurance report.
+ This method generates a specialized quality assurance report from quality
+ metrics, including an automatic summary with overall score and status.
+
Args:
- quality_metrics: Quality metrics dictionary
- file_path: Optional output file path
- **options: Additional options
-
+ quality_metrics: Quality metrics dictionary containing:
+ - score/overall_score: Overall quality score (0-1)
+ - completeness: Completeness metric (optional)
+ - accuracy: Accuracy metric (optional)
+ - consistency: Consistency metric (optional)
+ - Additional custom metrics
+ file_path: Optional output file path. If None, returns report as string.
+ **options: Additional options passed to generate_report()
+
Returns:
- Report string if file_path not provided, None otherwise
+ Report string if file_path is None, None if file was written
+
+ Example:
+ >>> metrics = {
+ ... "score": 0.85,
+ ... "completeness": 0.90,
+ ... "accuracy": 0.80
+ ... }
+ >>> generator.generate_quality_report(metrics, "quality.html", format="html")
"""
+ self.logger.debug("Generating quality assurance report")
+
+ # Build report data with summary
report_data = {
"title": "Quality Assurance Report",
"generated_at": datetime.now().isoformat(),
@@ -355,8 +461,27 @@ class ReportGenerator:
else:
lines.append(f"{prefix}{key}: {value}")
- def _generate_quality_summary(self, metrics: Dict[str, Any]) -> Dict[str, Any]:
- """Generate quality summary."""
+ def _generate_quality_summary(
+ self,
+ metrics: Dict[str, Any]
+ ) -> Dict[str, Any]:
+ """
+ Generate quality summary from metrics.
+
+ This method creates a summary dictionary from quality metrics including
+ overall score, status (PASS/FAIL), and key quality dimensions.
+
+ Args:
+ metrics: Quality metrics dictionary
+
+ Returns:
+ Dictionary with summary information:
+ - Overall Score: Formatted score (0.00-1.00)
+ - Status: "PASS" if score >= 0.7, "FAIL" otherwise
+ - Completeness: Completeness metric or "N/A"
+ - Accuracy: Accuracy metric or "N/A"
+ - Consistency: Consistency metric or "N/A"
+ """
score = metrics.get("score") or metrics.get("overall_score", 0.0)
return {
diff --git a/semantica/export/vector_exporter.py b/semantica/export/vector_exporter.py
index 1ce5079b..509b7509 100644
--- a/semantica/export/vector_exporter.py
+++ b/semantica/export/vector_exporter.py
@@ -1,8 +1,25 @@
"""
-Vector Exporter for Vector Embeddings Use Cases
+Vector Exporter Module
-Exports vector embeddings and vector data to various formats
-for use with vector stores and embedding systems.
+This module provides comprehensive vector embedding export capabilities for the
+Semantica framework, enabling export to various formats for vector stores and
+embedding systems.
+
+Key Features:
+ - Multiple vector format export (JSON, NumPy, Binary, FAISS)
+ - Vector store integration (Pinecone, Weaviate, Qdrant, FAISS)
+ - Metadata and document association
+ - Batch vector export
+ - Multi-dimensional vector support
+
+Example Usage:
+ >>> from semantica.export import VectorExporter
+ >>> exporter = VectorExporter(format="json", include_metadata=True)
+ >>> exporter.export(vectors, "vectors.json")
+ >>> exporter.export_for_vector_store(vectors, "pinecone.json", vector_store_type="pinecone")
+
+Author: Semantica Contributors
+License: MIT
"""
from typing import Any, Dict, List, Optional, Union
@@ -19,32 +36,59 @@ class VectorExporter:
"""
Vector exporter for embeddings and vector data.
- • Exports vector embeddings to various formats
- • Supports JSON, NumPy, and binary formats
- • Handles metadata and document associations
- • Generates vector store import formats
- • Supports batch vector export
- • Handles multi-dimensional vectors
+ This class provides comprehensive vector embedding export functionality for
+ various formats and vector store systems.
+
+ Features:
+ - Multiple vector format export (JSON, NumPy, Binary, FAISS)
+ - Vector store integration (Pinecone, Weaviate, Qdrant, FAISS)
+ - Metadata and document association
+ - Batch vector export
+ - Multi-dimensional vector support
+
+ Example Usage:
+ >>> exporter = VectorExporter(
+ ... format="json",
+ ... include_metadata=True,
+ ... include_text=True
+ ... )
+ >>> exporter.export(vectors, "vectors.json")
"""
- def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ def __init__(
+ self,
+ format: str = "json",
+ include_metadata: bool = True,
+ include_text: bool = True,
+ config: Optional[Dict[str, Any]] = None,
+ **kwargs
+ ):
"""
Initialize vector exporter.
+ Sets up the exporter with specified format and inclusion options.
+
Args:
- config: Configuration dictionary
- **kwargs: Additional configuration options:
- - format: Export format ('json', 'numpy', 'binary', 'faiss')
- - include_metadata: Include metadata (default: True)
- - include_text: Include original text (default: True)
+ format: Default export format - 'json', 'numpy', 'binary', or 'faiss'
+ (default: 'json')
+ include_metadata: Whether to include metadata in export (default: True)
+ include_text: Whether to include original text in export (default: True)
+ config: Optional configuration dictionary (merged with kwargs)
+ **kwargs: Additional configuration options
"""
self.logger = get_logger("vector_exporter")
self.config = config or {}
self.config.update(kwargs)
- self.format = self.config.get("format", "json")
- self.include_metadata = self.config.get("include_metadata", True)
- self.include_text = self.config.get("include_text", True)
+ # Vector export configuration
+ self.format = format
+ self.include_metadata = include_metadata
+ self.include_text = include_text
+
+ self.logger.debug(
+ f"Vector exporter initialized: format={format}, "
+ f"include_metadata={include_metadata}, include_text={include_text}"
+ )
def export(
self,
@@ -54,20 +98,48 @@ class VectorExporter:
**options
) -> None:
"""
- Export vectors to file.
+ Export vectors to file in specified format.
+
+ This method exports vector embeddings to various formats suitable for
+ different use cases (JSON for human-readable, NumPy for Python, FAISS for
+ similarity search, etc.).
+
+ Supported Formats:
+ - "json": JSON format (human-readable, includes metadata)
+ - "numpy": NumPy compressed format (.npz)
+ - "binary": Binary format (raw float32 array)
+ - "faiss": FAISS index format (for similarity search)
Args:
- vectors: List of vector dictionaries or dict with 'vectors' key
+ vectors: Vector data:
+ - List of dicts: Each dict with 'id', 'vector', 'text', 'metadata'
+ - Dict: With 'vectors' key containing list, and optional 'metadata'
file_path: Output file path
- format: Export format ('json', 'numpy', 'binary', 'faiss')
- **options: Additional options
+ format: Export format - 'json', 'numpy', 'binary', or 'faiss'
+ (default: self.format)
+ **options: Additional format-specific options
+
+ Raises:
+ ValidationError: If format is unsupported
+
+ Example:
+ >>> vectors = [
+ ... {"id": "v1", "vector": [0.1, 0.2, ...], "text": "text1"},
+ ... {"id": "v2", "vector": [0.3, 0.4, ...], "text": "text2"}
+ ... ]
+ >>> exporter.export(vectors, "vectors.json", format="json")
"""
file_path = Path(file_path)
ensure_directory(file_path.parent)
export_format = format or self.format
- # Normalize input
+ self.logger.debug(
+ f"Exporting vectors to {export_format}: {file_path}, "
+ f"include_metadata={self.include_metadata}, include_text={self.include_text}"
+ )
+
+ # Normalize input data
if isinstance(vectors, dict):
vector_list = vectors.get("vectors", [])
metadata = vectors.get("metadata", {})
@@ -75,6 +147,7 @@ class VectorExporter:
vector_list = vectors
metadata = {}
+ # Export based on format
if export_format == "json":
self._export_json(vector_list, file_path, metadata, **options)
elif export_format == "numpy":
@@ -84,7 +157,10 @@ class VectorExporter:
elif export_format == "faiss":
self._export_faiss(vector_list, file_path, **options)
else:
- raise ValidationError(f"Unsupported vector format: {export_format}")
+ raise ValidationError(
+ f"Unsupported vector format: {export_format}. "
+ "Supported formats: json, numpy, binary, faiss"
+ )
self.logger.info(f"Exported vectors ({export_format}) to: {file_path}")
@@ -113,7 +189,19 @@ class VectorExporter:
metadata: Dict[str, Any],
**options
) -> None:
- """Export to JSON format."""
+ """
+ Export vectors to JSON format.
+
+ This method exports vectors to JSON format with metadata, text, and
+ vector data. Suitable for human-readable export and integration with
+ systems that consume JSON.
+
+ Args:
+ vectors: List of vector dictionaries
+ file_path: Output JSON file path
+ metadata: Additional metadata to include in export
+ **options: Additional options (unused)
+ """
export_data = {
"vectors": [],
"metadata": {
@@ -129,13 +217,15 @@ class VectorExporter:
"vector": vec_data.get("vector") or vec_data.get("embedding", [])
}
+ # Add text if requested and available
if self.include_text and "text" in vec_data:
vector_entry["text"] = vec_data["text"]
+ # Add metadata if requested and available
if self.include_metadata and "metadata" in vec_data:
vector_entry["metadata"] = vec_data["metadata"]
- # Determine dimension
+ # Determine dimension from first vector
vector = vector_entry["vector"]
if isinstance(vector, list) and len(vector) > 0:
if export_data["metadata"]["dimension"] is None:
@@ -144,6 +234,11 @@ class VectorExporter:
export_data["vectors"].append(vector_entry)
write_json_file(export_data, file_path, indent=2)
+
+ self.logger.debug(
+ f"Exported {len(vectors)} vector(s) to JSON: "
+ f"dimension={export_data['metadata']['dimension']}"
+ )
def _export_numpy(
self,
@@ -151,13 +246,29 @@ class VectorExporter:
file_path: Path,
**options
) -> None:
- """Export to NumPy format."""
+ """
+ Export vectors to NumPy format.
+
+ This method exports vectors to NumPy compressed format (.npz) with
+ optional text and metadata arrays. Also saves metadata as separate JSON.
+
+ Args:
+ vectors: List of vector dictionaries
+ file_path: Output .npz file path
+ **options: Additional options (unused)
+
+ Raises:
+ ImportError: If NumPy is not installed
+ ValidationError: If no vectors to export
+ """
try:
import numpy as np
except ImportError:
- raise ImportError("NumPy not installed. Install with: pip install numpy")
+ raise ImportError(
+ "NumPy not installed. Install with: pip install numpy"
+ )
- # Extract vectors
+ # Extract vectors and associated data
vector_list = []
ids = []
texts = []
@@ -169,41 +280,55 @@ class VectorExporter:
vector_list.append(vector)
ids.append(vec_data.get("id") or vec_data.get("vector_id", ""))
+ # Add text if requested
if self.include_text and "text" in vec_data:
texts.append(vec_data["text"])
else:
texts.append(None)
+ # Add metadata if requested
if self.include_metadata and "metadata" in vec_data:
metadata_list.append(vec_data["metadata"])
else:
metadata_list.append(None)
if not vector_list:
- raise ValidationError("No vectors to export")
+ raise ValidationError("No vectors to export. Vector list is empty.")
# Convert to numpy array
vector_array = np.array(vector_list)
- # Save as .npz (compressed numpy format)
+ # Build save dictionary
save_dict = {"vectors": vector_array, "ids": np.array(ids)}
+ # Add texts if any present
if any(t for t in texts if t):
save_dict["texts"] = np.array(texts, dtype=object)
+ # Add metadata if any present
if any(m for m in metadata_list if m):
save_dict["metadata"] = np.array(metadata_list, dtype=object)
+ # Save as compressed NumPy format
np.savez_compressed(file_path, **save_dict)
- # Also save metadata separately as JSON
+ # Save metadata separately as JSON for easy access
metadata_file = file_path.parent / f"{file_path.stem}_metadata.json"
metadata = {
"vector_count": len(vector_list),
- "dimension": vector_array.shape[1] if len(vector_array.shape) > 1 else vector_array.shape[0],
+ "dimension": (
+ vector_array.shape[1]
+ if len(vector_array.shape) > 1
+ else vector_array.shape[0]
+ ),
"shape": list(vector_array.shape)
}
write_json_file(metadata, metadata_file)
+
+ self.logger.debug(
+ f"Exported {len(vector_list)} vector(s) to NumPy: "
+ f"shape={vector_array.shape}, metadata={metadata_file}"
+ )
def _export_binary(
self,
@@ -247,16 +372,38 @@ class VectorExporter:
self,
vectors: List[Dict[str, Any]],
file_path: Path,
+ normalize: bool = False,
**options
) -> None:
- """Export to FAISS index format."""
+ """
+ Export vectors to FAISS index format.
+
+ This method exports vectors to FAISS index format for efficient similarity
+ search. Creates a FAISS index and saves it along with ID mapping.
+
+ Args:
+ vectors: List of vector dictionaries
+ file_path: Output FAISS index file path
+ normalize: Whether to normalize vectors before indexing (default: False)
+ **options: Additional options (unused)
+
+ Raises:
+ ImportError: If FAISS is not installed
+ ValidationError: If no vectors to export
+
+ Example:
+ >>> vectors = [{"id": "v1", "vector": [0.1, 0.2, ...]}, ...]
+ >>> exporter._export_faiss(vectors, "index.faiss", normalize=True)
+ """
try:
import faiss
import numpy as np
except ImportError:
- raise ImportError("FAISS not installed. Install with: pip install faiss-cpu or faiss-gpu")
+ raise ImportError(
+ "FAISS not installed. Install with: pip install faiss-cpu or faiss-gpu"
+ )
- # Extract vectors
+ # Extract vectors and IDs
vector_list = []
ids = []
@@ -267,26 +414,32 @@ class VectorExporter:
ids.append(vec_data.get("id") or vec_data.get("vector_id", ""))
if not vector_list:
- raise ValidationError("No vectors to export")
+ raise ValidationError("No vectors to export. Vector list is empty.")
# Convert to numpy array
vector_array = np.array(vector_list, dtype=np.float32)
-
- # Create FAISS index
dimension = vector_array.shape[1]
+
+ self.logger.debug(
+ f"Creating FAISS index: {len(vector_list)} vector(s), "
+ f"dimension={dimension}, normalize={normalize}"
+ )
+
+ # Create FAISS index (L2 distance)
index = faiss.IndexFlatL2(dimension)
# Normalize vectors if requested
- if options.get("normalize", False):
+ if normalize:
faiss.normalize_L2(vector_array)
+ self.logger.debug("Normalized vectors for FAISS index")
# Add vectors to index
index.add(vector_array)
- # Save index
+ # Save FAISS index
faiss.write_index(index, str(file_path))
- # Save ID mapping
+ # Save ID mapping for vector retrieval
id_file = file_path.parent / f"{file_path.stem}_ids.json"
id_mapping = {
"ids": ids,
@@ -294,6 +447,10 @@ class VectorExporter:
"dimension": dimension
}
write_json_file(id_mapping, id_file)
+
+ self.logger.debug(
+ f"Exported FAISS index: {file_path}, ID mapping={id_file}"
+ )
def export_for_vector_store(
self,
diff --git a/semantica/export/yaml_exporter.py b/semantica/export/yaml_exporter.py
index ab897073..7a072f96 100644
--- a/semantica/export/yaml_exporter.py
+++ b/semantica/export/yaml_exporter.py
@@ -1,9 +1,24 @@
"""
-YAML Exporter for Semantic Networks
+YAML Exporter Module
-Exports semantic networks (entities, relationships, triples) to YAML format
-for human-readable representation and intermediate processing in the
-6-stage ontology generation pipeline.
+This module provides comprehensive YAML export capabilities for the Semantica
+framework, enabling human-readable export of semantic networks and ontologies.
+
+Key Features:
+ - Semantic network export to YAML
+ - Ontology schema export for human editing
+ - Pipeline-ready YAML format
+ - Entity, relationship, and triple export
+ - Class and property definition export
+
+Example Usage:
+ >>> from semantica.export import SemanticNetworkYAMLExporter
+ >>> exporter = SemanticNetworkYAMLExporter()
+ >>> exporter.export(semantic_network, "network.yaml")
+ >>> exporter.export_for_pipeline(extracted_data, pipeline_stage=2)
+
+Author: Semantica Contributors
+License: MIT
"""
from typing import Any, Dict, List, Optional, Union
@@ -19,6 +34,10 @@ class SemanticNetworkYAMLExporter:
"""
Exports semantic networks to YAML format.
+ This class provides YAML export functionality for semantic networks, enabling
+ human-readable representation and intermediate processing in ontology
+ generation pipelines.
+
Part of the 6-stage ontology generation pipeline:
1. Document parsing
2. Semantic network extraction (YAML) ← This module
@@ -26,15 +45,23 @@ class SemanticNetworkYAMLExporter:
4. Type mapping
5. Hierarchy building
6. TTL export
+
+ Example Usage:
+ >>> exporter = SemanticNetworkYAMLExporter()
+ >>> exporter.export(semantic_network, "network.yaml")
"""
def __init__(self, **config):
"""
Initialize YAML exporter.
- • Setup YAML serialization
- • Configure output formatting
- • Initialize schema templates
+ Sets up the exporter with YAML serialization support.
+
+ Args:
+ **config: Configuration options (currently unused)
+
+ Raises:
+ ImportError: If PyYAML is not installed
"""
self.logger = get_logger("yaml_exporter")
self.config = config or {}
@@ -43,16 +70,41 @@ class SemanticNetworkYAMLExporter:
import yaml
self.yaml = yaml
except ImportError:
- raise ImportError("PyYAML not installed. Install with: pip install pyyaml")
+ raise ImportError(
+ "PyYAML not installed. Install with: pip install pyyaml"
+ )
+
+ self.logger.debug("Semantic network YAML exporter initialized")
- def export_semantic_network(self, semantic_network: Dict[str, Any], **options) -> str:
+ def export_semantic_network(
+ self,
+ semantic_network: Dict[str, Any],
+ **options
+ ) -> str:
"""
- Export semantic network to YAML.
+ Export semantic network to YAML string.
+
+ This method converts a semantic network (entities, relationships, triples)
+ to YAML format with metadata and provenance information.
- • Structure entities and relationships
- • Format as YAML document
- • Include metadata and provenance
- • Return YAML string
+ Args:
+ semantic_network: Semantic network dictionary containing:
+ - entities: List of entity dictionaries
+ - relationships: List of relationship dictionaries
+ - triples: List of triple dictionaries (optional)
+ - metadata: Metadata dictionary (optional)
+ **options: Additional export options (unused)
+
+ Returns:
+ String containing YAML representation of semantic network
+
+ Example:
+ >>> network = {
+ ... "entities": [...],
+ ... "relationships": [...],
+ ... "triples": [...]
+ ... }
+ >>> yaml_str = exporter.export_semantic_network(network)
"""
yaml_data = {
"metadata": {
@@ -65,7 +117,11 @@ class SemanticNetworkYAMLExporter:
"triples": semantic_network.get("triples", [])
}
- return self.yaml.dump(yaml_data, default_flow_style=False, sort_keys=False)
+ return self.yaml.dump(
+ yaml_data,
+ default_flow_style=False,
+ sort_keys=False
+ )
def export(
self,