Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: Add OWL and Vector exporters, remove Neo4j exporter

KaifAhmad1ec813295e32e
diff --git a/libs/semantica/export/__init__.py b/libs/semantica/export/__init__.py
index 74b02d4a..b929871c 100644
--- a/libs/semantica/export/__init__.py
+++ b/libs/semantica/export/__init__.py
@@ -12,9 +12,34 @@ Exports:
- ReportGenerator: Report generation
"""
-# from .rdf_exporter import RDFExporter
-# from .json_exporter import JSONExporter
-# from .csv_exporter import CSVExporter
-# from .graph_exporter import GraphExporter
-# from .yaml_exporter import SemanticNetworkYAMLExporter, YAMLSchemaExporter
-# from .report_generator import ReportGenerator
+from .rdf_exporter import (
+ RDFExporter,
+ RDFSerializer,
+ RDFValidator,
+ NamespaceManager,
+)
+from .json_exporter import JSONExporter
+from .csv_exporter import CSVExporter
+from .graph_exporter import GraphExporter
+from .yaml_exporter import (
+ SemanticNetworkYAMLExporter,
+ YAMLSchemaExporter,
+)
+from .report_generator import ReportGenerator
+from .owl_exporter import OWLExporter
+from .vector_exporter import VectorExporter
+
+__all__ = [
+ "RDFExporter",
+ "RDFSerializer",
+ "RDFValidator",
+ "NamespaceManager",
+ "JSONExporter",
+ "CSVExporter",
+ "GraphExporter",
+ "SemanticNetworkYAMLExporter",
+ "YAMLSchemaExporter",
+ "ReportGenerator",
+ "OWLExporter",
+ "VectorExporter",
+]
diff --git a/libs/semantica/export/csv_exporter.py b/libs/semantica/export/csv_exporter.py
index e7003043..e61bd8c3 100644
--- a/libs/semantica/export/csv_exporter.py
+++ b/libs/semantica/export/csv_exporter.py
@@ -5,10 +5,236 @@ This module provides CSV export capabilities
for tabular data and structured information.
"""
-# TODO: Implement CSV export
-# - CSV export functionality
-# - Tabular data serialization
-# - Metadata and schema export
-# - Performance optimization
-# - Error handling and recovery
-# - Advanced CSV features
+from typing import Any, Dict, List, Optional, Union
+from pathlib import Path
+import csv
+from collections import defaultdict
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..utils.helpers import ensure_directory
+
+
+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
+ """
+
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize CSV exporter.
+
+ 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)
+ """
+ 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)
+
+ def export(
+ self,
+ data: Union[List[Dict[str, Any]], Dict[str, Any]],
+ file_path: Union[str, Path],
+ **options
+ ) -> None:
+ """
+ Export data to CSV file.
+
+ 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')
+ """
+ file_path = Path(file_path)
+ ensure_directory(file_path.parent)
+
+ # Handle different data structures
+ if isinstance(data, dict):
+ # Export each key as separate CSV file
+ 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)
+ elif isinstance(data, list):
+ # Single CSV file
+ self._write_csv(data, file_path, **options)
+ else:
+ raise ValidationError(f"Unsupported data type: {type(data)}")
+
+ self.logger.info(f"Exported CSV to: {file_path}")
+
+ def export_entities(
+ self,
+ entities: List[Dict[str, Any]],
+ file_path: Union[str, Path],
+ **options
+ ) -> None:
+ """
+ Export entities to CSV.
+
+ Args:
+ entities: List of entity dictionaries
+ file_path: Output file path
+ **options: Additional options
+ """
+ if not entities:
+ raise ValidationError("No entities to export")
+
+ # Normalize entity data
+ normalized_entities = []
+ for entity in entities:
+ normalized = {
+ "id": entity.get("id") or entity.get("entity_id", ""),
+ "text": entity.get("text") or entity.get("label") or entity.get("name", ""),
+ "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
+ if "metadata" in entity:
+ import json
+ normalized["metadata"] = json.dumps(entity["metadata"])
+
+ normalized_entities.append(normalized)
+
+ self._write_csv(normalized_entities, file_path, **options)
+
+ def export_relationships(
+ self,
+ relationships: List[Dict[str, Any]],
+ file_path: Union[str, Path],
+ **options
+ ) -> None:
+ """
+ Export relationships to CSV.
+
+ Args:
+ relationships: List of relationship dictionaries
+ file_path: Output file path
+ **options: Additional options
+ """
+ if not relationships:
+ raise ValidationError("No relationships to export")
+
+ # Normalize relationship data
+ normalized_rels = []
+ for rel in relationships:
+ normalized = {
+ "id": rel.get("id", ""),
+ "source_id": rel.get("source_id") or rel.get("source", ""),
+ "target_id": rel.get("target_id") or rel.get("target", ""),
+ "type": rel.get("type") or rel.get("relationship_type", ""),
+ "confidence": rel.get("confidence", ""),
+ }
+
+ # Add metadata as JSON string
+ if "metadata" in rel:
+ import json
+ normalized["metadata"] = json.dumps(rel["metadata"])
+
+ normalized_rels.append(normalized)
+
+ self._write_csv(normalized_rels, file_path, **options)
+
+ def export_knowledge_graph(
+ self,
+ knowledge_graph: Dict[str, Any],
+ base_path: Union[str, Path],
+ **options
+ ) -> None:
+ """
+ Export knowledge graph to CSV files.
+
+ Args:
+ knowledge_graph: Knowledge graph dictionary
+ base_path: Base path for output files
+ **options: Additional options
+ """
+ base_path = Path(base_path)
+
+ # 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)
+
+ # 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)
+
+ # 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)
+
+ # 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)
+
+ def _write_csv(
+ self,
+ data: List[Dict[str, Any]],
+ file_path: Path,
+ **options
+ ) -> None:
+ """Write data to CSV file."""
+ if not data:
+ raise ValidationError("No data to write")
+
+ fieldnames = options.get("fieldnames")
+ if not fieldnames:
+ # Get all unique keys from data
+ fieldnames = set()
+ for item in data:
+ fieldnames.update(item.keys())
+ fieldnames = sorted(list(fieldnames))
+
+ mode = options.get("mode", "w")
+
+ try:
+ with open(file_path, mode, newline='', encoding=self.encoding) as f:
+ writer = csv.DictWriter(
+ f,
+ fieldnames=fieldnames,
+ delimiter=self.delimiter,
+ extrasaction='ignore'
+ )
+
+ if self.include_header and mode == 'w':
+ writer.writeheader()
+
+ for row in data:
+ # Convert values to strings
+ row_str = {
+ k: str(v) if v is not None else ""
+ for k, v in row.items()
+ if k in fieldnames
+ }
+ writer.writerow(row_str)
+
+ except Exception as e:
+ raise ProcessingError(f"Failed to write CSV file: {e}") from e
diff --git a/libs/semantica/export/graph_exporter.py b/libs/semantica/export/graph_exporter.py
index bf543827..b767241c 100644
--- a/libs/semantica/export/graph_exporter.py
+++ b/libs/semantica/export/graph_exporter.py
@@ -5,10 +5,296 @@ This module provides graph format export capabilities
for knowledge graphs and network data.
"""
-# TODO: Implement graph export
-# - Graph format export functionality
-# - Network data serialization
-# - Graph visualization export
-# - Performance optimization
-# - Error handling and recovery
-# - Advanced graph features
+from typing import Any, Dict, List, Optional, Union
+from pathlib import Path
+import json
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..utils.helpers import ensure_directory
+
+
+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
+ """
+
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize graph exporter.
+
+ Args:
+ config: Configuration dictionary
+ **kwargs: Additional configuration options:
+ - format: Export format ('graphml', 'gexf', 'json', 'dot')
+ - include_attributes: Include node/edge attributes (default: True)
+ """
+ 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)
+
+ def export(
+ self,
+ graph_data: Dict[str, Any],
+ file_path: Union[str, Path],
+ format: Optional[str] = None,
+ **options
+ ) -> None:
+ """
+ Export graph to file.
+
+ Args:
+ graph_data: Graph data dictionary
+ file_path: Output file path
+ format: Export format ('graphml', 'gexf', 'json', 'dot')
+ **options: Additional options
+ """
+ file_path = Path(file_path)
+ ensure_directory(file_path.parent)
+
+ export_format = format or self.format
+
+ if export_format == "json":
+ self._export_json(graph_data, file_path, **options)
+ elif export_format == "graphml":
+ self._export_graphml(graph_data, file_path, **options)
+ elif export_format == "gexf":
+ self._export_gexf(graph_data, file_path, **options)
+ elif export_format == "dot":
+ self._export_dot(graph_data, file_path, **options)
+ else:
+ raise ValidationError(f"Unsupported graph format: {export_format}")
+
+ self.logger.info(f"Exported graph ({export_format}) to: {file_path}")
+
+ def export_knowledge_graph(
+ self,
+ knowledge_graph: Dict[str, Any],
+ file_path: Union[str, Path],
+ format: Optional[str] = None,
+ **options
+ ) -> None:
+ """
+ Export knowledge graph to graph format.
+
+ Args:
+ knowledge_graph: Knowledge graph dictionary
+ file_path: Output file path
+ format: Export format
+ **options: Additional options
+ """
+ # Convert knowledge graph to graph format
+ graph_data = self._convert_kg_to_graph(knowledge_graph)
+ 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."""
+ nodes = []
+ edges = []
+
+ # Convert entities to nodes
+ entities = kg.get("entities", [])
+ 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", ""),
+ "type": entity.get("type") or entity.get("entity_type", "entity")
+ }
+
+ if self.include_attributes:
+ node["attributes"] = {
+ "confidence": entity.get("confidence", 1.0),
+ **entity.get("metadata", {})
+ }
+
+ nodes.append(node)
+
+ # Convert relationships to edges
+ relationships = kg.get("relationships", [])
+ for rel in relationships:
+ edge = {
+ "source": rel.get("source_id") or rel.get("source"),
+ "target": rel.get("target_id") or rel.get("target"),
+ "type": rel.get("type") or rel.get("relationship_type", "related_to")
+ }
+
+ if self.include_attributes:
+ edge["attributes"] = {
+ "confidence": rel.get("confidence", 1.0),
+ **rel.get("metadata", {})
+ }
+
+ edges.append(edge)
+
+ 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."""
+ 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."""
+ 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"')
+ lines.append(' xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns')
+ lines.append(' http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">')
+ lines.append("")
+
+ # Define attributes
+ 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
+ lines.append(' <graph id="G" edgedefault="directed">')
+ lines.append("")
+
+ # Nodes
+ nodes = graph_data.get("nodes", [])
+ for node in nodes:
+ node_id = node.get("id", "")
+ label = node.get("label", "")
+ node_type = node.get("type", "")
+
+ lines.append(f' <node id="{node_id}">')
+ lines.append(f' <data key="label">{label}</data>')
+ lines.append(f' <data key="type">{node_type}</data>')
+
+ if self.include_attributes and "attributes" in node:
+ attrs = node["attributes"]
+ if "confidence" in attrs:
+ lines.append(f' <data key="confidence">{attrs["confidence"]}</data>')
+
+ lines.append(" </node>")
+
+ lines.append("")
+
+ # Edges
+ edges = graph_data.get("edges", [])
+ for edge in edges:
+ source = edge.get("source", "")
+ target = edge.get("target", "")
+ edge_type = edge.get("type", "")
+
+ lines.append(f' <edge source="{source}" target="{target}">')
+ lines.append(f' <data key="label">{edge_type}</data>')
+
+ if self.include_attributes and "attributes" in edge:
+ attrs = edge["attributes"]
+ if "confidence" in attrs:
+ lines.append(f' <data key="confidence">{attrs["confidence"]}</data>')
+
+ lines.append(" </edge>")
+
+ lines.append(" </graph>")
+ lines.append("</graphml>")
+
+ with open(file_path, "w", encoding="utf-8") as f:
+ f.write("\n".join(lines))
+
+ def _export_gexf(self, graph_data: Dict[str, Any], file_path: Path, **options) -> None:
+ """Export to GEXF format."""
+ 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
+ nodes = graph_data.get("nodes", [])
+ for node in nodes:
+ node_id = node.get("id", "")
+ label = node.get("label", "")
+
+ lines.append(f' <node id="{node_id}" label="{label}">')
+
+ if self.include_attributes and "attributes" in node:
+ lines.append(" <attvalues>")
+ attrs = node["attributes"]
+ for key, value in attrs.items():
+ lines.append(f' <attvalue for="{key}" value="{value}"/>')
+ lines.append(" </attvalues>")
+
+ lines.append(" </node>")
+
+ lines.append(" </nodes>")
+ lines.append(" <edges>")
+
+ # 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}">')
+
+ if self.include_attributes and "attributes" in edge:
+ lines.append(" <attvalues>")
+ attrs = edge["attributes"]
+ for key, value in attrs.items():
+ lines.append(f' <attvalue for="{key}" value="{value}"/>')
+ lines.append(" </attvalues>")
+
+ lines.append(" </edge>")
+
+ lines.append(" </edges>")
+ lines.append(" </graph>")
+ lines.append("</gexf>")
+
+ with open(file_path, "w", encoding="utf-8") as f:
+ f.write("\n".join(lines))
+
+ 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;")
+ lines.append("")
+
+ # Nodes
+ nodes = graph_data.get("nodes", [])
+ for node in nodes:
+ node_id = node.get("id", "").replace('"', '\\"')
+ label = node.get("label", "").replace('"', '\\"')
+ node_type = node.get("type", "")
+
+ attributes = [f'label="{label}"']
+ if node_type:
+ attributes.append(f'type="{node_type}"')
+
+ attrs_str = ", ".join(attributes)
+ lines.append(f' "{node_id}" [{attrs_str}];')
+
+ lines.append("")
+
+ # Edges
+ edges = graph_data.get("edges", [])
+ for edge in edges:
+ source = edge.get("source", "").replace('"', '\\"')
+ target = edge.get("target", "").replace('"', '\\"')
+ edge_type = edge.get("type", "").replace('"', '\\"')
+
+ attributes = [f'label="{edge_type}"']
+ attrs_str = ", ".join(attributes)
+ lines.append(f' "{source}" -> "{target}" [{attrs_str}];')
+
+ lines.append("}")
+
+ with open(file_path, "w", encoding="utf-8") as f:
+ f.write("\n".join(lines))
diff --git a/libs/semantica/export/json_exporter.py b/libs/semantica/export/json_exporter.py
index 294f36a0..a8041b9e 100644
--- a/libs/semantica/export/json_exporter.py
+++ b/libs/semantica/export/json_exporter.py
@@ -5,10 +5,308 @@ This module provides JSON and JSON-LD export capabilities
for knowledge graphs and semantic data.
"""
-# TODO: Implement JSON export
-# - JSON and JSON-LD export functionality
-# - Knowledge graph serialization
-# - Metadata and provenance export
-# - Performance optimization
-# - Error handling and recovery
-# - Advanced JSON features
+from typing import Any, Dict, List, Optional, Union
+from pathlib import Path
+import json
+from datetime import datetime
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..utils.helpers import ensure_directory, write_json_file
+
+
+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
+ """
+
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize JSON exporter.
+
+ 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')
+ """
+ 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")
+
+ def export(
+ self,
+ data: Any,
+ file_path: Union[str, Path],
+ format: Optional[str] = None,
+ **options
+ ) -> None:
+ """
+ Export data to JSON file.
+
+ 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)
+ """
+ file_path = Path(file_path)
+ ensure_directory(file_path.parent)
+
+ export_format = format or self.format
+
+ if export_format == "json-ld":
+ json_data = self._convert_to_jsonld(data, **options)
+ else:
+ json_data = self._convert_to_json(data, **options)
+
+ write_json_file(
+ json_data,
+ file_path,
+ indent=self.indent,
+ ensure_ascii=self.ensure_ascii
+ )
+
+ self.logger.info(f"Exported JSON to: {file_path}")
+
+ def export_knowledge_graph(
+ self,
+ knowledge_graph: Dict[str, Any],
+ file_path: Union[str, Path],
+ format: Optional[str] = None,
+ **options
+ ) -> None:
+ """
+ Export knowledge graph to JSON/JSON-LD.
+
+ Args:
+ knowledge_graph: Knowledge graph dictionary
+ file_path: Output file path
+ format: Export format ('json', 'json-ld')
+ **options: Additional options
+ """
+ export_format = format or self.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)
+
+ self.export(json_data, file_path, format=export_format, **options)
+
+ def export_entities(
+ self,
+ entities: List[Dict[str, Any]],
+ file_path: Union[str, Path],
+ **options
+ ) -> None:
+ """
+ Export entities to JSON.
+
+ Args:
+ entities: List of entity dictionaries
+ file_path: Output file path
+ **options: Additional options
+ """
+ json_data = {
+ "@context": {
+ "@vocab": "https://semantica.dev/vocab/",
+ "entities": {
+ "@id": "semantica:entities",
+ "@container": "@list"
+ }
+ },
+ "entities": entities,
+ "metadata": {
+ "exported_at": datetime.now().isoformat(),
+ "entity_count": len(entities),
+ **options.get("metadata", {})
+ }
+ }
+
+ self.export(json_data, file_path, **options)
+
+ def export_relationships(
+ self,
+ relationships: List[Dict[str, Any]],
+ file_path: Union[str, Path],
+ **options
+ ) -> None:
+ """
+ Export relationships to JSON.
+
+ Args:
+ relationships: List of relationship dictionaries
+ file_path: Output file path
+ **options: Additional options
+ """
+ json_data = {
+ "@context": {
+ "@vocab": "https://semantica.dev/vocab/",
+ "relationships": {
+ "@id": "semantica:relationships",
+ "@container": "@list"
+ }
+ },
+ "relationships": relationships,
+ "metadata": {
+ "exported_at": datetime.now().isoformat(),
+ "relationship_count": len(relationships),
+ **options.get("metadata", {})
+ }
+ }
+
+ self.export(json_data, file_path, **options)
+
+ def _convert_to_json(self, data: Any, **options) -> Dict[str, Any]:
+ """Convert data to JSON format."""
+ if isinstance(data, dict):
+ result = dict(data)
+
+ # Add metadata if requested
+ if options.get("include_metadata", True):
+ if "metadata" not in result:
+ result["metadata"] = {}
+ result["metadata"]["exported_at"] = datetime.now().isoformat()
+
+ return result
+ elif isinstance(data, list):
+ return {
+ "data": data,
+ "count": len(data),
+ "metadata": {
+ "exported_at": datetime.now().isoformat(),
+ **options.get("metadata", {})
+ }
+ }
+ else:
+ return {"value": data}
+
+ def _convert_to_jsonld(self, data: Any, **options) -> Dict[str, Any]:
+ """Convert data to JSON-LD format."""
+ jsonld = {
+ "@context": {
+ "@vocab": "https://semantica.dev/vocab/",
+ "semantica": "https://semantica.dev/ns#"
+ }
+ }
+
+ if isinstance(data, dict):
+ if "entities" in data or "relationships" in data:
+ # Knowledge graph structure
+ jsonld.update(self._convert_kg_to_jsonld(data, **options))
+ else:
+ # Generic data
+ jsonld["@graph"] = [data]
+ elif isinstance(data, list):
+ jsonld["@graph"] = data
+ else:
+ jsonld["@value"] = data
+
+ # Add metadata
+ jsonld["@id"] = f"https://semantica.dev/data/{datetime.now().isoformat()}"
+ jsonld["semantica:exportedAt"] = datetime.now().isoformat()
+
+ return jsonld
+
+ def _convert_kg_to_json(self, kg: Dict[str, Any], **options) -> Dict[str, Any]:
+ """Convert knowledge graph to JSON."""
+ result = {
+ "entities": kg.get("entities", []),
+ "relationships": kg.get("relationships", []),
+ "nodes": kg.get("nodes", []),
+ "edges": kg.get("edges", []),
+ "metadata": {
+ "exported_at": datetime.now().isoformat(),
+ **kg.get("metadata", {}),
+ **options.get("metadata", {})
+ }
+ }
+
+ # Add statistics if available
+ if "statistics" in kg:
+ result["statistics"] = kg["statistics"]
+
+ return result
+
+ def _convert_kg_to_jsonld(self, kg: Dict[str, Any], **options) -> Dict[str, Any]:
+ """Convert knowledge graph to JSON-LD."""
+ jsonld = {
+ "@context": {
+ "@vocab": "https://semantica.dev/vocab/",
+ "semantica": "https://semantica.dev/ns#",
+ "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
+ "rdfs": "http://www.w3.org/2000/01/rdf-schema#"
+ },
+ "@id": f"https://semantica.dev/graph/{datetime.now().isoformat()}",
+ "@type": "semantica:KnowledgeGraph"
+ }
+
+ # Convert entities
+ entities = kg.get("entities", [])
+ if entities:
+ jsonld["semantica:entities"] = [
+ self._entity_to_jsonld(e) for e in entities
+ ]
+
+ # Convert relationships
+ relationships = kg.get("relationships", [])
+ if relationships:
+ jsonld["semantica:relationships"] = [
+ self._relationship_to_jsonld(r) for r in relationships
+ ]
+
+ # Add metadata
+ jsonld["semantica:exportedAt"] = datetime.now().isoformat()
+ if "metadata" in kg:
+ jsonld["semantica:metadata"] = kg["metadata"]
+
+ return jsonld
+
+ def _entity_to_jsonld(self, entity: Dict[str, Any]) -> Dict[str, Any]:
+ """Convert entity to JSON-LD format."""
+ jsonld = {
+ "@id": entity.get("id") or f"semantica:entity/{entity.get('text', 'unknown')}",
+ "@type": entity.get("type") or "semantica:Entity",
+ "semantica:text": entity.get("text") or entity.get("label", ""),
+ "semantica:confidence": entity.get("confidence", 1.0)
+ }
+
+ 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."""
+ jsonld = {
+ "@id": rel.get("id") or f"semantica:rel/{rel.get('source_id')}_{rel.get('target_id')}",
+ "@type": "semantica:Relationship",
+ "semantica:type": rel.get("type", "related_to"),
+ "semantica:source": {
+ "@id": rel.get("source_id") or rel.get("source")
+ },
+ "semantica:target": {
+ "@id": rel.get("target_id") or rel.get("target")
+ },
+ "semantica:confidence": rel.get("confidence", 1.0)
+ }
+
+ if "metadata" in rel:
+ jsonld["semantica:metadata"] = rel["metadata"]
+
+ return jsonld
diff --git a/libs/semantica/export/owl_exporter.py b/libs/semantica/export/owl_exporter.py
new file mode 100644
index 00000000..f4934218
--- /dev/null
+++ b/libs/semantica/export/owl_exporter.py
@@ -0,0 +1,332 @@
+"""
+OWL Exporter for Semantic Modeling
+
+Exports ontologies and knowledge graphs to OWL (Web Ontology Language) format
+for semantic modeling and ontology representation.
+"""
+
+from typing import Any, Dict, List, Optional, Union
+from pathlib import Path
+from datetime import datetime
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..utils.helpers import ensure_directory
+
+
+class OWLExporter:
+ """
+ OWL exporter for semantic modeling.
+
+ • 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
+ """
+
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize OWL exporter.
+
+ Args:
+ config: Configuration dictionary
+ **kwargs: Additional configuration options:
+ - ontology_uri: Base ontology URI
+ - version: Ontology version
+ - format: Export format ('owl-xml', 'turtle')
+ """
+ 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")
+
+ def export(
+ self,
+ ontology: Dict[str, Any],
+ file_path: Union[str, Path],
+ format: Optional[str] = None,
+ **options
+ ) -> None:
+ """
+ Export ontology to OWL format.
+
+ Args:
+ ontology: Ontology dictionary with classes, properties, etc.
+ file_path: Output file path
+ format: Export format ('owl-xml', 'turtle')
+ **options: Additional options
+ """
+ file_path = Path(file_path)
+ ensure_directory(file_path.parent)
+
+ export_format = format or self.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}")
+
+ encoding = options.get("encoding", "utf-8")
+ with open(file_path, "w", encoding=encoding) as f:
+ f.write(owl_content)
+
+ self.logger.info(f"Exported OWL ({export_format}) to: {file_path}")
+
+ def export_ontology(
+ self,
+ ontology: Dict[str, Any],
+ file_path: Union[str, Path],
+ **options
+ ) -> None:
+ """
+ Export complete ontology to OWL.
+
+ Args:
+ ontology: Ontology dictionary
+ file_path: Output file path
+ **options: Additional options
+ """
+ self.export(ontology, file_path, **options)
+
+ def _export_owl_xml(self, ontology: Dict[str, Any], **options) -> str:
+ """Export to OWL-XML format."""
+ ontology_uri = ontology.get("uri") or self.ontology_uri
+ ontology_name = ontology.get("name", "SemanticaOntology")
+ version = ontology.get("version") or self.version
+
+ lines = ['<?xml version="1.0"?>']
+ lines.append('<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"')
+ lines.append(' xmlns:owl="http://www.w3.org/2002/07/owl#"')
+ lines.append(' xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"')
+ lines.append(' xmlns:xsd="http://www.w3.org/2001/XMLSchema#">')
+ lines.append("")
+
+ # Ontology declaration
+ lines.append(f' <owl:Ontology rdf:about="{ontology_uri}">')
+ lines.append(f' <rdfs:label>{ontology_name}</rdfs:label>')
+ lines.append(f' <owl:versionInfo>{version}</owl:versionInfo>')
+ if ontology.get("description"):
+ lines.append(f' <rdfs:comment>{ontology.get("description")}</rdfs:comment>')
+ lines.append(" </owl:Ontology>")
+ lines.append("")
+
+ # Classes
+ classes = ontology.get("classes", [])
+ for cls in classes:
+ class_uri = cls.get("uri") or cls.get("id", "")
+ class_name = cls.get("name") or cls.get("label", "")
+
+ lines.append(f' <owl:Class rdf:about="{class_uri}">')
+ lines.append(f' <rdfs:label>{class_name}</rdfs:label>')
+
+ if cls.get("comment"):
+ lines.append(f' <rdfs:comment>{cls.get("comment")}</rdfs:comment>')
+
+ # Subclass relationships
+ if cls.get("subClassOf"):
+ parent = cls.get("subClassOf")
+ lines.append(f' <rdfs:subClassOf rdf:resource="{parent}"/>')
+
+ # Equivalent classes
+ if cls.get("equivalentClass"):
+ equiv = cls.get("equivalentClass")
+ lines.append(f' <owl:equivalentClass rdf:resource="{equiv}"/>')
+
+ lines.append(" </owl:Class>")
+ lines.append("")
+
+ # Object properties
+ object_properties = ontology.get("object_properties", [])
+ for prop in object_properties:
+ prop_uri = prop.get("uri") or prop.get("id", "")
+ prop_name = prop.get("name") or prop.get("label", "")
+
+ lines.append(f' <owl:ObjectProperty rdf:about="{prop_uri}">')
+ lines.append(f' <rdfs:label>{prop_name}</rdfs:label>')
+
+ if prop.get("comment"):
+ lines.append(f' <rdfs:comment>{prop.get("comment")}</rdfs:comment>')
+
+ # Domain
+ if prop.get("domain"):
+ domain = prop.get("domain")
+ if isinstance(domain, list):
+ for d in domain:
+ lines.append(f' <rdfs:domain rdf:resource="{d}"/>')
+ else:
+ lines.append(f' <rdfs:domain rdf:resource="{domain}"/>')
+
+ # Range
+ if prop.get("range"):
+ range_val = prop.get("range")
+ if isinstance(range_val, list):
+ for r in range_val:
+ lines.append(f' <rdfs:range rdf:resource="{r}"/>')
+ else:
+ lines.append(f' <rdfs:range rdf:resource="{range_val}"/>')
+
+ lines.append(" </owl:ObjectProperty>")
+ lines.append("")
+
+ # Data properties
+ data_properties = ontology.get("data_properties", [])
+ for prop in data_properties:
+ prop_uri = prop.get("uri") or prop.get("id", "")
+ prop_name = prop.get("name") or prop.get("label", "")
+
+ lines.append(f' <owl:DatatypeProperty rdf:about="{prop_uri}">')
+ lines.append(f' <rdfs:label>{prop_name}</rdfs:label>')
+
+ if prop.get("comment"):
+ lines.append(f' <rdfs:comment>{prop.get("comment")}</rdfs:comment>')
+
+ # Domain
+ if prop.get("domain"):
+ domain = prop.get("domain")
+ lines.append(f' <rdfs:domain rdf:resource="{domain}"/>')
+
+ # Range
+ if prop.get("range"):
+ range_type = prop.get("range", "xsd:string")
+ lines.append(f' <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#{range_type}"/>')
+
+ lines.append(" </owl:DatatypeProperty>")
+ lines.append("")
+
+ lines.append("</rdf:RDF>")
+ return "\n".join(lines)
+
+ def _export_owl_turtle(self, ontology: Dict[str, Any], **options) -> str:
+ """Export to OWL Turtle format."""
+ ontology_uri = ontology.get("uri") or self.ontology_uri
+ ontology_name = ontology.get("name", "SemanticaOntology")
+ version = ontology.get("version") or self.version
+
+ lines = []
+
+ # Namespace declarations
+ lines.append("@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .")
+ lines.append("@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .")
+ lines.append("@prefix owl: <http://www.w3.org/2002/07/owl#> .")
+ lines.append("@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .")
+ lines.append(f"@prefix ont: <{ontology_uri}> .")
+ lines.append("")
+
+ # Ontology declaration
+ lines.append(f"<{ontology_uri}> a owl:Ontology ;")
+ lines.append(f' rdfs:label "{ontology_name}" ;')
+ lines.append(f' owl:versionInfo "{version}" .')
+ if ontology.get("description"):
+ lines.append(f' rdfs:comment "{ontology.get("description")}" ;')
+ lines.append("")
+
+ # Classes
+ classes = ontology.get("classes", [])
+ for cls in classes:
+ class_uri = cls.get("uri") or cls.get("id", "")
+ class_name = cls.get("name") or cls.get("label", "")
+
+ lines.append(f"<{class_uri}> a owl:Class ;")
+ lines.append(f' rdfs:label "{class_name}" .')
+
+ if cls.get("comment"):
+ lines.append(f' rdfs:comment "{cls.get("comment")}" ;')
+
+ if cls.get("subClassOf"):
+ parent = cls.get("subClassOf")
+ lines.append(f' rdfs:subClassOf <{parent}> ;')
+
+ # Remove trailing semicolon and add period
+ if lines[-1].endswith(" ;"):
+ lines[-1] = lines[-1].rstrip(" ;") + " ."
+ else:
+ lines.append(" .")
+ lines.append("")
+
+ # Object properties
+ object_properties = ontology.get("object_properties", [])
+ for prop in object_properties:
+ prop_uri = prop.get("uri") or prop.get("id", "")
+ prop_name = prop.get("name") or prop.get("label", "")
+
+ lines.append(f"<{prop_uri}> a owl:ObjectProperty ;")
+ lines.append(f' rdfs:label "{prop_name}" .')
+
+ if prop.get("domain"):
+ domain = prop.get("domain")
+ if isinstance(domain, list):
+ for d in domain:
+ lines.append(f' rdfs:domain <{d}> ;')
+ else:
+ lines.append(f' rdfs:domain <{domain}> ;')
+
+ if prop.get("range"):
+ range_val = prop.get("range")
+ if isinstance(range_val, list):
+ for r in range_val:
+ lines.append(f' rdfs:range <{r}> ;')
+ else:
+ lines.append(f' rdfs:range <{range_val}> ;')
+
+ if lines[-1].endswith(" ;"):
+ lines[-1] = lines[-1].rstrip(" ;") + " ."
+ lines.append("")
+
+ return "\n".join(lines)
+
+ def export_classes(
+ self,
+ classes: List[Dict[str, Any]],
+ file_path: Union[str, Path],
+ **options
+ ) -> None:
+ """
+ Export classes to OWL format.
+
+ Args:
+ classes: List of class definitions
+ file_path: Output file path
+ **options: Additional options
+ """
+ ontology = {
+ "classes": classes,
+ "uri": options.get("ontology_uri", self.ontology_uri),
+ "name": options.get("ontology_name", "SemanticaOntology")
+ }
+ self.export(ontology, file_path, **options)
+
+ def export_properties(
+ self,
+ properties: List[Dict[str, Any]],
+ file_path: Union[str, Path],
+ property_type: str = "object",
+ **options
+ ) -> None:
+ """
+ Export properties to OWL format.
+
+ Args:
+ properties: List of property definitions
+ file_path: Output file path
+ property_type: Property type ('object', 'data')
+ **options: Additional options
+ """
+ ontology = {
+ "uri": options.get("ontology_uri", self.ontology_uri),
+ "name": options.get("ontology_name", "SemanticaOntology")
+ }
+
+ if property_type == "object":
+ ontology["object_properties"] = properties
+ else:
+ ontology["data_properties"] = properties
+
+ self.export(ontology, file_path, **options)
+
diff --git a/libs/semantica/export/rdf_exporter.py b/libs/semantica/export/rdf_exporter.py
index 000ce52a..2a1b0471 100644
--- a/libs/semantica/export/rdf_exporter.py
+++ b/libs/semantica/export/rdf_exporter.py
@@ -17,88 +17,111 @@ Main Classes:
- NamespaceManager: RDF namespace management
"""
+from typing import Any, Dict, List, Optional, Set, Union
+from pathlib import Path
-class RDFExporter:
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..utils.helpers import ensure_directory
+
+
+class NamespaceManager:
"""
- RDF export and serialization handler.
+ RDF namespace management engine.
- • Exports data to RDF formats
- • Handles RDF serialization
• Manages RDF namespaces
- • Validates RDF output
- • Supports multiple RDF formats
- • Handles batch RDF export
-
- Attributes:
- • rdf_serializer: RDF serialization engine
- • rdf_validator: RDF validation engine
- • namespace_manager: Namespace manager
- • supported_formats: List of supported formats
- • export_config: Export configuration
-
- Methods:
- • export_to_rdf(): Export data to RDF
- • serialize_rdf(): Serialize RDF data
- • validate_rdf(): Validate RDF output
- • manage_namespaces(): Manage RDF namespaces
+ • Handles namespace declarations
+ • Processes namespace conflicts
+ • Manages namespace metadata
"""
- def __init__(self, config=None, **kwargs):
+ def __init__(self, **config):
"""
- Initialize RDF exporter.
+ Initialize namespace manager.
- • Setup RDF serialization
- • Configure export formats
- • Initialize validation tools
- • Setup namespace management
- • Configure batch processing
+ • Setup namespace handling
+ • Configure namespace resolution
+ • Initialize conflict resolution
+ • Setup metadata management
"""
- pass
+ self.logger = get_logger("namespace_manager")
+ 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#",
+ "owl": "http://www.w3.org/2002/07/owl#",
+ "xsd": "http://www.w3.org/2001/XMLSchema#",
+ "semantica": "https://semantica.dev/ns#"
+ }
+ self.config = config or {}
- def export_to_rdf(self, data, format="turtle", **options):
+ def extract_namespaces(self, rdf_data: Dict[str, Any]) -> Dict[str, str]:
"""
- Export data to RDF format.
+ Extract namespaces from RDF data.
- • Convert data to RDF
- • Apply format-specific serialization
- • Handle namespace declarations
- • Validate RDF output
- • Return RDF export
- """
- pass
-
- def serialize_rdf(self, rdf_data, format="turtle", **options):
+ • Identify namespace usage
+ • Extract namespace declarations
+ • Analyze namespace requirements
+ • Return namespace information
"""
- Serialize RDF data to specified format.
+ extracted = {}
- • Convert RDF to serialized format
- • Apply format-specific rules
- • Handle encoding and formatting
- • Return serialized RDF
- """
- pass
+ # Check for @context in JSON-LD
+ if "@context" in rdf_data:
+ context = rdf_data["@context"]
+ if isinstance(context, dict):
+ for prefix, uri in context.items():
+ if not prefix.startswith("@"):
+ extracted[prefix] = uri
+
+ return extracted
- def validate_rdf(self, rdf_data, **options):
+ def generate_namespace_declarations(self, namespaces: Dict[str, str], format: str = "turtle") -> str:
"""
- Validate RDF data quality and structure.
+ Generate namespace declarations.
- • Check RDF syntax and structure
- • Validate namespace usage
- • Check RDF consistency
- • Return validation results
+ • Create namespace declarations
+ • Handle namespace formatting
+ • Optimize namespace usage
+ • Return namespace declarations
"""
- pass
+ declarations = []
+
+ if format == "turtle":
+ for prefix, uri in namespaces.items():
+ declarations.append(f"@prefix {prefix}: <{uri}> .")
+ elif format == "rdfxml":
+ for prefix, uri in namespaces.items():
+ declarations.append(f'xmlns:{prefix}="{uri}"')
+ elif format == "jsonld":
+ # JSON-LD uses @context
+ return "" # Handled separately
+
+ return "\n".join(declarations)
- def manage_namespaces(self, rdf_data, **namespaces):
+ def resolve_namespace_conflicts(self, namespaces: Dict[str, str]) -> Dict[str, str]:
"""
- Manage RDF namespaces and declarations.
+ Resolve namespace conflicts.
- • Extract namespace requirements
- • Generate namespace declarations
- • Handle namespace conflicts
- • Return namespace management results
+ • Identify namespace conflicts
+ • Apply conflict resolution
+ • Handle namespace mapping
+ • Return resolved namespaces
"""
- pass
+ resolved = {}
+ seen_uris = {}
+
+ for prefix, uri in namespaces.items():
+ if uri in seen_uris:
+ # Conflict - use existing prefix or create new one
+ 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}")
+ else:
+ resolved[prefix] = uri
+ seen_uris[uri] = prefix
+
+ return resolved
class RDFSerializer:
@@ -120,9 +143,11 @@ class RDFSerializer:
• Initialize encoding tools
• Setup metadata processing
"""
- pass
+ self.logger = get_logger("rdf_serializer")
+ self.config = config or {}
+ self.namespace_manager = NamespaceManager()
- def serialize_to_turtle(self, rdf_data, **options):
+ def serialize_to_turtle(self, rdf_data: Dict[str, Any], **options) -> str:
"""
Serialize RDF to Turtle format.
@@ -131,9 +156,39 @@ class RDFSerializer:
• Optimize Turtle output
• Return Turtle serialization
"""
- pass
+ lines = []
+
+ # Generate namespace declarations
+ namespaces = self.namespace_manager.extract_namespaces(rdf_data)
+ if namespaces:
+ ns_declarations = self.namespace_manager.generate_namespace_declarations(namespaces, "turtle")
+ lines.append(ns_declarations)
+ lines.append("")
+
+ # Convert entities to triples
+ entities = rdf_data.get("entities", [])
+ for entity in entities:
+ entity_id = entity.get("id") or f"semantica:entity_{hash(entity.get('text', ''))}"
+ entity_type = entity.get("type", "semantica:Entity")
+ text = entity.get("text") or entity.get("label", "")
+
+ 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("")
+
+ # Convert relationships to 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")
+
+ lines.append(f"<{source_id}> <{rel_type}> <{target_id}> .")
+
+ return "\n".join(lines)
- def serialize_to_rdfxml(self, rdf_data, **options):
+ def serialize_to_rdfxml(self, rdf_data: Dict[str, Any], **options) -> str:
"""
Serialize RDF to RDF/XML format.
@@ -142,9 +197,42 @@ class RDFSerializer:
• Optimize XML structure
• Return RDF/XML serialization
"""
- pass
+ lines = ['<?xml version="1.0" encoding="UTF-8"?>']
+ lines.append('<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"')
+ lines.append(' xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"')
+ lines.append(' xmlns:semantica="https://semantica.dev/ns#">')
+ lines.append("")
+
+ # Convert entities
+ entities = rdf_data.get("entities", [])
+ for entity in entities:
+ entity_id = entity.get("id") or f"semantica:entity_{hash(entity.get('text', ''))}"
+ entity_type = entity.get("type", "semantica:Entity")
+ text = entity.get("text") or entity.get("label", "")
+
+ 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(" </rdf:Description>")
+ lines.append("")
+
+ # Convert relationships
+ 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")
+
+ lines.append(f' <rdf:Description rdf:about="{source_id}">')
+ lines.append(f' <{rel_type} rdf:resource="{target_id}"/>')
+ lines.append(" </rdf:Description>")
+ lines.append("")
+
+ lines.append("</rdf:RDF>")
+ return "\n".join(lines)
- def serialize_to_jsonld(self, rdf_data, **options):
+ def serialize_to_jsonld(self, rdf_data: Dict[str, Any], **options) -> str:
"""
Serialize RDF to JSON-LD format.
@@ -153,7 +241,40 @@ class RDFSerializer:
• Optimize JSON structure
• Return JSON-LD serialization
"""
- pass
+ import json
+
+ jsonld = {
+ "@context": {
+ "@vocab": "https://semantica.dev/vocab/",
+ "semantica": "https://semantica.dev/ns#",
+ "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
+ "rdfs": "http://www.w3.org/2000/01/rdf-schema#"
+ },
+ "@graph": []
+ }
+
+ # Convert entities
+ entities = rdf_data.get("entities", [])
+ for entity in entities:
+ jsonld["@graph"].append({
+ "@id": entity.get("id") or f"semantica:entity/{entity.get('text', '')}",
+ "@type": entity.get("type", "semantica:Entity"),
+ "semantica:text": entity.get("text") or entity.get("label", ""),
+ "semantica:confidence": entity.get("confidence", 1.0)
+ })
+
+ # Convert relationships
+ relationships = rdf_data.get("relationships", [])
+ for rel in relationships:
+ jsonld["@graph"].append({
+ "@id": rel.get("id") or f"semantica:rel/{rel.get('source_id')}_{rel.get('target_id')}",
+ "@type": "semantica:Relationship",
+ "semantica:source": {"@id": rel.get("source_id")},
+ "semantica:target": {"@id": rel.get("target_id")},
+ "semantica:type": rel.get("type", "related_to")
+ })
+
+ return json.dumps(jsonld, indent=2, ensure_ascii=False)
class RDFValidator:
@@ -175,9 +296,10 @@ class RDFValidator:
• Initialize consistency checkers
• Setup quality assessment
"""
- pass
+ self.logger = get_logger("rdf_validator")
+ self.config = config or {}
- def validate_rdf_syntax(self, rdf_data, format="turtle"):
+ def validate_rdf_syntax(self, rdf_data: Dict[str, Any], format: str = "turtle") -> Dict[str, Any]:
"""
Validate RDF syntax for specified format.
@@ -186,9 +308,45 @@ class RDFValidator:
• Handle syntax errors
• Return validation results
"""
- pass
+ errors = []
+ warnings = []
+
+ # Basic structure validation
+ if not isinstance(rdf_data, dict):
+ errors.append("RDF data must be a dictionary")
+ return {"valid": False, "errors": errors, "warnings": warnings}
+
+ # 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")
+
+ # 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")
+ continue
+
+ if "id" not in entity and "text" not in entity:
+ warnings.append(f"Entity {i} missing 'id' or 'text'")
+
+ # 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")
+ continue
+
+ if "source_id" not in rel and "target_id" not in rel:
+ errors.append(f"Relationship {i} missing 'source_id' or 'target_id'")
+
+ return {
+ "valid": len(errors) == 0,
+ "errors": errors,
+ "warnings": warnings
+ }
- def validate_namespace_usage(self, rdf_data):
+ def validate_namespace_usage(self, rdf_data: Dict[str, Any]) -> Dict[str, Any]:
"""
Validate RDF namespace usage.
@@ -197,9 +355,20 @@ class RDFValidator:
• Handle namespace conflicts
• Return namespace validation
"""
- pass
+ issues = []
+
+ # Check for @context in JSON-LD
+ if "@context" in rdf_data:
+ context = rdf_data["@context"]
+ if not isinstance(context, dict):
+ issues.append("@context must be a dictionary")
+
+ return {
+ "valid": len(issues) == 0,
+ "issues": issues
+ }
- def check_rdf_consistency(self, rdf_data):
+ def check_rdf_consistency(self, rdf_data: Dict[str, Any]) -> Dict[str, Any]:
"""
Check RDF consistency and coherence.
@@ -208,59 +377,171 @@ class RDFValidator:
• Validate RDF relationships
• Return consistency report
"""
- pass
+ issues = []
+
+ # Check relationship references
+ relationships = rdf_data.get("relationships", [])
+ 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")
+
+ if source_id and source_id not in entity_ids:
+ issues.append(f"Relationship references non-existent source entity: {source_id}")
+
+ if target_id and target_id not in entity_ids:
+ issues.append(f"Relationship references non-existent target entity: {target_id}")
+
+ return {
+ "consistent": len(issues) == 0,
+ "issues": issues
+ }
-class NamespaceManager:
+class RDFExporter:
"""
- RDF namespace management engine.
+ RDF export and serialization handler.
+ • Exports data to RDF formats
+ • Handles RDF serialization
• Manages RDF namespaces
- • Handles namespace declarations
- • Processes namespace conflicts
- • Manages namespace metadata
+ • Validates RDF output
+ • Supports multiple RDF formats
+ • Handles batch RDF export
"""
- def __init__(self, **config):
+ def __init__(self, config=None, **kwargs):
"""
- Initialize namespace manager.
+ Initialize RDF exporter.
- • Setup namespace handling
- • Configure namespace resolution
- • Initialize conflict resolution
- • Setup metadata management
+ • Setup RDF serialization
+ • Configure export formats
+ • Initialize validation tools
+ • Setup namespace management
+ • Configure batch processing
"""
- pass
+ self.logger = get_logger("rdf_exporter")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ self.serializer = RDFSerializer()
+ self.validator = RDFValidator()
+ self.namespace_manager = NamespaceManager()
+
+ self.supported_formats = ["turtle", "rdfxml", "jsonld", "ntriples", "n3"]
- def extract_namespaces(self, rdf_data):
+ def export_to_rdf(self, data: Dict[str, Any], format: str = "turtle", **options) -> str:
"""
- Extract namespaces from RDF data.
+ Export data to RDF format.
- • Identify namespace usage
- • Extract namespace declarations
- • Analyze namespace requirements
- • Return namespace information
+ • Convert data to RDF
+ • Apply format-specific serialization
+ • Handle namespace declarations
+ • Validate RDF output
+ • Return RDF export
"""
- pass
+ if format not in self.supported_formats:
+ raise ValidationError(f"Unsupported RDF format: {format}")
+
+ # Validate input
+ validation = self.validator.validate_rdf_syntax(data, format)
+ if not validation["valid"]:
+ self.logger.warning(f"RDF validation issues: {validation['errors']}")
+
+ # Serialize
+ if format == "turtle":
+ return self.serializer.serialize_to_turtle(data, **options)
+ elif format == "rdfxml":
+ return self.serializer.serialize_to_rdfxml(data, **options)
+ elif format == "jsonld":
+ return self.serializer.serialize_to_jsonld(data, **options)
+ else:
+ raise ValidationError(f"Format {format} not yet implemented")
- def generate_namespace_declarations(self, namespaces):
+ def export(
+ self,
+ data: Dict[str, Any],
+ file_path: Union[str, Path],
+ format: str = "turtle",
+ **options
+ ) -> None:
+ """
+ Export data to RDF file.
+
+ Args:
+ data: Data to export
+ file_path: Output file path
+ format: RDF format ('turtle', 'rdfxml', 'jsonld')
+ **options: Additional options
+ """
+ file_path = Path(file_path)
+ ensure_directory(file_path.parent)
+
+ rdf_content = self.export_to_rdf(data, format=format, **options)
+
+ encoding = options.get("encoding", "utf-8")
+
+ with open(file_path, "w", encoding=encoding) as f:
+ f.write(rdf_content)
+
+ self.logger.info(f"Exported RDF ({format}) to: {file_path}")
+
+ def serialize_rdf(self, rdf_data: Dict[str, Any], format: str = "turtle", **options) -> str:
"""
- Generate namespace declarations.
+ Serialize RDF data to specified format.
- • Create namespace declarations
- • Handle namespace formatting
- • Optimize namespace usage
- • Return namespace declarations
+ • Convert RDF to serialized format
+ • Apply format-specific rules
+ • Handle encoding and formatting
+ • Return serialized RDF
"""
- pass
+ return self.export_to_rdf(rdf_data, format=format, **options)
- def resolve_namespace_conflicts(self, namespaces):
+ def validate_rdf(self, rdf_data: Dict[str, Any], **options) -> Dict[str, Any]:
"""
- Resolve namespace conflicts.
+ Validate RDF data quality and structure.
- • Identify namespace conflicts
- • Apply conflict resolution
- • Handle namespace mapping
- • Return resolved namespaces
+ • Check RDF syntax and structure
+ • Validate namespace usage
+ • Check RDF consistency
+ • Return validation results
+ """
+ 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)
+
+ return {
+ "syntax": syntax_validation,
+ "namespaces": namespace_validation,
+ "consistency": consistency_check,
+ "overall_valid": (
+ syntax_validation["valid"] and
+ namespace_validation["valid"] and
+ consistency_check["consistent"]
+ )
+ }
+
+ def manage_namespaces(self, rdf_data: Dict[str, Any], **namespaces: str) -> Dict[str, Any]:
"""
- pass
+ Manage RDF namespaces and declarations.
+
+ • Extract namespace requirements
+ • Generate namespace declarations
+ • Handle namespace conflicts
+ • Return namespace management results
+ """
+ # Extract existing namespaces
+ extracted = self.namespace_manager.extract_namespaces(rdf_data)
+
+ # Merge with provided namespaces
+ all_namespaces = {**extracted, **namespaces}
+
+ # Resolve conflicts
+ resolved = self.namespace_manager.resolve_namespace_conflicts(all_namespaces)
+
+ return {
+ "namespaces": resolved,
+ "declarations": self.namespace_manager.generate_namespace_declarations(resolved, "turtle")
+ }
diff --git a/libs/semantica/export/report_generator.py b/libs/semantica/export/report_generator.py
index 816a5f30..8d53eb6b 100644
--- a/libs/semantica/export/report_generator.py
+++ b/libs/semantica/export/report_generator.py
@@ -5,10 +5,380 @@ This module provides report generation capabilities
for analysis results and framework metrics.
"""
-# TODO: Implement report generation
-# - Report generation functionality
-# - Analysis result formatting
-# - Framework metrics reporting
-# - Performance optimization
-# - Error handling and recovery
-# - Advanced reporting features
+from typing import Any, Dict, List, Optional, Union
+from pathlib import Path
+from datetime import datetime
+import json
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..utils.helpers import ensure_directory
+
+
+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
+ """
+
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize report generator.
+
+ 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
+ """
+ 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")
+
+ def generate_report(
+ self,
+ data: Dict[str, Any],
+ file_path: Optional[Union[str, Path]] = None,
+ format: Optional[str] = None,
+ **options
+ ) -> Union[str, None]:
+ """
+ Generate report from data.
+
+ Args:
+ data: Report data dictionary
+ file_path: Optional output file path
+ format: Report format ('html', 'markdown', 'json', 'text')
+ **options: Additional options
+
+ Returns:
+ Report string if file_path not provided, None otherwise
+ """
+ report_format = format or self.format
+
+ if report_format == "markdown":
+ report = self._generate_markdown(data, **options)
+ elif report_format == "html":
+ report = self._generate_html(data, **options)
+ elif report_format == "json":
+ report = self._generate_json(data, **options)
+ elif report_format == "text":
+ report = self._generate_text(data, **options)
+ else:
+ raise ValidationError(f"Unsupported report format: {report_format}")
+
+ 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
+
+ def generate_quality_report(
+ self,
+ quality_metrics: Dict[str, Any],
+ file_path: Optional[Union[str, Path]] = None,
+ **options
+ ) -> Union[str, None]:
+ """
+ Generate quality assurance report.
+
+ Args:
+ quality_metrics: Quality metrics dictionary
+ file_path: Optional output file path
+ **options: Additional options
+
+ Returns:
+ Report string if file_path not provided, None otherwise
+ """
+ report_data = {
+ "title": "Quality Assurance Report",
+ "generated_at": datetime.now().isoformat(),
+ "metrics": quality_metrics,
+ "summary": self._generate_quality_summary(quality_metrics)
+ }
+
+ return self.generate_report(report_data, file_path=file_path, **options)
+
+ def generate_analysis_report(
+ self,
+ analysis_results: Dict[str, Any],
+ file_path: Optional[Union[str, Path]] = None,
+ **options
+ ) -> Union[str, None]:
+ """
+ Generate analysis report.
+
+ Args:
+ analysis_results: Analysis results dictionary
+ file_path: Optional output file path
+ **options: Additional options
+
+ Returns:
+ Report string if file_path not provided, None otherwise
+ """
+ report_data = {
+ "title": "Analysis Report",
+ "generated_at": datetime.now().isoformat(),
+ "analysis": analysis_results,
+ "summary": self._generate_analysis_summary(analysis_results)
+ }
+
+ return self.generate_report(report_data, file_path=file_path, **options)
+
+ def generate_metrics_report(
+ self,
+ metrics: Dict[str, Any],
+ file_path: Optional[Union[str, Path]] = None,
+ **options
+ ) -> Union[str, None]:
+ """
+ Generate metrics report.
+
+ Args:
+ metrics: Metrics dictionary
+ file_path: Optional output file path
+ **options: Additional options
+
+ Returns:
+ Report string if file_path not provided, None otherwise
+ """
+ report_data = {
+ "title": "Framework Metrics Report",
+ "generated_at": datetime.now().isoformat(),
+ "metrics": metrics,
+ "summary": self._generate_metrics_summary(metrics)
+ }
+
+ return self.generate_report(report_data, file_path=file_path, **options)
+
+ def _generate_markdown(self, data: Dict[str, Any], **options) -> str:
+ """Generate Markdown report."""
+ lines = []
+
+ # Title
+ title = data.get("title", "Report")
+ lines.append(f"# {title}")
+ lines.append("")
+
+ # Generated at
+ if "generated_at" in data:
+ lines.append(f"**Generated:** {data['generated_at']}")
+ lines.append("")
+
+ # Summary
+ if "summary" in data:
+ lines.append("## Summary")
+ lines.append("")
+ summary = data["summary"]
+ if isinstance(summary, dict):
+ for key, value in summary.items():
+ lines.append(f"- **{key}**: {value}")
+ else:
+ lines.append(str(summary))
+ lines.append("")
+
+ # Metrics
+ if "metrics" in data:
+ lines.append("## Metrics")
+ lines.append("")
+ metrics = data["metrics"]
+ self._add_dict_to_markdown(metrics, lines, level=2)
+
+ # Analysis
+ if "analysis" in data:
+ lines.append("## Analysis")
+ lines.append("")
+ analysis = data["analysis"]
+ self._add_dict_to_markdown(analysis, lines, level=2)
+
+ return "\n".join(lines)
+
+ def _generate_html(self, data: Dict[str, Any], **options) -> str:
+ """Generate HTML report."""
+ lines = ['<!DOCTYPE html>']
+ lines.append('<html lang="en">')
+ lines.append("<head>")
+ lines.append(' <meta charset="UTF-8">')
+ lines.append(' <meta name="viewport" content="width=device-width, initial-scale=1.0">')
+ title = data.get("title", "Report")
+ lines.append(f' <title>{title}</title>')
+ lines.append(' <style>')
+ lines.append(' body { font-family: Arial, sans-serif; margin: 20px; }')
+ lines.append(' h1 { color: #333; }')
+ lines.append(' h2 { color: #666; margin-top: 30px; }')
+ lines.append(' table { border-collapse: collapse; width: 100%; margin: 20px 0; }')
+ lines.append(' th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }')
+ lines.append(' th { background-color: #f2f2f2; }')
+ lines.append(' </style>')
+ lines.append("</head>")
+ lines.append("<body>")
+
+ # Title
+ title = data.get("title", "Report")
+ lines.append(f" <h1>{title}</h1>")
+
+ # Generated at
+ if "generated_at" in data:
+ lines.append(f' <p><strong>Generated:</strong> {data["generated_at"]}</p>')
+
+ # Summary
+ if "summary" in data:
+ lines.append(" <h2>Summary</h2>")
+ summary = data["summary"]
+ if isinstance(summary, dict):
+ lines.append(" <ul>")
+ for key, value in summary.items():
+ lines.append(f" <li><strong>{key}:</strong> {value}</li>")
+ lines.append(" </ul>")
+ else:
+ lines.append(f" <p>{summary}</p>")
+
+ # Metrics
+ if "metrics" in data:
+ lines.append(" <h2>Metrics</h2>")
+ metrics = data["metrics"]
+ self._add_dict_to_html(metrics, lines)
+
+ lines.append("</body>")
+ lines.append("</html>")
+
+ return "\n".join(lines)
+
+ def _generate_json(self, data: Dict[str, Any], **options) -> str:
+ """Generate JSON report."""
+ return json.dumps(data, indent=2, ensure_ascii=False)
+
+ def _generate_text(self, data: Dict[str, Any], **options) -> str:
+ """Generate plain text report."""
+ lines = []
+
+ # Title
+ title = data.get("title", "Report")
+ lines.append("=" * 60)
+ lines.append(title)
+ lines.append("=" * 60)
+ lines.append("")
+
+ # Generated at
+ if "generated_at" in data:
+ lines.append(f"Generated: {data['generated_at']}")
+ lines.append("")
+
+ # Summary
+ if "summary" in data:
+ lines.append("SUMMARY")
+ lines.append("-" * 60)
+ summary = data["summary"]
+ if isinstance(summary, dict):
+ for key, value in summary.items():
+ lines.append(f" {key}: {value}")
+ else:
+ lines.append(str(summary))
+ lines.append("")
+
+ # Metrics
+ if "metrics" in data:
+ lines.append("METRICS")
+ lines.append("-" * 60)
+ metrics = data["metrics"]
+ self._add_dict_to_text(metrics, lines, indent=2)
+
+ return "\n".join(lines)
+
+ def _add_dict_to_markdown(self, data: Dict[str, Any], lines: List[str], level: int = 2) -> None:
+ """Add dictionary to markdown."""
+ for key, value in data.items():
+ if isinstance(value, dict):
+ lines.append(f"{'#' * level} {key}")
+ lines.append("")
+ self._add_dict_to_markdown(value, lines, level + 1)
+ elif isinstance(value, list):
+ lines.append(f"**{key}:**")
+ for item in value:
+ if isinstance(item, dict):
+ lines.append("- " + ", ".join(f"{k}: {v}" for k, v in item.items()))
+ else:
+ lines.append(f"- {item}")
+ lines.append("")
+ else:
+ lines.append(f"- **{key}**: {value}")
+
+ def _add_dict_to_html(self, data: Dict[str, Any], lines: List[str]) -> None:
+ """Add dictionary to HTML."""
+ lines.append(" <table>")
+ lines.append(" <tr><th>Key</th><th>Value</th></tr>")
+
+ for key, value in data.items():
+ if isinstance(value, (dict, list)):
+ value_str = json.dumps(value, indent=2)
+ else:
+ value_str = str(value)
+
+ lines.append(f" <tr><td>{key}</td><td>{value_str}</td></tr>")
+
+ lines.append(" </table>")
+
+ def _add_dict_to_text(self, data: Dict[str, Any], lines: List[str], indent: int = 0) -> None:
+ """Add dictionary to text."""
+ prefix = " " * indent
+
+ for key, value in data.items():
+ if isinstance(value, dict):
+ lines.append(f"{prefix}{key}:")
+ self._add_dict_to_text(value, lines, indent + 2)
+ elif isinstance(value, list):
+ lines.append(f"{prefix}{key}:")
+ for item in value:
+ if isinstance(item, dict):
+ item_str = ", ".join(f"{k}={v}" for k, v in item.items())
+ lines.append(f"{prefix} - {item_str}")
+ else:
+ lines.append(f"{prefix} - {item}")
+ else:
+ lines.append(f"{prefix}{key}: {value}")
+
+ def _generate_quality_summary(self, metrics: Dict[str, Any]) -> Dict[str, Any]:
+ """Generate quality summary."""
+ score = metrics.get("score") or metrics.get("overall_score", 0.0)
+
+ return {
+ "Overall Score": f"{score:.2f}",
+ "Status": "PASS" if score >= 0.7 else "FAIL",
+ "Completeness": metrics.get("completeness", "N/A"),
+ "Accuracy": metrics.get("accuracy", "N/A"),
+ "Consistency": metrics.get("consistency", "N/A")
+ }
+
+ def _generate_analysis_summary(self, analysis: Dict[str, Any]) -> Dict[str, Any]:
+ """Generate analysis summary."""
+ return {
+ "Analysis Type": analysis.get("type", "Unknown"),
+ "Items Analyzed": analysis.get("total_count", 0),
+ "Status": analysis.get("status", "Completed")
+ }
+
+ def _generate_metrics_summary(self, metrics: Dict[str, Any]) -> Dict[str, Any]:
+ """Generate metrics summary."""
+ return {
+ "Total Items": metrics.get("total_items", 0),
+ "Success Rate": f"{metrics.get('success_rate', 0.0):.2%}",
+ "Average Confidence": f"{metrics.get('average_confidence', 0.0):.2f}"
+ }
diff --git a/libs/semantica/export/vector_exporter.py b/libs/semantica/export/vector_exporter.py
new file mode 100644
index 00000000..1ce5079b
--- /dev/null
+++ b/libs/semantica/export/vector_exporter.py
@@ -0,0 +1,406 @@
+"""
+Vector Exporter for Vector Embeddings Use Cases
+
+Exports vector embeddings and vector data to various formats
+for use with vector stores and embedding systems.
+"""
+
+from typing import Any, Dict, List, Optional, Union
+from pathlib import Path
+import json
+import numpy as np
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..utils.helpers import ensure_directory, write_json_file
+
+
+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
+ """
+
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize vector exporter.
+
+ 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)
+ """
+ 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)
+
+ def export(
+ self,
+ vectors: Union[List[Dict[str, Any]], Dict[str, Any]],
+ file_path: Union[str, Path],
+ format: Optional[str] = None,
+ **options
+ ) -> None:
+ """
+ Export vectors to file.
+
+ Args:
+ vectors: List of vector dictionaries or dict with 'vectors' key
+ file_path: Output file path
+ format: Export format ('json', 'numpy', 'binary', 'faiss')
+ **options: Additional options
+ """
+ file_path = Path(file_path)
+ ensure_directory(file_path.parent)
+
+ export_format = format or self.format
+
+ # Normalize input
+ if isinstance(vectors, dict):
+ vector_list = vectors.get("vectors", [])
+ metadata = vectors.get("metadata", {})
+ else:
+ vector_list = vectors
+ metadata = {}
+
+ if export_format == "json":
+ self._export_json(vector_list, file_path, metadata, **options)
+ elif export_format == "numpy":
+ self._export_numpy(vector_list, file_path, **options)
+ elif export_format == "binary":
+ self._export_binary(vector_list, file_path, **options)
+ elif export_format == "faiss":
+ self._export_faiss(vector_list, file_path, **options)
+ else:
+ raise ValidationError(f"Unsupported vector format: {export_format}")
+
+ self.logger.info(f"Exported vectors ({export_format}) to: {file_path}")
+
+ def export_embeddings(
+ self,
+ embeddings: List[Dict[str, Any]],
+ file_path: Union[str, Path],
+ format: Optional[str] = None,
+ **options
+ ) -> None:
+ """
+ Export embeddings to file.
+
+ Args:
+ embeddings: List of embedding dictionaries with 'id', 'vector', 'text', etc.
+ file_path: Output file path
+ format: Export format
+ **options: Additional options
+ """
+ self.export(embeddings, file_path, format=format, **options)
+
+ def _export_json(
+ self,
+ vectors: List[Dict[str, Any]],
+ file_path: Path,
+ metadata: Dict[str, Any],
+ **options
+ ) -> None:
+ """Export to JSON format."""
+ export_data = {
+ "vectors": [],
+ "metadata": {
+ "vector_count": len(vectors),
+ "dimension": None,
+ **metadata
+ }
+ }
+
+ for vec_data in vectors:
+ vector_entry = {
+ "id": vec_data.get("id") or vec_data.get("vector_id", ""),
+ "vector": vec_data.get("vector") or vec_data.get("embedding", [])
+ }
+
+ if self.include_text and "text" in vec_data:
+ vector_entry["text"] = vec_data["text"]
+
+ if self.include_metadata and "metadata" in vec_data:
+ vector_entry["metadata"] = vec_data["metadata"]
+
+ # Determine dimension
+ vector = vector_entry["vector"]
+ if isinstance(vector, list) and len(vector) > 0:
+ if export_data["metadata"]["dimension"] is None:
+ export_data["metadata"]["dimension"] = len(vector)
+
+ export_data["vectors"].append(vector_entry)
+
+ write_json_file(export_data, file_path, indent=2)
+
+ def _export_numpy(
+ self,
+ vectors: List[Dict[str, Any]],
+ file_path: Path,
+ **options
+ ) -> None:
+ """Export to NumPy format."""
+ try:
+ import numpy as np
+ except ImportError:
+ raise ImportError("NumPy not installed. Install with: pip install numpy")
+
+ # Extract vectors
+ vector_list = []
+ ids = []
+ texts = []
+ metadata_list = []
+
+ for vec_data in vectors:
+ vector = vec_data.get("vector") or vec_data.get("embedding", [])
+ if vector:
+ vector_list.append(vector)
+ ids.append(vec_data.get("id") or vec_data.get("vector_id", ""))
+
+ if self.include_text and "text" in vec_data:
+ texts.append(vec_data["text"])
+ else:
+ texts.append(None)
+
+ 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")
+
+ # Convert to numpy array
+ vector_array = np.array(vector_list)
+
+ # Save as .npz (compressed numpy format)
+ save_dict = {"vectors": vector_array, "ids": np.array(ids)}
+
+ if any(t for t in texts if t):
+ save_dict["texts"] = np.array(texts, dtype=object)
+
+ if any(m for m in metadata_list if m):
+ save_dict["metadata"] = np.array(metadata_list, dtype=object)
+
+ np.savez_compressed(file_path, **save_dict)
+
+ # Also save metadata separately as JSON
+ 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],
+ "shape": list(vector_array.shape)
+ }
+ write_json_file(metadata, metadata_file)
+
+ def _export_binary(
+ self,
+ vectors: List[Dict[str, Any]],
+ file_path: Path,
+ **options
+ ) -> None:
+ """Export to binary format."""
+ try:
+ import numpy as np
+ except ImportError:
+ raise ImportError("NumPy not installed. Install with: pip install numpy")
+
+ # Extract vectors
+ vector_list = []
+ for vec_data in vectors:
+ vector = vec_data.get("vector") or vec_data.get("embedding", [])
+ if vector:
+ vector_list.append(vector)
+
+ if not vector_list:
+ raise ValidationError("No vectors to export")
+
+ # Convert to numpy array
+ vector_array = np.array(vector_list, dtype=np.float32)
+
+ # Save as binary
+ vector_array.tofile(file_path)
+
+ # Save metadata
+ 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],
+ "shape": list(vector_array.shape),
+ "dtype": "float32"
+ }
+ write_json_file(metadata, metadata_file)
+
+ def _export_faiss(
+ self,
+ vectors: List[Dict[str, Any]],
+ file_path: Path,
+ **options
+ ) -> None:
+ """Export to FAISS index format."""
+ try:
+ import faiss
+ import numpy as np
+ except ImportError:
+ raise ImportError("FAISS not installed. Install with: pip install faiss-cpu or faiss-gpu")
+
+ # Extract vectors
+ vector_list = []
+ ids = []
+
+ for vec_data in vectors:
+ vector = vec_data.get("vector") or vec_data.get("embedding", [])
+ if vector:
+ vector_list.append(vector)
+ ids.append(vec_data.get("id") or vec_data.get("vector_id", ""))
+
+ if not vector_list:
+ raise ValidationError("No vectors to export")
+
+ # Convert to numpy array
+ vector_array = np.array(vector_list, dtype=np.float32)
+
+ # Create FAISS index
+ dimension = vector_array.shape[1]
+ index = faiss.IndexFlatL2(dimension)
+
+ # Normalize vectors if requested
+ if options.get("normalize", False):
+ faiss.normalize_L2(vector_array)
+
+ # Add vectors to index
+ index.add(vector_array)
+
+ # Save index
+ faiss.write_index(index, str(file_path))
+
+ # Save ID mapping
+ id_file = file_path.parent / f"{file_path.stem}_ids.json"
+ id_mapping = {
+ "ids": ids,
+ "vector_count": len(ids),
+ "dimension": dimension
+ }
+ write_json_file(id_mapping, id_file)
+
+ def export_for_vector_store(
+ self,
+ vectors: List[Dict[str, Any]],
+ file_path: Union[str, Path],
+ vector_store_type: str = "pinecone",
+ **options
+ ) -> None:
+ """
+ Export in format suitable for specific vector store.
+
+ Args:
+ vectors: List of vector dictionaries
+ file_path: Output file path
+ vector_store_type: Vector store type ('pinecone', 'weaviate', 'qdrant', 'faiss')
+ **options: Additional options
+ """
+ if vector_store_type == "pinecone":
+ self._export_pinecone_format(vectors, file_path, **options)
+ elif vector_store_type == "weaviate":
+ self._export_weaviate_format(vectors, file_path, **options)
+ elif vector_store_type == "qdrant":
+ self._export_qdrant_format(vectors, file_path, **options)
+ elif vector_store_type == "faiss":
+ self._export_faiss(vectors, file_path, **options)
+ else:
+ # Default to JSON
+ self._export_json(vectors, Path(file_path), {}, **options)
+
+ def _export_pinecone_format(
+ self,
+ vectors: List[Dict[str, Any]],
+ file_path: Path,
+ **options
+ ) -> None:
+ """Export in Pinecone format."""
+ pinecone_data = []
+
+ for vec_data in vectors:
+ vector_id = vec_data.get("id") or vec_data.get("vector_id", "")
+ vector = vec_data.get("vector") or vec_data.get("embedding", [])
+ metadata = vec_data.get("metadata", {})
+
+ if "text" in vec_data and self.include_text:
+ metadata["text"] = vec_data["text"]
+
+ pinecone_data.append({
+ "id": vector_id,
+ "values": vector,
+ "metadata": metadata
+ })
+
+ export_data = {"vectors": pinecone_data}
+ write_json_file(export_data, file_path, indent=2)
+
+ def _export_weaviate_format(
+ self,
+ vectors: List[Dict[str, Any]],
+ file_path: Path,
+ **options
+ ) -> None:
+ """Export in Weaviate format."""
+ weaviate_data = []
+
+ for vec_data in vectors:
+ vector_id = vec_data.get("id") or vec_data.get("vector_id", "")
+ vector = vec_data.get("vector") or vec_data.get("embedding", [])
+
+ weaviate_obj = {
+ "id": vector_id,
+ "vector": vector
+ }
+
+ if "text" in vec_data and self.include_text:
+ weaviate_obj["text"] = vec_data["text"]
+
+ if "metadata" in vec_data and self.include_metadata:
+ weaviate_obj.update(vec_data["metadata"])
+
+ weaviate_data.append(weaviate_obj)
+
+ export_data = {"objects": weaviate_data}
+ write_json_file(export_data, file_path, indent=2)
+
+ def _export_qdrant_format(
+ self,
+ vectors: List[Dict[str, Any]],
+ file_path: Path,
+ **options
+ ) -> None:
+ """Export in Qdrant format."""
+ qdrant_data = []
+
+ for vec_data in vectors:
+ vector_id = vec_data.get("id") or vec_data.get("vector_id", "")
+ vector = vec_data.get("vector") or vec_data.get("embedding", [])
+ payload = vec_data.get("metadata", {})
+
+ if "text" in vec_data and self.include_text:
+ payload["text"] = vec_data["text"]
+
+ qdrant_data.append({
+ "id": vector_id,
+ "vector": vector,
+ "payload": payload
+ })
+
+ export_data = {"points": qdrant_data}
+ write_json_file(export_data, file_path, indent=2)
+
diff --git a/libs/semantica/export/yaml_exporter.py b/libs/semantica/export/yaml_exporter.py
index caf25932..ab897073 100644
--- a/libs/semantica/export/yaml_exporter.py
+++ b/libs/semantica/export/yaml_exporter.py
@@ -6,6 +6,14 @@ for human-readable representation and intermediate processing in the
6-stage ontology generation pipeline.
"""
+from typing import Any, Dict, List, Optional, Union
+from pathlib import Path
+from datetime import datetime
+
+from ..utils.exceptions import ValidationError, ProcessingError
+from ..utils.logging import get_logger
+from ..utils.helpers import ensure_directory
+
class SemanticNetworkYAMLExporter:
"""
@@ -28,9 +36,16 @@ class SemanticNetworkYAMLExporter:
• Configure output formatting
• Initialize schema templates
"""
- pass
+ self.logger = get_logger("yaml_exporter")
+ self.config = config or {}
+
+ try:
+ import yaml
+ self.yaml = yaml
+ except ImportError:
+ raise ImportError("PyYAML not installed. Install with: pip install pyyaml")
- def export_semantic_network(self, semantic_network, **options):
+ def export_semantic_network(self, semantic_network: Dict[str, Any], **options) -> str:
"""
Export semantic network to YAML.
@@ -39,9 +54,44 @@ class SemanticNetworkYAMLExporter:
• Include metadata and provenance
• Return YAML string
"""
- pass
+ yaml_data = {
+ "metadata": {
+ "exported_at": datetime.now().isoformat(),
+ "version": "1.0",
+ **semantic_network.get("metadata", {})
+ },
+ "entities": semantic_network.get("entities", []),
+ "relationships": semantic_network.get("relationships", []),
+ "triples": semantic_network.get("triples", [])
+ }
+
+ return self.yaml.dump(yaml_data, default_flow_style=False, sort_keys=False)
+
+ def export(
+ self,
+ data: Dict[str, Any],
+ file_path: Union[str, Path],
+ **options
+ ) -> None:
+ """
+ Export data to YAML file.
+
+ Args:
+ data: Data to export
+ file_path: Output file path
+ **options: Additional options
+ """
+ file_path = Path(file_path)
+ ensure_directory(file_path.parent)
+
+ yaml_content = self.export_semantic_network(data, **options)
+
+ with open(file_path, "w", encoding="utf-8") as f:
+ f.write(yaml_content)
+
+ self.logger.info(f"Exported YAML to: {file_path}")
- def export_entities(self, entities, include_metadata=True, **options):
+ def export_entities(self, entities: List[Dict[str, Any]], include_metadata: bool = True, **options) -> str:
"""
Export entities to YAML format.
@@ -50,9 +100,19 @@ class SemanticNetworkYAMLExporter:
• Add confidence scores
• Return YAML representation
"""
- pass
+ yaml_data = {
+ "entities": entities
+ }
+
+ if include_metadata:
+ yaml_data["metadata"] = {
+ "exported_at": datetime.now().isoformat(),
+ "entity_count": len(entities)
+ }
+
+ return self.yaml.dump(yaml_data, default_flow_style=False, sort_keys=False)
- def export_relationships(self, relationships, include_properties=True, **options):
+ def export_relationships(self, relationships: List[Dict[str, Any]], include_properties: bool = True, **options) -> str:
"""
Export relationships to YAML format.
@@ -61,9 +121,19 @@ class SemanticNetworkYAMLExporter:
• Add directional information
• Return YAML representation
"""
- pass
+ yaml_data = {
+ "relationships": relationships
+ }
+
+ if include_properties:
+ yaml_data["metadata"] = {
+ "exported_at": datetime.now().isoformat(),
+ "relationship_count": len(relationships)
+ }
+
+ return self.yaml.dump(yaml_data, default_flow_style=False, sort_keys=False)
- def export_triples(self, triples, include_confidence=True, **options):
+ def export_triples(self, triples: List[Dict[str, Any]], include_confidence: bool = True, **options) -> str:
"""
Export RDF triples to YAML format.
@@ -72,9 +142,27 @@ class SemanticNetworkYAMLExporter:
• Add confidence and provenance
• Return YAML representation
"""
- pass
+ yaml_data = {
+ "triples": [
+ {
+ "subject": t.get("subject") or t.get("s"),
+ "predicate": t.get("predicate") or t.get("p"),
+ "object": t.get("object") or t.get("o"),
+ **({"confidence": t.get("confidence")} if include_confidence and "confidence" in t else {}),
+ **({"provenance": t.get("provenance")} if "provenance" in t else {})
+ }
+ for t in triples
+ ]
+ }
+
+ yaml_data["metadata"] = {
+ "exported_at": datetime.now().isoformat(),
+ "triple_count": len(triples)
+ }
+
+ return self.yaml.dump(yaml_data, default_flow_style=False, sort_keys=False)
- def export_for_pipeline(self, extracted_data, pipeline_stage=2, **options):
+ def export_for_pipeline(self, extracted_data: Dict[str, Any], pipeline_stage: int = 2, **options) -> str:
"""
Export in format suitable for ontology generation pipeline.
@@ -83,7 +171,20 @@ class SemanticNetworkYAMLExporter:
• Include extraction metadata
• Return pipeline-ready YAML
"""
- pass
+ yaml_data = {
+ "pipeline_stage": pipeline_stage,
+ "metadata": {
+ "extracted_at": datetime.now().isoformat(),
+ **extracted_data.get("metadata", {})
+ },
+ "semantic_network": {
+ "entities": extracted_data.get("entities", []),
+ "relationships": extracted_data.get("relationships", []),
+ "triples": extracted_data.get("triples", [])
+ }
+ }
+
+ return self.yaml.dump(yaml_data, default_flow_style=False, sort_keys=False)
class YAMLSchemaExporter:
@@ -96,9 +197,16 @@ class YAMLSchemaExporter:
def __init__(self, **config):
"""Initialize schema exporter."""
- pass
+ self.logger = get_logger("yaml_schema_exporter")
+ self.config = config or {}
+
+ try:
+ import yaml
+ self.yaml = yaml
+ except ImportError:
+ raise ImportError("PyYAML not installed. Install with: pip install pyyaml")
- def export_ontology_schema(self, ontology, **options):
+ def export_ontology_schema(self, ontology: Dict[str, Any], **options) -> str:
"""
Export ontology schema to YAML.
@@ -107,12 +215,76 @@ class YAMLSchemaExporter:
• Structure for easy editing
• Return YAML schema
"""
- pass
+ yaml_data = {
+ "ontology": {
+ "uri": ontology.get("uri", ""),
+ "title": ontology.get("title", ""),
+ "description": ontology.get("description", ""),
+ "version": ontology.get("version", "1.0")
+ },
+ "classes": ontology.get("classes", []),
+ "properties": ontology.get("properties", []),
+ "namespaces": ontology.get("namespaces", {})
+ }
+
+ return self.yaml.dump(yaml_data, default_flow_style=False, sort_keys=False)
- def export_class_definitions(self, classes, include_hierarchy=True, **options):
+ def export_class_definitions(self, classes: List[Dict[str, Any]], include_hierarchy: bool = True, **options) -> str:
"""Export class definitions to YAML."""
- pass
+ yaml_data = {
+ "classes": classes
+ }
+
+ if include_hierarchy:
+ yaml_data["hierarchy"] = self._extract_hierarchy(classes)
+
+ return self.yaml.dump(yaml_data, default_flow_style=False, sort_keys=False)
- def export_property_definitions(self, properties, include_domain_range=True, **options):
+ def export_property_definitions(self, properties: List[Dict[str, Any]], include_domain_range: bool = True, **options) -> str:
"""Export property definitions to YAML."""
- pass
+ yaml_data = {
+ "properties": properties
+ }
+
+ if include_domain_range:
+ yaml_data["domain_range"] = self._extract_domain_range(properties)
+
+ return self.yaml.dump(yaml_data, default_flow_style=False, sort_keys=False)
+
+ def _extract_hierarchy(self, classes: List[Dict[str, Any]]) -> Dict[str, Any]:
+ """Extract class hierarchy."""
+ hierarchy = {}
+
+ for cls in classes:
+ class_id = cls.get("id") or cls.get("uri", "")
+ parent = cls.get("parent") or cls.get("subClassOf")
+
+ if class_id:
+ hierarchy[class_id] = {
+ "label": cls.get("label", ""),
+ "parent": parent,
+ "children": []
+ }
+
+ # Build children relationships
+ for class_id, class_info in hierarchy.items():
+ parent = class_info.get("parent")
+ if parent and parent in hierarchy:
+ hierarchy[parent]["children"].append(class_id)
+
+ return hierarchy
+
+ def _extract_domain_range(self, properties: List[Dict[str, Any]]) -> Dict[str, Any]:
+ """Extract property domain and range."""
+ domain_range = {}
+
+ for prop in properties:
+ prop_id = prop.get("id") or prop.get("uri", "")
+ if prop_id:
+ domain_range[prop_id] = {
+ "label": prop.get("label", ""),
+ "domain": prop.get("domain", []),
+ "range": prop.get("range", [])
+ }
+
+ return domain_range