Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
Organize export folder structure and add LPG export support
KaifAhmad1a0a4fdfb13da
diff --git a/semantica/export/__init__.py b/semantica/export/__init__.pyindex e81ee2b6..d30f7707 100644--- a/semantica/export/__init__.py+++ b/semantica/export/__init__.py@@ -2,15 +2,87 @@Export and Reporting ModuleThis module provides comprehensive export and reporting capabilities for the-Semantica framework, supporting multiple formats and use cases.+Semantica framework, supporting multiple formats and use cases including RDF,+JSON, CSV, Graph, YAML, OWL, Vector, and LPG (Labeled Property Graph) formats.++Algorithms Used:++RDF Export:+ - RDF Serialization: Multiple format serialization (Turtle, RDF/XML, JSON-LD, N-Triples, N3)+ - Namespace Management: Namespace registration, conflict resolution, declaration generation+ - RDF Validation: RDF syntax validation, triple validation, namespace validation+ - URI Generation: Hash-based and text-based URI assignment for RDF resources+ - Triple Extraction: Entity and relationship to RDF triple conversion+ - Format Conversion: Cross-format RDF conversion algorithms++LPG (Labeled Property Graph) Export:+ - LPG Serialization: Labeled Property Graph format for Neo4j, Memgraph, and similar databases+ - Node Label Assignment: Entity type to node label mapping+ - Relationship Type Mapping: Relationship type to edge label conversion+ - Property Serialization: Entity and relationship properties to LPG property format+ - Cypher Query Generation: Cypher CREATE statements for graph database import+ - Batch Node/Relationship Export: Efficient batch processing for large graphs+ - Index Generation: Index and constraint generation for graph databases++JSON/JSON-LD Export:+ - JSON Serialization: Standard JSON serialization with configurable indentation+ - JSON-LD Context Management: @context generation and management+ - Knowledge Graph Serialization: Graph structure to JSON/JSON-LD conversion+ - Metadata Embedding: Provenance and metadata serialization in JSON structure+ - Pretty Printing: Formatted JSON output with indentation++CSV Export:+ - Tabular Serialization: Entity and relationship to CSV row conversion+ - Field Extraction: Dynamic field name extraction from data structures+ - Delimiter Handling: Configurable delimiter support (comma, tab, semicolon)+ - Header Generation: Automatic CSV header row generation+ - Metadata Serialization: JSON string serialization for complex metadata fields+ - Multi-file Export: Knowledge graph split into multiple CSV files (entities, relationships)++Graph Export:+ - GraphML Serialization: GraphML format generation for graph visualization tools+ - GEXF Serialization: GEXF format generation for Gephi and similar tools+ - DOT Serialization: Graphviz DOT format generation+ - Node/Edge Attribute Mapping: Property to graph attribute conversion+ - Graph Structure Conversion: Knowledge graph to graph format transformation++YAML Export:+ - YAML Serialization: Human-readable YAML format generation+ - Semantic Network Export: Entity-relationship network to YAML conversion+ - Schema Export: Ontology schema to YAML for human editing+ - Pipeline Integration: Stage-specific YAML export for ontology generation pipeline++OWL Export:+ - OWL-XML Serialization: OWL/XML format generation+ - Turtle Serialization: OWL in Turtle format+ - Class Hierarchy Export: Class definition and hierarchy serialization+ - Property Export: Object and data property definition export+ - OWL 2.0 Feature Support: Advanced OWL features (cardinality, restrictions, etc.)+ - Ontology Validation: OWL syntax and semantic validation++Vector Export:+ - Vector Serialization: Multiple format support (JSON, NumPy, Binary, FAISS)+ - Vector Store Integration: Format conversion for Pinecone, Weaviate, Qdrant, FAISS+ - Metadata Association: Vector-to-metadata mapping and serialization+ - Batch Export: Efficient batch vector export processing+ - Multi-dimensional Support: Variable dimension vector handling++Report Generation:+ - Template Rendering: Template-based report generation (HTML, Markdown, JSON, Text)+ - Quality Metrics Aggregation: Statistical aggregation of quality metrics+ - Chart Generation: Visualization and chart generation (if enabled)+ - Format Conversion: Cross-format report conversion+ - Section Organization: Hierarchical report section organizationKey Features:- - Multiple export formats (RDF, JSON, CSV, Graph, YAML, OWL, Vector)- - Knowledge graph export+ - Multiple export formats (RDF, JSON, CSV, Graph, YAML, OWL, Vector, LPG)+ - Knowledge graph export with format auto-detection- Report generation (HTML, Markdown, JSON, Text)- Vector store integration- Batch export processing- Metadata and provenance tracking+ - Method registry for extensibility+ - Configuration management with environment variables and config filesMain Classes:- RDFExporter: RDF format export (Turtle, RDF/XML, JSON-LD)@@ -20,14 +92,31 @@ Main Classes:- YAMLExporter: YAML format export for semantic networks- OWLExporter: OWL format export for ontologies- VectorExporter: Vector embedding export for vector stores+ - LPGExporter: LPG format export for Neo4j, Memgraph, and similar databases- ReportGenerator: Report generation (HTML, Markdown, JSON, Text)+ - MethodRegistry: Registry for custom export methods+ - ExportConfig: Configuration manager for export module++Convenience Functions:+ - export_knowledge_graph: Unified knowledge graph export with format dispatch+ - export_rdf: RDF export wrapper+ - export_json: JSON/JSON-LD export wrapper+ - export_csv: CSV export wrapper+ - export_graph: Graph format export wrapper+ - export_yaml: YAML export wrapper+ - export_owl: OWL export wrapper+ - export_vector: Vector export wrapper+ - export_lpg: LPG export wrapper+ - generate_report: Report generation wrapperExample Usage:- >>> from semantica.export import JSONExporter, CSVExporter+ >>> from semantica.export import export_knowledge_graph, export_lpg, JSONExporter+ >>> # Using convenience function+ >>> export_knowledge_graph(kg, "output.json", format="json")+ >>> export_lpg(kg, "output.cypher", method="cypher")+ >>> # Using classes directly>>> json_exporter = JSONExporter()>>> json_exporter.export_knowledge_graph(kg, "output.json")- >>> csv_exporter = CSVExporter()- >>> csv_exporter.export_entities(entities, "entities.csv")Author: Semantica ContributorsLicense: MIT@@ -49,8 +138,26 @@ from .yaml_exporter import (from .report_generator import ReportGeneratorfrom .owl_exporter import OWLExporterfrom .vector_exporter import VectorExporter+from .lpg_exporter import LPGExporter+from .registry import MethodRegistry, method_registry+from .methods import (+ export_rdf,+ export_json,+ export_csv,+ export_graph,+ export_yaml,+ export_owl,+ export_vector,+ export_lpg,+ generate_report,+ export_knowledge_graph,+ get_export_method,+ list_available_methods,+)+from .config import ExportConfig, export_config__all__ = [+ # Core Exporters"RDFExporter","RDFSerializer","RDFValidator",@@ -63,4 +170,23 @@ __all__ = ["ReportGenerator","OWLExporter","VectorExporter",+ "LPGExporter",+ # Registry and Methods+ "MethodRegistry",+ "method_registry",+ "export_rdf",+ "export_json",+ "export_csv",+ "export_graph",+ "export_yaml",+ "export_owl",+ "export_vector",+ "export_lpg",+ "generate_report",+ "export_knowledge_graph",+ "get_export_method",+ "list_available_methods",+ # Configuration+ "ExportConfig",+ "export_config",]diff --git a/semantica/export/config.py b/semantica/export/config.pynew file mode 100644index 00000000..9343f8b8--- /dev/null+++ b/semantica/export/config.py@@ -0,0 +1,173 @@+"""+Configuration Management Module for Export++This module provides centralized configuration management for export operations,+supporting multiple configuration sources including environment variables, config files,+and programmatic configuration.++Supported Configuration Sources:+ - Environment variables: EXPORT_DEFAULT_FORMAT, EXPORT_OUTPUT_DIR, EXPORT_INCLUDE_METADATA, etc.+ - Config files: YAML, JSON, TOML formats+ - Programmatic: Python API for setting export configurations++Algorithms Used:+ - Environment Variable Parsing: OS-level environment variable access+ - YAML Parsing: YAML parser for configuration file loading+ - JSON Parsing: JSON parser for configuration file loading+ - TOML Parsing: TOML parser for configuration file loading+ - Fallback Chain: Priority-based configuration resolution+ - Dictionary Merging: Deep merge algorithms for configuration updates++Key Features:+ - Environment variable support for export parameters+ - Config file support (YAML, JSON, TOML formats)+ - Programmatic configuration via Python API+ - Method-specific configuration management+ - Automatic fallback chain (config file -> environment -> defaults)+ - Global config instance for easy access++Main Classes:+ - ExportConfig: Main configuration manager class for export module++Example Usage:+ >>> from semantica.export.config import export_config+ >>> format = export_config.get("default_format", default="json")+ >>> export_config.set("default_format", "json-ld")+ >>> method_config = export_config.get_method_config("rdf")+"""++import os+from typing import Optional, Dict, Any+from pathlib import Path++from ..utils.logging import get_logger+++class ExportConfig:+ """Configuration manager for export module - supports .env files, environment variables, and programmatic config."""++ def __init__(self, config_file: Optional[str] = None):+ """Initialize configuration manager."""+ self.logger = get_logger("export_config")+ self._configs: Dict[str, Any] = {}+ self._method_configs: Dict[str, Dict] = {}+ self._load_config_file(config_file)+ self._load_env_vars()++ def _load_config_file(self, config_file: Optional[str]):+ """Load configuration from file."""+ if config_file and Path(config_file).exists():+ try:+ # Support YAML, JSON, TOML+ if config_file.endswith('.yaml') or config_file.endswith('.yml'):+ import yaml+ with open(config_file, 'r') as f:+ data = yaml.safe_load(f) or {}+ self._configs.update(data.get("export", {}))+ self._method_configs.update(data.get("export_methods", {}))+ elif config_file.endswith('.json'):+ import json+ with open(config_file, 'r') as f:+ data = json.load(f) or {}+ self._configs.update(data.get("export", {}))+ self._method_configs.update(data.get("export_methods", {}))+ elif config_file.endswith('.toml'):+ import toml+ with open(config_file, 'r') as f:+ data = toml.load(f) or {}+ if "export" in data:+ self._configs.update(data["export"])+ if "export_methods" in data:+ self._method_configs.update(data["export_methods"])+ self.logger.info(f"Loaded export config from {config_file}")+ except Exception as e:+ self.logger.warning(f"Failed to load config file {config_file}: {e}")++ def _load_env_vars(self):+ """Load configuration from environment variables."""+ # Export-specific environment variables with EXPORT_ prefix+ env_mappings = {+ "EXPORT_DEFAULT_FORMAT": ("default_format", str),+ "EXPORT_OUTPUT_DIR": ("output_dir", str),+ "EXPORT_INCLUDE_METADATA": ("include_metadata", bool),+ "EXPORT_INDENT": ("indent", int),+ "EXPORT_ENCODING": ("encoding", str),+ "EXPORT_DELIMITER": ("delimiter", str),+ "EXPORT_NAMESPACE_BASE": ("namespace_base", str),+ "EXPORT_VALIDATE": ("validate", bool),+ }++ for env_key, (config_key, type_func) in env_mappings.items():+ value = os.getenv(env_key)+ if value:+ try:+ if type_func == bool:+ self._configs[config_key] = value.lower() in ("true", "1", "yes", "on")+ else:+ self._configs[config_key] = type_func(value)+ except (ValueError, TypeError):+ self.logger.warning(f"Failed to parse {env_key}={value}")++ # Also check for any EXPORT_ prefixed variables+ env_prefix = "EXPORT_"+ for key, value in os.environ.items():+ if key.startswith(env_prefix) and key not in env_mappings:+ config_key = key[len(env_prefix):].lower()+ # Try to convert to appropriate type+ if value.lower() in ('true', 'false'):+ self._configs[config_key] = value.lower() == 'true'+ elif value.isdigit():+ self._configs[config_key] = int(value)+ else:+ try:+ self._configs[config_key] = float(value)+ except ValueError:+ self._configs[config_key] = value++ def set(self, key: str, value: Any):+ """Set configuration value programmatically."""+ self._configs[key] = value++ def get(self, key: str, default: Any = None) -> Any:+ """Get configuration value with fallback chain: config -> env -> default."""+ # Check config first+ if key in self._configs:+ return self._configs[key]++ # Check environment variables+ env_key = f"EXPORT_{key.upper()}"+ value = os.getenv(env_key)+ if value:+ try:+ # Try to convert to appropriate type+ if isinstance(default, int):+ return int(value)+ elif isinstance(default, float):+ return float(value)+ elif isinstance(default, bool):+ return value.lower() in ("true", "1", "yes", "on")+ return value+ except (ValueError, TypeError):+ pass++ return default++ def set_method_config(self, method: str, **config):+ """Set method-specific configuration."""+ self._method_configs[method] = config++ def get_method_config(self, method: str) -> Dict:+ """Get method-specific configuration."""+ return self._method_configs.get(method, {})++ def get_all(self) -> Dict[str, Any]:+ """Get all configuration."""+ return {+ "config": self._configs.copy(),+ "method_configs": self._method_configs.copy()+ }+++# Global config instance+export_config = ExportConfig()+diff --git a/semantica/export/export_usage.md b/semantica/export/export_usage.mdnew file mode 100644index 00000000..90e30f93--- /dev/null+++ b/semantica/export/export_usage.md@@ -0,0 +1,877 @@+# Export Module Usage Guide++This guide demonstrates how to use the export module for exporting knowledge graphs, entities, relationships, and data to various formats including RDF, JSON, CSV, Graph, YAML, OWL, Vector, and LPG formats.++## Table of Contents++1. [Basic Usage](#basic-usage)+2. [RDF Export](#rdf-export)+3. [JSON/JSON-LD Export](#jsonjson-ld-export)+4. [CSV Export](#csv-export)+5. [Graph Export](#graph-export)+6. [YAML Export](#yaml-export)+7. [OWL Export](#owl-export)+8. [Vector Export](#vector-export)+9. [LPG Export](#lpg-export)+10. [Report Generation](#report-generation)+11. [Knowledge Graph Export](#knowledge-graph-export)+12. [Using Methods](#using-methods)+13. [Using Registry](#using-registry)+14. [Configuration](#configuration)+15. [Advanced Examples](#advanced-examples)++## Basic Usage++### Using the Convenience Function++```python+from semantica.export import export_knowledge_graph++# Export knowledge graph to JSON+kg = {+ "entities": [...],+ "relationships": [...],+ "metadata": {...}+}++export_knowledge_graph(kg, "output.json", format="json")+export_knowledge_graph(kg, "output.ttl", format="turtle")+export_knowledge_graph(kg, "output.cypher", format="cypher")+```++### Using Main Classes++```python+from semantica.export import JSONExporter, RDFExporter, LPGExporter++# Create exporters+json_exporter = JSONExporter(indent=2)+rdf_exporter = RDFExporter()+lpg_exporter = LPGExporter()++# Export knowledge graph+json_exporter.export_knowledge_graph(kg, "output.json")+rdf_exporter.export(kg, "output.ttl", format="turtle")+lpg_exporter.export_knowledge_graph(kg, "output.cypher")+```++## RDF Export++### Turtle Format++```python+from semantica.export import RDFExporter++exporter = RDFExporter()++# Export to Turtle format+exporter.export(kg, "output.ttl", format="turtle")++# Export knowledge graph+exporter.export_knowledge_graph(kg, "kg.ttl", format="turtle")+```++### RDF/XML Format++```python+from semantica.export import RDFExporter++exporter = RDFExporter()++# Export to RDF/XML format+exporter.export(kg, "output.rdf", format="rdfxml")+```++### JSON-LD Format++```python+from semantica.export import RDFExporter++exporter = RDFExporter()++# Export to JSON-LD format+exporter.export(kg, "output.jsonld", format="jsonld")+```++### Using RDF Export Methods++```python+from semantica.export.methods import export_rdf++# Turtle format+export_rdf(kg, "output.ttl", format="turtle")++# RDF/XML format+export_rdf(kg, "output.rdf", format="rdfxml")++# JSON-LD format+export_rdf(kg, "output.jsonld", format="jsonld")+```++## JSON/JSON-LD Export++### Standard JSON Export++```python+from semantica.export import JSONExporter++exporter = JSONExporter(+ indent=2,+ ensure_ascii=False,+ format="json"+)++# Export knowledge graph+exporter.export_knowledge_graph(kg, "output.json")++# Export entities+exporter.export_entities(entities, "entities.json")+```++### JSON-LD Export++```python+from semantica.export import JSONExporter++exporter = JSONExporter(format="json-ld")++# Export knowledge graph as JSON-LD+exporter.export_knowledge_graph(kg, "output.jsonld", format="json-ld")+```++### Using JSON Export Methods++```python+from semantica.export.methods import export_json++# Standard JSON+export_json(kg, "output.json", format="json")++# JSON-LD+export_json(kg, "output.jsonld", format="json-ld")+```++## CSV Export++### Entity Export++```python+from semantica.export import CSVExporter++exporter = CSVExporter(+ delimiter=",",+ encoding="utf-8",+ include_header=True+)++# Export entities+exporter.export_entities(entities, "entities.csv")++# Export relationships+exporter.export_relationships(relationships, "relationships.csv")+```++### Knowledge Graph Export++```python+from semantica.export import CSVExporter++exporter = CSVExporter()++# Export knowledge graph to multiple CSV files+exporter.export_knowledge_graph(kg, "kg_base")+# Creates: kg_base_entities.csv, kg_base_relationships.csv+```++### Using CSV Export Methods++```python+from semantica.export.methods import export_csv++# Export entities+export_csv(entities, "entities.csv")++# Export knowledge graph+export_csv(kg, "kg_base")+```++## Graph Export++### GraphML Format++```python+from semantica.export import GraphExporter++exporter = GraphExporter(+ format="graphml",+ include_attributes=True+)++# Export knowledge graph+exporter.export_knowledge_graph(kg, "graph.graphml")+```++### GEXF Format++```python+from semantica.export import GraphExporter++exporter = GraphExporter(format="gexf")++# Export knowledge graph+exporter.export_knowledge_graph(kg, "graph.gexf", format="gexf")+```++### DOT Format++```python+from semantica.export import GraphExporter++exporter = GraphExporter(format="dot")++# Export knowledge graph+exporter.export_knowledge_graph(kg, "graph.dot", format="dot")+```++### Using Graph Export Methods++```python+from semantica.export.methods import export_graph++# GraphML+export_graph(graph_data, "graph.graphml", format="graphml")++# GEXF+export_graph(graph_data, "graph.gexf", format="gexf")++# DOT+export_graph(graph_data, "graph.dot", format="dot")+```++## YAML Export++### Semantic Network Export++```python+from semantica.export import SemanticNetworkYAMLExporter++exporter = SemanticNetworkYAMLExporter()++# Export semantic network+exporter.export(semantic_network, "network.yaml")+```++### Schema Export++```python+from semantica.export import YAMLSchemaExporter++exporter = YAMLSchemaExporter()++# Export schema+exporter.export(schema, "schema.yaml")+```++### Using YAML Export Methods++```python+from semantica.export.methods import export_yaml++# Semantic network+export_yaml(semantic_network, "network.yaml", method="semantic_network")++# Schema+export_yaml(schema, "schema.yaml", method="schema")+```++## OWL Export++### OWL/XML Format++```python+from semantica.export import OWLExporter++exporter = OWLExporter(+ ontology_uri="http://example.org/ontology#",+ version="1.0",+ format="owl-xml"+)++# Export ontology+exporter.export(ontology, "ontology.owl", format="owl-xml")+```++### Turtle Format++```python+from semantica.export import OWLExporter++exporter = OWLExporter(format="turtle")++# Export ontology in Turtle format+exporter.export(ontology, "ontology.ttl", format="turtle")+```++### Using OWL Export Methods++```python+from semantica.export.methods import export_owl++# OWL/XML+export_owl(ontology, "ontology.owl", format="owl-xml")++# Turtle+export_owl(ontology, "ontology.ttl", format="turtle")+```++## Vector Export++### JSON Format++```python+from semantica.export import VectorExporter++exporter = VectorExporter(+ format="json",+ include_metadata=True,+ include_text=True+)++# Export vectors+exporter.export(vectors, "vectors.json")+```++### NumPy Format++```python+from semantica.export import VectorExporter++exporter = VectorExporter(format="numpy")++# Export vectors+exporter.export(vectors, "vectors.npy", format="numpy")+```++### FAISS Format++```python+from semantica.export import VectorExporter++exporter = VectorExporter(format="faiss")++# Export vectors for FAISS+exporter.export(vectors, "vectors.faiss", format="faiss")+```++### Using Vector Export Methods++```python+from semantica.export.methods import export_vector++# JSON+export_vector(vectors, "vectors.json", format="json")++# NumPy+export_vector(vectors, "vectors.npy", format="numpy")++# FAISS+export_vector(vectors, "vectors.faiss", format="faiss")+```++## LPG Export++### Cypher Query Export++```python+from semantica.export import LPGExporter++exporter = LPGExporter(+ batch_size=1000,+ include_indexes=True+)++# Export knowledge graph to Cypher queries+exporter.export_knowledge_graph(kg, "graph.cypher")+```++### Using LPG Export Methods++```python+from semantica.export.methods import export_lpg++# Export to Cypher format+export_lpg(kg, "graph.cypher", method="cypher")+```++### Importing into Neo4j++```python+from semantica.export import LPGExporter++exporter = LPGExporter()++# Export to Cypher file+exporter.export_knowledge_graph(kg, "graph.cypher")++# Then import into Neo4j using cypher-shell:+# cypher-shell -u neo4j -p password < graph.cypher+```++### Importing into Memgraph++```python+from semantica.export import LPGExporter++exporter = LPGExporter()++# Export to Cypher file+exporter.export_knowledge_graph(kg, "graph.cypher")++# Then import into Memgraph using mgconsole:+# mgconsole < graph.cypher+```++## Report Generation++### HTML Report++```python+from semantica.export import ReportGenerator++generator = ReportGenerator(+ format="html",+ include_charts=True+)++# Generate report+generator.generate_report(data, "report.html", format="html")+```++### Markdown Report++```python+from semantica.export import ReportGenerator++generator = ReportGenerator(format="markdown")++# Generate report+generator.generate_report(data, "report.md", format="markdown")+```++### Quality Report++```python+from semantica.export import ReportGenerator++generator = ReportGenerator()++# Generate quality report+generator.generate_quality_report(metrics, "quality.md", format="markdown")+```++### Using Report Generation Methods++```python+from semantica.export.methods import generate_report++# HTML report+generate_report(data, "report.html", format="html")++# Markdown report+generate_report(data, "report.md", format="markdown")+```++## Knowledge Graph Export++### Unified Export Function++```python+from semantica.export.methods import export_knowledge_graph++kg = {+ "entities": [...],+ "relationships": [...],+ "metadata": {...}+}++# Auto-detect format from file extension+export_knowledge_graph(kg, "output.json") # JSON format+export_knowledge_graph(kg, "output.ttl") # Turtle format+export_knowledge_graph(kg, "output.cypher") # Cypher format++# Explicit format specification+export_knowledge_graph(kg, "output.json", format="json-ld")+export_knowledge_graph(kg, "output.rdf", format="rdfxml")+```++### Multiple Format Export++```python+from semantica.export.methods import export_knowledge_graph++kg = {...}++# Export to multiple formats+formats = ["json", "turtle", "csv", "cypher"]+for fmt in formats:+ export_knowledge_graph(kg, f"output.{fmt}", format=fmt)+```++## Using Methods++### Format-Specific Methods++```python+from semantica.export.methods import (+ export_rdf,+ export_json,+ export_csv,+ export_graph,+ export_yaml,+ export_owl,+ export_vector,+ export_lpg+)++# RDF export+export_rdf(kg, "output.ttl", format="turtle")++# JSON export+export_json(kg, "output.json", format="json")++# CSV export+export_csv(entities, "entities.csv")++# Graph export+export_graph(graph_data, "graph.graphml", format="graphml")++# YAML export+export_yaml(semantic_network, "network.yaml")++# OWL export+export_owl(ontology, "ontology.owl", format="owl-xml")++# Vector export+export_vector(vectors, "vectors.json", format="json")++# LPG export+export_lpg(kg, "graph.cypher", method="cypher")+```++## Using Registry++### Registering Custom Methods++```python+from semantica.export.registry import method_registry++def custom_json_export(data, file_path, **kwargs):+ """Custom JSON export function."""+ # Your custom implementation+ pass++# Register custom method+method_registry.register("json", "custom_method", custom_json_export)++# Use custom method+from semantica.export.methods import export_json+export_json(data, "output.json", method="custom_method")+```++### Listing Available Methods++```python+from semantica.export.methods import list_available_methods++# List all methods+all_methods = list_available_methods()+print(all_methods)++# List methods for specific task+json_methods = list_available_methods("json")+print(json_methods)+```++### Getting Registered Methods++```python+from semantica.export.methods import get_export_method++# Get method from registry+method = get_export_method("json", "custom_method")+if method:+ method(data, "output.json")+```++## Configuration++### Environment Variables++```bash+# Set export configuration via environment variables+export EXPORT_DEFAULT_FORMAT="json"+export EXPORT_OUTPUT_DIR="./exports"+export EXPORT_INCLUDE_METADATA="true"+export EXPORT_INDENT=2+export EXPORT_ENCODING="utf-8"+export EXPORT_DELIMITER=","+export EXPORT_NAMESPACE_BASE="http://example.org/ns#"+export EXPORT_VALIDATE="true"+```++### Programmatic Configuration++```python+from semantica.export.config import export_config++# Set configuration+export_config.set("default_format", "json")+export_config.set("output_dir", "./exports")+export_config.set("include_metadata", True)++# Get configuration+format = export_config.get("default_format", default="json")+output_dir = export_config.get("output_dir", default="./")++# Method-specific configuration+export_config.set_method_config("rdf", format="turtle")+rdf_config = export_config.get_method_config("rdf")+```++### Config File (YAML)++```yaml+export:+ default_format: "json"+ output_dir: "./exports"+ include_metadata: true+ indent: 2+ encoding: "utf-8"+ delimiter: ","+ namespace_base: "http://example.org/ns#"+ validate: true++export_methods:+ rdf:+ format: "turtle"+ validate: true+ json:+ indent: 2+ ensure_ascii: false+ csv:+ delimiter: ","+ include_header: true+ lpg:+ batch_size: 1000+ include_indexes: true+```++```python+from semantica.export.config import ExportConfig++# Load from config file+config = ExportConfig(config_file="config.yaml")+```++## Advanced Examples++### Complete Export Pipeline++```python+from semantica.export.methods import (+ export_knowledge_graph,+ export_rdf,+ export_lpg+)++kg = {+ "entities": [...],+ "relationships": [...],+ "metadata": {...}+}++# Export to multiple formats+export_knowledge_graph(kg, "output.json", format="json")+export_rdf(kg, "output.ttl", format="turtle")+export_lpg(kg, "output.cypher", method="cypher")+```++### Batch Export with Format Detection++```python+from semantica.export.methods import export_knowledge_graph+from pathlib import Path++kg = {...}++# Export to multiple formats based on file extensions+output_files = [+ "output.json",+ "output.ttl",+ "output.csv",+ "output.cypher",+ "output.graphml"+]++for file_path in output_files:+ export_knowledge_graph(kg, file_path)+ # Format auto-detected from extension+```++### Custom Export Method++```python+from semantica.export.registry import method_registry+from semantica.export.methods import export_json++def custom_jsonld_export(data, file_path, **kwargs):+ """Custom JSON-LD export with specific context."""+ from semantica.export import JSONExporter++ exporter = JSONExporter(format="json-ld")++ # Add custom context+ if isinstance(data, dict) and "@context" not in data:+ data["@context"] = {+ "@vocab": "http://example.org/vocab#",+ "ex": "http://example.org/ns#"+ }++ exporter.export(data, file_path, format="json-ld", **kwargs)++# Register custom method+method_registry.register("json", "custom_jsonld", custom_jsonld_export)++# Use custom method+export_json(kg, "output.jsonld", method="custom_jsonld")+```++### LPG Export with Custom Configuration++```python+from semantica.export import LPGExporter++# Custom LPG exporter configuration+exporter = LPGExporter(+ batch_size=5000, # Larger batches for big graphs+ include_indexes=True+)++# Export large knowledge graph+exporter.export_knowledge_graph(large_kg, "large_graph.cypher")+```++### Multi-Format Knowledge Graph Export++```python+from semantica.export.methods import export_knowledge_graph++kg = {...}++# Export to all supported formats+formats = {+ "json": "output.json",+ "json-ld": "output.jsonld",+ "turtle": "output.ttl",+ "rdfxml": "output.rdf",+ "csv": "output_base",+ "graphml": "graph.graphml",+ "cypher": "graph.cypher",+ "yaml": "network.yaml",+ "owl": "ontology.owl"+}++for format_name, file_path in formats.items():+ try:+ export_knowledge_graph(kg, file_path, format=format_name)+ print(f"✓ Exported to {format_name}: {file_path}")+ except Exception as e:+ print(f"✗ Failed to export {format_name}: {e}")+```++## Best Practices++1. **Format Selection**: Choose the appropriate format for your use case+ - JSON/JSON-LD: Web applications, APIs+ - RDF/Turtle: Semantic web, linked data+ - CSV: Tabular analysis, spreadsheets+ - GraphML/GEXF: Graph visualization tools+ - Cypher/LPG: Graph databases (Neo4j, Memgraph)+ - YAML: Human-readable, pipeline integration+ - OWL: Ontology modeling++2. **Batch Processing**: Use batch export for large knowledge graphs+ ```python+ exporter = LPGExporter(batch_size=5000)+ exporter.export_knowledge_graph(large_kg, "output.cypher")+ ```++3. **Metadata Preservation**: Include metadata for provenance tracking+ ```python+ export_config.set("include_metadata", True)+ ```++4. **Validation**: Enable validation for RDF/OWL exports+ ```python+ export_config.set("validate", True)+ ```++5. **Error Handling**: Always handle export errors gracefully+ ```python+ try:+ export_knowledge_graph(kg, "output.json")+ except Exception as e:+ logger.error(f"Export failed: {e}")+ ```++6. **Format Auto-Detection**: Use file extensions for automatic format detection+ ```python+ export_knowledge_graph(kg, "output.ttl") # Auto-detects Turtle format+ ```++7. **Configuration Management**: Use environment variables or config files for consistent settings+ ```python+ export_config.set("default_format", "json")+ ```++## Performance Tips++1. **Batch Size**: Adjust batch size based on graph size and memory+ ```python+ exporter = LPGExporter(batch_size=10000) # For very large graphs+ ```++2. **Parallel Export**: Export to multiple formats in parallel+ ```python+ from concurrent.futures import ThreadPoolExecutor++ with ThreadPoolExecutor() as executor:+ executor.submit(export_json, kg, "output.json")+ executor.submit(export_rdf, kg, "output.ttl", format="turtle")+ executor.submit(export_lpg, kg, "output.cypher")+ ```++3. **Streaming Export**: For very large graphs, consider streaming export+ ```python+ # Use batch processing for large exports+ exporter = CSVExporter()+ exporter.export_knowledge_graph(large_kg, "output_base")+ ```++4. **Caching**: Cache exported files when possible+ ```python+ # Check if export already exists+ if not Path("output.json").exists():+ export_knowledge_graph(kg, "output.json")+ ```++5. **Compression**: Compress large exports+ ```python+ import gzip+ export_knowledge_graph(kg, "output.json")+ # Then compress+ with open("output.json", "rb") as f_in:+ with gzip.open("output.json.gz", "wb") as f_out:+ f_out.writelines(f_in)+ ```+diff --git a/semantica/export/lpg_exporter.py b/semantica/export/lpg_exporter.pynew file mode 100644index 00000000..bd821d49--- /dev/null+++ b/semantica/export/lpg_exporter.py@@ -0,0 +1,329 @@+"""+LPG (Labeled Property Graph) Export Module++This module provides comprehensive LPG export capabilities for the Semantica framework,+enabling export to graph databases like Neo4j, Memgraph, and similar systems.++Key Features:+ - LPG format export for Neo4j, Memgraph, and similar databases+ - Cypher query generation for graph database import+ - Node label assignment from entity types+ - Relationship type mapping+ - Property serialization+ - Batch export processing+ - Index and constraint generation++Example Usage:+ >>> from semantica.export import LPGExporter+ >>> exporter = LPGExporter()+ >>> exporter.export_knowledge_graph(kg, "output.cypher")+ >>> exporter.export_to_neo4j(kg, uri="bolt://localhost:7687", username="neo4j", password="password")+"""++from typing import Any, Dict, List, Optional, Union+from pathlib import Path++from ..utils.exceptions import ValidationError, ProcessingError+from ..utils.logging import get_logger+from ..utils.helpers import ensure_directory+from ..utils.progress_tracker import get_progress_tracker+++class LPGExporter:+ """+ LPG exporter for knowledge graphs and graph databases.++ This class provides comprehensive LPG export functionality for knowledge graphs,+ supporting export to Neo4j, Memgraph, and similar graph databases via Cypher queries.++ Features:+ - Cypher query generation for graph database import+ - Node label assignment from entity types+ - Relationship type mapping+ - Property serialization+ - Batch export processing+ - Index and constraint generation++ Example Usage:+ >>> exporter = LPGExporter()+ >>> exporter.export_knowledge_graph(kg, "output.cypher")+ """++ def __init__(+ self,+ batch_size: int = 1000,+ include_indexes: bool = True,+ config: Optional[Dict[str, Any]] = None,+ **kwargs+ ):+ """+ Initialize LPG exporter.++ Sets up the exporter with batch size and index generation options.++ Args:+ batch_size: Batch size for Cypher queries (default: 1000)+ include_indexes: Whether to generate indexes and constraints (default: True)+ config: Optional configuration dictionary (merged with kwargs)+ **kwargs: Additional configuration options+ """+ self.logger = get_logger("lpg_exporter")+ self.config = config or {}+ self.config.update(kwargs)++ # LPG export configuration+ self.batch_size = batch_size+ self.include_indexes = include_indexes++ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()++ self.logger.debug(+ f"LPG exporter initialized: batch_size={batch_size}, "+ f"include_indexes={include_indexes}"+ )++ def export(+ self,+ knowledge_graph: Dict[str, Any],+ file_path: Union[str, Path],+ **options+ ) -> None:+ """+ Export knowledge graph to LPG format (Cypher queries).++ This method exports a knowledge graph to Cypher CREATE statements that can+ be imported into Neo4j, Memgraph, or similar graph databases.++ Args:+ 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)+ file_path: Output Cypher file path+ **options: Additional export options++ Example:+ >>> kg = {+ ... "entities": [...],+ ... "relationships": [...]+ ... }+ >>> exporter.export(kg, "graph.cypher")+ """+ file_path = Path(file_path)+ ensure_directory(file_path.parent)++ tracking_id = self.progress_tracker.start_tracking(+ file=str(file_path),+ module="export",+ submodule="LPGExporter",+ message=f"Exporting knowledge graph to LPG format: {file_path}"+ )++ try:+ # Generate Cypher queries+ cypher_queries = self._generate_cypher_queries(knowledge_graph, **options)++ # Write to file+ with open(file_path, 'w', encoding='utf-8') as f:+ f.write('\n'.join(cypher_queries))++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Exported {len(cypher_queries)} Cypher queries")+ self.logger.info(f"Exported knowledge graph to LPG format: {file_path}")++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raise++ def _generate_cypher_queries(+ self,+ knowledge_graph: Dict[str, Any],+ **options+ ) -> List[str]:+ """+ Generate Cypher CREATE queries from knowledge graph.++ Args:+ knowledge_graph: Knowledge graph dictionary+ **options: Additional options++ Returns:+ List of Cypher query strings+ """+ queries = []++ # Generate indexes if requested+ if self.include_indexes:+ queries.extend(self._generate_indexes(knowledge_graph))++ # Extract entities and relationships+ entities = knowledge_graph.get("entities", [])+ relationships = knowledge_graph.get("relationships", [])+ nodes = knowledge_graph.get("nodes", entities)+ edges = knowledge_graph.get("edges", relationships)++ # Generate node creation queries+ node_queries = self._generate_node_queries(nodes)+ queries.extend(node_queries)++ # Generate relationship creation queries+ rel_queries = self._generate_relationship_queries(edges)+ queries.extend(rel_queries)++ return queries++ def _generate_indexes(self, knowledge_graph: Dict[str, Any]) -> List[str]:+ """Generate Cypher index and constraint creation queries."""+ indexes = []++ # Get unique entity types for labels+ entity_types = set()+ for entity in knowledge_graph.get("entities", []):+ entity_type = entity.get("type") or entity.get("entity_type")+ if entity_type:+ entity_types.add(entity_type)++ # Create indexes on common properties+ for entity_type in entity_types:+ # Index on id property+ indexes.append(+ f"CREATE INDEX IF NOT EXISTS FOR (n:{entity_type}) ON (n.id);"+ )+ # Index on name property if exists+ indexes.append(+ f"CREATE INDEX IF NOT EXISTS FOR (n:{entity_type}) ON (n.name);"+ )++ return indexes++ def _generate_node_queries(self, nodes: List[Dict[str, Any]]) -> List[str]:+ """Generate Cypher node creation queries."""+ queries = []++ # Process nodes in batches+ for i in range(0, len(nodes), self.batch_size):+ batch = nodes[i:i + self.batch_size]+ batch_query = self._create_nodes_batch(batch)+ queries.append(batch_query)++ return queries++ def _create_nodes_batch(self, nodes: List[Dict[str, Any]]) -> str:+ """Create a batch of nodes in a single Cypher query."""+ if not nodes:+ return ""++ lines = []+ for idx, node in enumerate(nodes):+ node_id = node.get("id") or node.get("entity_id", f"node_{idx}")+ node_type = node.get("type") or node.get("entity_type", "Entity")+ label = node.get("label") or node.get("name") or node.get("text", "")++ # Escape special characters+ node_id_escaped = self._escape_cypher_string(str(node_id))+ label_escaped = self._escape_cypher_string(str(label))++ # Build properties+ properties = {"id": node_id_escaped, "name": label_escaped}++ # Add other properties+ for key, value in node.items():+ if key not in ["id", "entity_id", "type", "entity_type", "label", "name", "text"]:+ if isinstance(value, (str, int, float, bool)):+ properties[key] = self._format_cypher_value(value)++ # Format properties+ props_str = ", ".join([f"{k}: {v}" for k, v in properties.items()])++ # Create node+ lines.append(f"CREATE (n{idx}:{node_type} {{{props_str}}});")++ return "\n".join(lines)++ def _generate_relationship_queries(self, edges: List[Dict[str, Any]]) -> List[str]:+ """Generate Cypher relationship creation queries."""+ queries = []++ # Process edges in batches+ for i in range(0, len(edges), self.batch_size):+ batch = edges[i:i + self.batch_size]+ batch_query = self._create_relationships_batch(batch)+ queries.append(batch_query)++ return queries++ def _create_relationships_batch(self, edges: List[Dict[str, Any]]) -> str:+ """Create a batch of relationships in a single Cypher query."""+ if not edges:+ return ""++ lines = []+ for idx, edge in enumerate(edges):+ source_id = edge.get("source") or edge.get("source_id")+ target_id = edge.get("target") or edge.get("target_id")+ rel_type = edge.get("type") or edge.get("relationship_type", "RELATED_TO")++ if not source_id or not target_id:+ continue++ # Escape special characters+ source_escaped = self._escape_cypher_string(str(source_id))+ target_escaped = self._escape_cypher_string(str(target_id))+ rel_type_escaped = rel_type.upper().replace(" ", "_")++ # Build properties+ properties = {}+ for key, value in edge.items():+ if key not in ["source", "source_id", "target", "target_id", "type", "relationship_type"]:+ if isinstance(value, (str, int, float, bool)):+ properties[key] = self._format_cypher_value(value)++ # Format properties+ if properties:+ props_str = ", ".join([f"{k}: {v}" for k, v in properties.items()])+ props_str = f" {{{props_str}}}"+ else:+ props_str = ""++ # Create relationship+ lines.append(+ f"MATCH (a {{id: '{source_escaped}'}}), (b {{id: '{target_escaped}'}}) "+ f"CREATE (a)-[r:{rel_type_escaped}{props_str}]->(b);"+ )++ return "\n".join(lines)++ def _escape_cypher_string(self, value: str) -> str:+ """Escape special characters in Cypher strings."""+ return value.replace("'", "\\'").replace("\\", "\\\\")++ def _format_cypher_value(self, value: Any) -> str:+ """Format a value for Cypher query."""+ if isinstance(value, str):+ escaped = self._escape_cypher_string(value)+ return f"'{escaped}'"+ elif isinstance(value, bool):+ return str(value).lower()+ else:+ return str(value)++ def export_knowledge_graph(+ self,+ knowledge_graph: Dict[str, Any],+ file_path: Union[str, Path],+ **options+ ) -> None:+ """+ Export knowledge graph to LPG format.++ Convenience method that calls export().++ Args:+ knowledge_graph: Knowledge graph dictionary+ file_path: Output file path+ **options: Additional export options+ """+ self.export(knowledge_graph, file_path, **options)+diff --git a/semantica/export/methods.py b/semantica/export/methods.pynew file mode 100644index 00000000..3b111c22--- /dev/null+++ b/semantica/export/methods.py@@ -0,0 +1,752 @@+"""+Export Methods Module++This module provides all export methods as simple, reusable functions for+exporting knowledge graphs, entities, relationships, and data to various formats.+It supports multiple export approaches and integrates with the method registry+for extensibility.++Supported Methods:++RDF Export:+ - "turtle": Turtle format export+ - "rdfxml": RDF/XML format export+ - "jsonld": JSON-LD format export+ - "ntriples": N-Triples format export+ - "n3": N3 format export++JSON Export:+ - "json": Standard JSON format export+ - "json-ld": JSON-LD format export++CSV Export:+ - "csv": CSV format export with configurable delimiter++Graph Export:+ - "graphml": GraphML format export+ - "gexf": GEXF format export+ - "dot": DOT format export+ - "json": JSON graph format export++YAML Export:+ - "yaml": YAML format export+ - "semantic_network": Semantic network YAML export+ - "schema": Schema YAML export++OWL Export:+ - "owl-xml": OWL/XML format export+ - "turtle": OWL in Turtle format++Vector Export:+ - "json": JSON vector format+ - "numpy": NumPy format+ - "binary": Binary format+ - "faiss": FAISS format++LPG Export:+ - "cypher": Cypher query format for Neo4j/Memgraph+ - "lpg": Labeled Property Graph format++Report Generation:+ - "html": HTML report format+ - "markdown": Markdown report format+ - "json": JSON report format+ - "text": Plain text report format++Algorithms Used:++RDF Export:+ - RDF Serialization: Multiple format serialization (Turtle, RDF/XML, JSON-LD, N-Triples, N3)+ - Namespace Management: Namespace registration, conflict resolution, declaration generation+ - RDF Validation: RDF syntax validation, triple validation, namespace validation+ - URI Generation: Hash-based and text-based URI assignment for RDF resources+ - Triple Extraction: Entity and relationship to RDF triple conversion+ - Format Conversion: Cross-format RDF conversion algorithms++LPG (Labeled Property Graph) Export:+ - LPG Serialization: Labeled Property Graph format for Neo4j, Memgraph, and similar databases+ - Node Label Assignment: Entity type to node label mapping+ - Relationship Type Mapping: Relationship type to edge label conversion+ - Property Serialization: Entity and relationship properties to LPG property format+ - Cypher Query Generation: Cypher CREATE statements for graph database import+ - Batch Node/Relationship Export: Efficient batch processing for large graphs+ - Index Generation: Index and constraint generation for graph databases++JSON/JSON-LD Export:+ - JSON Serialization: Standard JSON serialization with configurable indentation+ - JSON-LD Context Management: @context generation and management+ - Knowledge Graph Serialization: Graph structure to JSON/JSON-LD conversion+ - Metadata Embedding: Provenance and metadata serialization in JSON structure+ - Pretty Printing: Formatted JSON output with indentation++CSV Export:+ - Tabular Serialization: Entity and relationship to CSV row conversion+ - Field Extraction: Dynamic field name extraction from data structures+ - Delimiter Handling: Configurable delimiter support (comma, tab, semicolon)+ - Header Generation: Automatic CSV header row generation+ - Metadata Serialization: JSON string serialization for complex metadata fields+ - Multi-file Export: Knowledge graph split into multiple CSV files (entities, relationships)++Graph Export:+ - GraphML Serialization: GraphML format generation for graph visualization tools+ - GEXF Serialization: GEXF format generation for Gephi and similar tools+ - DOT Serialization: Graphviz DOT format generation+ - Node/Edge Attribute Mapping: Property to graph attribute conversion+ - Graph Structure Conversion: Knowledge graph to graph format transformation++YAML Export:+ - YAML Serialization: Human-readable YAML format generation+ - Semantic Network Export: Entity-relationship network to YAML conversion+ - Schema Export: Ontology schema to YAML for human editing+ - Pipeline Integration: Stage-specific YAML export for ontology generation pipeline++OWL Export:+ - OWL-XML Serialization: OWL/XML format generation+ - Turtle Serialization: OWL in Turtle format+ - Class Hierarchy Export: Class definition and hierarchy serialization+ - Property Export: Object and data property definition export+ - OWL 2.0 Feature Support: Advanced OWL features (cardinality, restrictions, etc.)+ - Ontology Validation: OWL syntax and semantic validation++Vector Export:+ - Vector Serialization: Multiple format support (JSON, NumPy, Binary, FAISS)+ - Vector Store Integration: Format conversion for Pinecone, Weaviate, Qdrant, FAISS+ - Metadata Association: Vector-to-metadata mapping and serialization+ - Batch Export: Efficient batch vector export processing+ - Multi-dimensional Support: Variable dimension vector handling++Report Generation:+ - Template Rendering: Template-based report generation (HTML, Markdown, JSON, Text)+ - Quality Metrics Aggregation: Statistical aggregation of quality metrics+ - Chart Generation: Visualization and chart generation (if enabled)+ - Format Conversion: Cross-format report conversion+ - Section Organization: Hierarchical report section organization++Key Features:+ - Multiple export format methods+ - Knowledge graph export with format dispatch+ - Method dispatchers with registry support+ - Custom method registration capability+ - Consistent interface across all methods++Main Functions:+ - export_rdf: RDF export wrapper+ - export_json: JSON/JSON-LD export wrapper+ - export_csv: CSV export wrapper+ - export_graph: Graph format export wrapper+ - export_yaml: YAML export wrapper+ - export_owl: OWL export wrapper+ - export_vector: Vector export wrapper+ - export_lpg: LPG export wrapper+ - generate_report: Report generation wrapper+ - export_knowledge_graph: Unified knowledge graph export with format dispatch+ - get_export_method: Get export method by name+ - list_available_methods: List registered methods++Example Usage:+ >>> from semantica.export.methods import export_knowledge_graph, export_rdf, export_lpg+ >>> kg = {"entities": [...], "relationships": [...]}+ >>> export_knowledge_graph(kg, "output.json", format="json")+ >>> export_rdf(kg, "output.ttl", format="turtle")+ >>> export_lpg(kg, "output.cypher", method="cypher")+"""++from typing import Any, Dict, List, Optional, Callable, Union+from pathlib import Path++from ..utils.logging import get_logger+from ..utils.exceptions import ProcessingError, ConfigurationError+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 .owl_exporter import OWLExporter+from .vector_exporter import VectorExporter+from .lpg_exporter import LPGExporter+from .report_generator import ReportGenerator+from .registry import method_registry+from .config import export_config++logger = get_logger("export_methods")+++def export_rdf(+ data: Union[Dict[str, Any], List[Dict[str, Any]]],+ file_path: Union[str, Path],+ format: str = "turtle",+ method: str = "default",+ **kwargs+) -> None:+ """+ Export data to RDF format (convenience function).++ This is a user-friendly wrapper that exports data to RDF using the specified format.++ Args:+ data: Data to export (knowledge graph, entities, relationships, or triples)+ file_path: Output RDF file path+ format: RDF format (default: "turtle")+ - "turtle": Turtle format+ - "rdfxml": RDF/XML format+ - "jsonld": JSON-LD format+ - "ntriples": N-Triples format+ - "n3": N3 format+ method: Export method (default: "default")+ **kwargs: Additional options passed to RDFExporter++ Examples:+ >>> from semantica.export.methods import export_rdf+ >>> export_rdf(kg, "output.ttl", format="turtle")+ >>> export_rdf(entities, "output.rdf", format="rdfxml")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("rdf", method)+ if custom_method:+ try:+ return custom_method(data, file_path, format=format, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = export_config.get_method_config("rdf")+ config.update(kwargs)++ exporter = RDFExporter(**config)+ exporter.export(data, file_path, format=format, **kwargs)++ except Exception as e:+ logger.error(f"Failed to export RDF: {e}")+ raise+++def export_json(+ data: Union[Dict[str, Any], List[Dict[str, Any]]],+ file_path: Union[str, Path],+ format: str = "json",+ method: str = "default",+ **kwargs+) -> None:+ """+ Export data to JSON/JSON-LD format (convenience function).++ This is a user-friendly wrapper that exports data to JSON or JSON-LD format.++ Args:+ data: Data to export (knowledge graph, entities, relationships)+ file_path: Output JSON file path+ format: Export format (default: "json")+ - "json": Standard JSON format+ - "json-ld": JSON-LD format+ method: Export method (default: "default")+ **kwargs: Additional options passed to JSONExporter++ Examples:+ >>> from semantica.export.methods import export_json+ >>> export_json(kg, "output.json", format="json")+ >>> export_json(kg, "output.jsonld", format="json-ld")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("json", method)+ if custom_method:+ try:+ return custom_method(data, file_path, format=format, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = export_config.get_method_config("json")+ config.update(kwargs)+ config["format"] = format++ exporter = JSONExporter(**config)+ exporter.export(data, file_path, format=format, **kwargs)++ except Exception as e:+ logger.error(f"Failed to export JSON: {e}")+ raise+++def export_csv(+ data: Union[List[Dict[str, Any]], Dict[str, List[Dict[str, Any]]]],+ file_path: Union[str, Path],+ method: str = "default",+ **kwargs+) -> None:+ """+ Export data to CSV format (convenience function).++ This is a user-friendly wrapper that exports data to CSV format.++ Args:+ data: Data to export (list of dicts or dict with list values)+ file_path: Output CSV file path (or base path for multiple files)+ method: Export method (default: "default")+ **kwargs: Additional options passed to CSVExporter++ Examples:+ >>> from semantica.export.methods import export_csv+ >>> export_csv(entities, "entities.csv")+ >>> export_csv({"entities": [...], "relationships": [...]}, "output_base")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("csv", method)+ if custom_method:+ try:+ return custom_method(data, file_path, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = export_config.get_method_config("csv")+ config.update(kwargs)++ exporter = CSVExporter(**config)+ exporter.export(data, file_path, **kwargs)++ except Exception as e:+ logger.error(f"Failed to export CSV: {e}")+ raise+++def export_graph(+ graph_data: Dict[str, Any],+ file_path: Union[str, Path],+ format: str = "json",+ method: str = "default",+ **kwargs+) -> None:+ """+ Export graph data to graph format (convenience function).++ This is a user-friendly wrapper that exports graph data to various graph formats.++ Args:+ graph_data: Graph data dictionary with nodes and edges+ file_path: Output graph file path+ format: Graph format (default: "json")+ - "graphml": GraphML format+ - "gexf": GEXF format+ - "dot": DOT format+ - "json": JSON graph format+ method: Export method (default: "default")+ **kwargs: Additional options passed to GraphExporter++ Examples:+ >>> from semantica.export.methods import export_graph+ >>> export_graph(graph_data, "graph.graphml", format="graphml")+ >>> export_graph(graph_data, "graph.gexf", format="gexf")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("graph", method)+ if custom_method:+ try:+ return custom_method(graph_data, file_path, format=format, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = export_config.get_method_config("graph")+ config.update(kwargs)+ config["format"] = format++ exporter = GraphExporter(**config)+ exporter.export(graph_data, file_path, format=format, **kwargs)++ except Exception as e:+ logger.error(f"Failed to export graph: {e}")+ raise+++def export_yaml(+ data: Union[Dict[str, Any], List[Dict[str, Any]]],+ file_path: Union[str, Path],+ method: str = "semantic_network",+ **kwargs+) -> None:+ """+ Export data to YAML format (convenience function).++ This is a user-friendly wrapper that exports data to YAML format.++ Args:+ data: Data to export (semantic network, entities, relationships)+ file_path: Output YAML file path+ method: Export method (default: "semantic_network")+ - "semantic_network": Semantic network YAML export+ - "schema": Schema YAML export+ **kwargs: Additional options passed to YAML exporters++ Examples:+ >>> from semantica.export.methods import export_yaml+ >>> export_yaml(semantic_network, "network.yaml", method="semantic_network")+ >>> export_yaml(schema, "schema.yaml", method="schema")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("yaml", method)+ if custom_method:+ try:+ return custom_method(data, file_path, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = export_config.get_method_config("yaml")+ config.update(kwargs)++ if method == "semantic_network":+ exporter = SemanticNetworkYAMLExporter(**config)+ exporter.export(data, file_path, **kwargs)+ elif method == "schema":+ exporter = YAMLSchemaExporter(**config)+ exporter.export(data, file_path, **kwargs)+ else:+ raise ProcessingError(f"Unknown YAML export method: {method}")++ except Exception as e:+ logger.error(f"Failed to export YAML: {e}")+ raise+++def export_owl(+ ontology: Dict[str, Any],+ file_path: Union[str, Path],+ format: str = "owl-xml",+ method: str = "default",+ **kwargs+) -> None:+ """+ Export ontology to OWL format (convenience function).++ This is a user-friendly wrapper that exports ontologies to OWL format.++ Args:+ ontology: Ontology data dictionary+ file_path: Output OWL file path+ format: OWL format (default: "owl-xml")+ - "owl-xml": OWL/XML format+ - "turtle": OWL in Turtle format+ method: Export method (default: "default")+ **kwargs: Additional options passed to OWLExporter++ Examples:+ >>> from semantica.export.methods import export_owl+ >>> export_owl(ontology, "ontology.owl", format="owl-xml")+ >>> export_owl(ontology, "ontology.ttl", format="turtle")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("owl", method)+ if custom_method:+ try:+ return custom_method(ontology, file_path, format=format, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = export_config.get_method_config("owl")+ config.update(kwargs)+ config["format"] = format++ exporter = OWLExporter(**config)+ exporter.export(ontology, file_path, format=format, **kwargs)++ except Exception as e:+ logger.error(f"Failed to export OWL: {e}")+ raise+++def export_vector(+ vectors: Union[List, Dict[str, Any]],+ file_path: Union[str, Path],+ format: str = "json",+ method: str = "default",+ **kwargs+) -> None:+ """+ Export vectors to vector format (convenience function).++ This is a user-friendly wrapper that exports vectors to various vector formats.++ Args:+ vectors: Vector data (list of vectors or dict with vector data)+ file_path: Output vector file path+ format: Vector format (default: "json")+ - "json": JSON vector format+ - "numpy": NumPy format+ - "binary": Binary format+ - "faiss": FAISS format+ method: Export method (default: "default")+ **kwargs: Additional options passed to VectorExporter++ Examples:+ >>> from semantica.export.methods import export_vector+ >>> export_vector(vectors, "vectors.json", format="json")+ >>> export_vector(vectors, "vectors.npy", format="numpy")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("vector", method)+ if custom_method:+ try:+ return custom_method(vectors, file_path, format=format, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = export_config.get_method_config("vector")+ config.update(kwargs)+ config["format"] = format++ exporter = VectorExporter(**config)+ exporter.export(vectors, file_path, format=format, **kwargs)++ except Exception as e:+ logger.error(f"Failed to export vector: {e}")+ raise+++def export_lpg(+ knowledge_graph: Dict[str, Any],+ file_path: Union[str, Path],+ method: str = "cypher",+ **kwargs+) -> None:+ """+ Export knowledge graph to LPG format (convenience function).++ This is a user-friendly wrapper that exports knowledge graphs to LPG format+ (Cypher queries for Neo4j, Memgraph, etc.).++ Args:+ knowledge_graph: Knowledge graph dictionary with entities and relationships+ file_path: Output Cypher file path+ method: Export method (default: "cypher")+ - "cypher": Cypher query format+ - "lpg": Labeled Property Graph format+ **kwargs: Additional options passed to LPGExporter++ Examples:+ >>> from semantica.export.methods import export_lpg+ >>> export_lpg(kg, "graph.cypher", method="cypher")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("lpg", method)+ if custom_method:+ try:+ return custom_method(knowledge_graph, file_path, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = export_config.get_method_config("lpg")+ config.update(kwargs)++ exporter = LPGExporter(**config)+ exporter.export_knowledge_graph(knowledge_graph, file_path, **kwargs)++ except Exception as e:+ logger.error(f"Failed to export LPG: {e}")+ raise+++def generate_report(+ data: Dict[str, Any],+ file_path: Union[str, Path],+ format: str = "markdown",+ method: str = "default",+ **kwargs+) -> None:+ """+ Generate report (convenience function).++ This is a user-friendly wrapper that generates reports in various formats.++ Args:+ data: Report data dictionary+ file_path: Output report file path+ format: Report format (default: "markdown")+ - "html": HTML report format+ - "markdown": Markdown report format+ - "json": JSON report format+ - "text": Plain text report format+ method: Report generation method (default: "default")+ **kwargs: Additional options passed to ReportGenerator++ Examples:+ >>> from semantica.export.methods import generate_report+ >>> generate_report(metrics, "report.html", format="html")+ >>> generate_report(analysis, "report.md", format="markdown")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("report", method)+ if custom_method:+ try:+ return custom_method(data, file_path, format=format, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = export_config.get_method_config("report")+ config.update(kwargs)+ config["format"] = format++ generator = ReportGenerator(**config)+ generator.generate_report(data, file_path, format=format, **kwargs)++ except Exception as e:+ logger.error(f"Failed to generate report: {e}")+ raise+++def export_knowledge_graph(+ knowledge_graph: Dict[str, Any],+ file_path: Union[str, Path],+ format: str = "json",+ method: Optional[str] = None,+ **kwargs+) -> None:+ """+ Export knowledge graph to specified format (unified convenience function).++ This is a user-friendly wrapper that automatically routes to the appropriate+ exporter based on the file extension or format parameter.++ Args:+ knowledge_graph: Knowledge graph dictionary with entities and relationships+ file_path: Output file path (format auto-detected from extension if format not specified)+ format: Export format (auto-detected from file extension if not specified)+ - "json", "json-ld": JSONExporter+ - "csv": CSVExporter+ - "ttl", "turtle": RDFExporter (turtle)+ - "rdf", "rdfxml": RDFExporter (rdfxml)+ - "graphml": GraphExporter (graphml)+ - "gexf": GraphExporter (gexf)+ - "dot": GraphExporter (dot)+ - "yaml", "yml": YAML exporters+ - "owl": OWLExporter+ - "cypher": LPGExporter+ method: Optional specific export method+ **kwargs: Additional options passed to exporter++ Examples:+ >>> from semantica.export.methods import export_knowledge_graph+ >>> export_knowledge_graph(kg, "output.json", format="json")+ >>> export_knowledge_graph(kg, "output.ttl", format="turtle")+ >>> export_knowledge_graph(kg, "output.cypher", format="cypher")+ """+ # Auto-detect format from file extension if not specified+ if not format:+ file_path_obj = Path(file_path)+ ext = file_path_obj.suffix.lower()+ format_map = {+ ".json": "json",+ ".jsonld": "json-ld",+ ".csv": "csv",+ ".ttl": "turtle",+ ".rdf": "rdfxml",+ ".graphml": "graphml",+ ".gexf": "gexf",+ ".dot": "dot",+ ".yaml": "yaml",+ ".yml": "yaml",+ ".owl": "owl-xml",+ ".cypher": "cypher",+ }+ format = format_map.get(ext, "json")++ # Route to appropriate exporter+ if format in ["json", "json-ld"]:+ export_json(knowledge_graph, file_path, format=format, method=method, **kwargs)+ elif format == "csv":+ export_csv(knowledge_graph, file_path, method=method, **kwargs)+ elif format in ["turtle", "rdfxml", "jsonld", "ntriples", "n3"]:+ export_rdf(knowledge_graph, file_path, format=format, method=method, **kwargs)+ elif format in ["graphml", "gexf", "dot"]:+ export_graph(knowledge_graph, file_path, format=format, method=method, **kwargs)+ elif format in ["yaml", "yml"]:+ export_yaml(knowledge_graph, file_path, method=method, **kwargs)+ elif format in ["owl-xml", "owl"]:+ export_owl(knowledge_graph, file_path, format=format, method=method, **kwargs)+ elif format == "cypher":+ export_lpg(knowledge_graph, file_path, method=method, **kwargs)+ else:+ raise ProcessingError(f"Unknown export format: {format}")+++def get_export_method(task: str, name: str) -> Optional[Callable]:+ """+ Get a registered export method.++ Args:+ task: Task type ("rdf", "json", "csv", "graph", "yaml", "owl", "vector", "lpg", "report", "export")+ name: Method name++ Returns:+ Registered method or None if not found++ Examples:+ >>> from semantica.export.methods import get_export_method+ >>> method = get_export_method("json", "custom_method")+ >>> if method:+ ... result = method(data, "output.json")+ """+ return method_registry.get(task, name)+++def list_available_methods(task: Optional[str] = None) -> Dict[str, List[str]]:+ """+ List all available export methods.++ Args:+ task: Optional task type filter++ Returns:+ Dictionary mapping task types to method names++ Examples:+ >>> from semantica.export.methods import list_available_methods+ >>> all_methods = list_available_methods()+ >>> json_methods = list_available_methods("json")+ """+ return method_registry.list_all(task)+++# Register default methods+method_registry.register("rdf", "default", export_rdf)+method_registry.register("rdf", "turtle", export_rdf)+method_registry.register("rdf", "rdfxml", export_rdf)+method_registry.register("rdf", "jsonld", export_rdf)+method_registry.register("json", "default", export_json)+method_registry.register("json", "json", export_json)+method_registry.register("json", "json-ld", export_json)+method_registry.register("csv", "default", export_csv)+method_registry.register("csv", "csv", export_csv)+method_registry.register("graph", "default", export_graph)+method_registry.register("graph", "graphml", export_graph)+method_registry.register("graph", "gexf", export_graph)+method_registry.register("graph", "dot", export_graph)+method_registry.register("yaml", "default", export_yaml)+method_registry.register("yaml", "semantic_network", export_yaml)+method_registry.register("yaml", "schema", export_yaml)+method_registry.register("owl", "default", export_owl)+method_registry.register("owl", "owl-xml", export_owl)+method_registry.register("owl", "turtle", export_owl)+method_registry.register("vector", "default", export_vector)+method_registry.register("vector", "json", export_vector)+method_registry.register("vector", "numpy", export_vector)+method_registry.register("lpg", "default", export_lpg)+method_registry.register("lpg", "cypher", export_lpg)+method_registry.register("report", "default", generate_report)+method_registry.register("report", "html", generate_report)+method_registry.register("report", "markdown", generate_report)+method_registry.register("export", "default", export_knowledge_graph)+method_registry.register("export", "knowledge_graph", export_knowledge_graph)+diff --git a/semantica/export/registry.py b/semantica/export/registry.pynew file mode 100644index 00000000..c094b620--- /dev/null+++ b/semantica/export/registry.py@@ -0,0 +1,138 @@+"""+Method Registry Module for Export++This module provides a method registry system for registering custom export methods,+enabling extensibility and community contributions to the export toolkit.++Supported Registration Types:+ - Method Registry: Register custom export methods for:+ * "rdf": RDF export methods+ * "json": JSON/JSON-LD export methods+ * "csv": CSV export methods+ * "graph": Graph format export methods+ * "yaml": YAML export methods+ * "owl": OWL export methods+ * "vector": Vector export methods+ * "lpg": LPG (Labeled Property Graph) export methods+ * "report": Report generation methods+ * "export": General export methods++Algorithms Used:+ - Registry Pattern: Dictionary-based registration and lookup+ - Dynamic Registration: Runtime function registration+ - Type Checking: Type validation for registered components+ - Lookup Algorithms: Hash-based O(1) lookup for methods+ - Task-based Organization: Hierarchical organization by task type++Key Features:+ - Method registry for custom export methods+ - Task-based method organization (rdf, json, csv, graph, yaml, owl, vector, lpg, report, export)+ - Dynamic registration and unregistration+ - Easy discovery of available methods+ - Support for community-contributed extensions++Main Classes:+ - MethodRegistry: Registry for custom export methods++Global Instances:+ - method_registry: Global method registry instance++Example Usage:+ >>> from semantica.export.registry import method_registry+ >>> method_registry.register("json", "custom_method", custom_json_export_function)+ >>> available = method_registry.list_all("json")+"""++from typing import Dict, Callable, Any, List, Optional+++class MethodRegistry:+ """Registry for custom export methods."""++ _methods: Dict[str, Dict[str, Callable]] = {+ "rdf": {},+ "json": {},+ "csv": {},+ "graph": {},+ "yaml": {},+ "owl": {},+ "vector": {},+ "lpg": {},+ "report": {},+ "export": {},+ }++ @classmethod+ def register(cls, task: str, name: str, method_func: Callable):+ """+ Register a custom export method.++ Args:+ task: Task type ("rdf", "json", "csv", "graph", "yaml", "owl", "vector", "lpg", "report", "export")+ name: Method name+ method_func: Method function+ """+ if task not in cls._methods:+ cls._methods[task] = {}+ cls._methods[task][name] = method_func++ @classmethod+ def get(cls, task: str, name: str) -> Optional[Callable]:+ """+ Get method by task and name.++ Args:+ task: Task type ("rdf", "json", "csv", "graph", "yaml", "owl", "vector", "lpg", "report", "export")+ name: Method name++ Returns:+ Method function or None+ """+ return cls._methods.get(task, {}).get(name)++ @classmethod+ def list_all(cls, task: Optional[str] = None) -> Dict[str, List[str]]:+ """+ List all registered methods.++ Args:+ task: Optional task type to filter by++ Returns:+ Dictionary mapping task types to method names+ """+ if task:+ return {task: list(cls._methods.get(task, {}).keys())}+ return {t: list(m.keys()) for t, m in cls._methods.items()}++ @classmethod+ def unregister(cls, task: str, name: str):+ """+ Unregister a method.++ Args:+ task: Task type ("rdf", "json", "csv", "graph", "yaml", "owl", "vector", "lpg", "report", "export")+ name: Method name+ """+ if task in cls._methods and name in cls._methods[task]:+ del cls._methods[task][name]++ @classmethod+ def clear(cls, task: Optional[str] = None):+ """+ Clear all registered methods for a task or all tasks.++ Args:+ task: Optional task type to clear (clears all if None)+ """+ if task:+ if task in cls._methods:+ cls._methods[task].clear()+ else:+ for task_dict in cls._methods.values():+ task_dict.clear()+++# Global registry+method_registry = MethodRegistry()+