Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Merge main into staging, resolve conflicts keeping local changes

KaifAhmad16ebc094f56cc
diff --cc docs/concepts.md
index 192cd8b1,6b686450..d90f3a80
--- a/docs/concepts.md
+++ b/docs/concepts.md
@@@ -56,150 -56,31 +56,178 @@@ graph L
style E fill:#fff3e0,stroke:#ef6c00,stroke-width:2px
```
++<<<<<<< HEAD
+**Practical Examples**:
+
+=== "Basic Usage"
+ Build a knowledge graph from a document with just a few lines:
+
+ ```python
+ from semantica import Semantica
+
+ # Initialize Semantica with default settings
+ semantica = Semantica()
+
+ # Build knowledge graph from a PDF document
+ result = semantica.build_knowledge_base(
+ sources=["company_report.pdf"],
+ embeddings=True, # Generate vector embeddings
+ graph=True # Build knowledge graph
+ )
+
+ kg = result["knowledge_graph"]
+
+ print(f"Extracted {len(kg['entities'])} entities")
+ print(f"Found {len(kg['relationships'])} relationships")
+
+ for entity in kg['entities'][:5]:
+ print(f" {entity['text']} ({entity['type']})")
+ ```
+
+=== "Direct KG Module Usage"
+ Use the `kg` module directly for more control:
+
+ ```python
+ from semantica.kg import GraphBuilder
+
+ # Option 1: Using the convenience function (semantica.kg.build)
+ kg = build(
+ sources=[
+ {
+ "entities": [
+ {"id": "e1", "text": "Apple Inc.", "type": "Organization"},
+ {"id": "e2", "text": "Tim Cook", "type": "Person"},
+ {"id": "e3", "text": "Cupertino", "type": "Location"}
+ ],
+ "relationships": [
+ {"source": "e2", "target": "e1", "type": "CEO_OF"},
+ {"source": "e1", "target": "e3", "type": "LOCATED_IN"}
+ ]
+ }
+ ],
+ merge_entities=True,
+ resolve_conflicts=True
+ )
+
+ print(f"Graph built: {kg['metadata']['num_entities']} entities, "
+ f"{kg['metadata']['num_relationships']} relationships")
+
+ # Option 2: Using GraphBuilder for advanced configuration
+ builder = GraphBuilder(
+ merge_entities=True,
+ entity_resolution_strategy="fuzzy", # "exact", "fuzzy", or "semantic"
+ resolve_conflicts=True,
+ enable_temporal=True, # Enable time-aware edges
+ temporal_granularity="day"
+ )
+ kg = builder.build(sources)
+ ```
+
+=== "Multi-Source Integration"
+ Merge knowledge from multiple data sources:
+
+ ```python
+ from semantica import Semantica
+
+ semantica = Semantica()
+
+ # Build graphs from different sources
+ kg_news = semantica.build_knowledge_base(
+ sources=["news_articles/"],
+ normalize=True
+ )["knowledge_graph"]
+
+ kg_reports = semantica.build_knowledge_base(
+ sources=["financial_reports/"],
+ normalize=True
+ )["knowledge_graph"]
+
+ # Merge into a unified knowledge graph
+ from semantica.kg import GraphBuilder
+ builder = GraphBuilder(
+ merge_entities=True,
+ entity_resolution_strategy="semantic" # Use embeddings for matching
+ )
+
+ unified_kg = builder.merge([kg_news, kg_reports])
+
+ print(f"Merged graph: {len(unified_kg['entities'])} unique entities")
+ print(f"Deduplicated from {len(kg_news['entities']) + len(kg_reports['entities'])} total")
+ ```
+
+=== "Graph Analytics"
+ Analyze the structure and properties of your knowledge graph:
+
+ ```python
+ from semantica.kg import (
+ GraphAnalyzer,
+ CentralityCalculator,
+ CommunityDetector,
+ ConnectivityAnalyzer,
+ analyze_graph,
+ calculate_centrality,
+ detect_communities,
+ analyze_connectivity
+ )
+
+ # Method 1: Using convenience functions
+ analysis = analyze_graph(kg, method="default")
+ centrality_scores = calculate_centrality(kg, method="degree")
+ communities = detect_communities(kg, method="louvain")
+ connectivity = analyze_connectivity(kg, method="default")
+
+ # Method 2: Using classes for more control
+ analyzer = GraphAnalyzer()
+ centrality_calc = CentralityCalculator()
+ community_detector = CommunityDetector()
+ connectivity_analyzer = ConnectivityAnalyzer()
+
+ # Run comprehensive analysis
+ analysis = analyzer.analyze(kg)
+ print(f"Graph density: {analysis['density']:.3f}")
+ print(f"Average degree: {analysis['avg_degree']:.2f}")
+
+ # Calculate centrality measures
+ degree_centrality = centrality_calc.calculate(kg, method="degree")
+ betweenness = centrality_calc.calculate(kg, method="betweenness")
+ print(f"Top entities by degree: {list(degree_centrality.items())[:3]}")
+
+ # Detect communities
+ communities = community_detector.detect(kg, method="louvain")
+ print(f"Found {len(communities)} communities")
+
+ # Analyze connectivity
+ conn = connectivity_analyzer.analyze(kg)
+ print(f"Connected components: {conn['num_components']}")
+ print(f"Largest component: {conn['largest_component_size']} nodes")
+ ```
++=======
+ **Practical Example**:
+
+ ```python
+ from semantica import Semantica
+
+ # Initialize Semantica
+ semantica = Semantica()
+
+ # Build knowledge graph from document
+ result = semantica.build_knowledge_base(
+ sources=["company_report.pdf"],
+ embeddings=True,
+ graph=True
+ )
+
+ kg = result["knowledge_graph"]
+
+ # Access entities and relationships
+ print(f"Entities: {len(kg['entities'])}")
+ print(f"Relationships: {len(kg['relationships'])}")
+
+ # Query the graph
+ for entity in kg['entities'][:5]:
+ print(f"- {entity.get('text', 'N/A')}: {entity.get('type', 'N/A')}")
+ ```
++>>>>>>> origin/main
**Related Modules**:
@@@ -232,185 -113,42 +260,223 @@@
**Extraction Methods**:
++<<<<<<< HEAD
+=== "Quick Start"
+ Extract entities from text using the convenience function:
++=======
+ === "Rule-based"
+ Uses pattern matching (regex) to identify entities.
+
+ **Pros**: Fast, deterministic, no training data needed
+
+ **Cons**: Limited to predefined patterns, less flexible
++>>>>>>> origin/main
+
+ ```python
+ from semantica.semantic_extract import NamedEntityRecognizer
+
++<<<<<<< HEAD
+ text = """
+ Apple Inc. was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne
+ in Cupertino, California on April 1, 1976. The company is now worth
+ over $3 trillion and employs more than 160,000 people worldwide.
+ """
+
+ # Initialize the NER extractor
+ ner = NamedEntityRecognizer()
+
+ # Extract entities
+ entities = ner.extract_entities(text)
+
+ print(f"Extracted {len(entities)} entities:")
+ for entity in entities:
+ print(f" {entity['text']:20} | Type: {entity['type']:15} | "
+ f"Confidence: {entity.get('confidence', 0.0):.2f}")
+ ```
+
+=== "Named Entity Recognizer"
+ Use the `NamedEntityRecognizer` class for advanced control:
+
+ ```python
+ from semantica.semantic_extract import NamedEntityRecognizer
+
+ # Initialize with custom configuration
+ ner = NamedEntityRecognizer(
+ methods=["spacy", "rule-based"], # Use multiple methods
+ confidence_threshold=0.7,
+ merge_overlapping=True
+ )
+
+ text = "Elon Musk announced that Tesla will invest $10B in Texas."
+
+ # Extract entities with detailed output
+ entities = ner.extract_entities(text)
+
+ for entity in entities:
+ print(f"""
+ Entity: {entity['text']}
+ Type: {entity['type']}
+ Start: {entity['start_char']}, End: {entity['end_char']}
+ Confidence: {entity['confidence']:.2f}
+ Method: {entity.get('extraction_method', 'N/A')}
+ """)
+ ```
+
+=== "Custom Entity Types"
+ Define and extract custom entity types for your domain:
+
+ ```python
+ from semantica.semantic_extract import (
+ NamedEntityRecognizer,
+ CustomEntityDetector
+ )
+
+ # Define custom entity patterns for a medical domain
+ custom_detector = CustomEntityDetector(
+ patterns={
+ "Drug": [
+ r"\b(aspirin|ibuprofen|acetaminophen)\b",
+ r"\b\w+(?:mycin|cillin|phen)\b" # Common drug suffixes
+ ],
+ "Dosage": [
+ r"\d+\s*(?:mg|ml|g|mcg)\b",
+ r"\b(?:once|twice|three times)\s+(?:daily|weekly)\b"
+ ],
+ "Condition": [
+ r"\b(?:diabetes|hypertension|arthritis)\b",
+ r"\b\w+itis\b" # Inflammation conditions
+ ]
+ }
+ )
+
+ ner = NamedEntityRecognizer(
+ custom_detectors=[custom_detector],
+ include_standard_types=True # Also extract Person, Org, etc.
+ )
+
+ medical_text = """
+ Patient prescribed ibuprofen 400mg twice daily for arthritis.
+ Previous treatment with amoxicillin was discontinued.
+ """
+
+ entities = ner.extract_entities(medical_text)
+
+ # Group by type
+ from collections import defaultdict
+ by_type = defaultdict(list)
+ for e in entities:
+ by_type[e['type']].append(e['text'])
+
+ for entity_type, items in by_type.items():
+ print(f"{entity_type}: {', '.join(items)}")
+
+ # Output:
+ # Drug: ibuprofen, amoxicillin
+ # Dosage: 400mg, twice daily
+ # Condition: arthritis
+ ```
+
+=== "LLM-Enhanced Extraction"
+ Use LLMs for context-aware, high-accuracy extraction:
+
+ ```python
+ from semantica.semantic_extract import (
+ NamedEntityRecognizer,
+ LLMEnhancer,
+ create_provider
+ )
+
+ # Create LLM provider (supports OpenAI, Anthropic, Groq, Ollama)
+ provider = create_provider(
+ provider_type="openai",
+ model="gpt-4o",
+ api_key="your-api-key" # Or use OPENAI_API_KEY env var
+ )
+
+ # Initialize LLM-enhanced NER
+ enhancer = LLMEnhancer(provider=provider)
+ ner = NamedEntityRecognizer(
+ llm_enhancer=enhancer,
+ use_llm_verification=True # Verify with LLM
+ )
+
+ # Extract with LLM enhancement for ambiguous cases
+ text = """
+ Apple reported record revenue. Tim said the new Apple Watch
+ and the partnership with Goldman Sachs exceeded expectations.
+ """
+
+ entities = ner.extract_entities(
+ text,
+ context="Financial earnings report" # Provide context for better accuracy
+ )
+
+ # LLM helps distinguish:
+ # - "Apple" (company) vs "apple" (fruit)
+ # - "Tim" (person - Tim Cook) from context
+ # - "Goldman Sachs" (organization)
+ # - "Apple Watch" (product vs organization)
+ ```
+
+=== "Batch Processing"
+ Process multiple documents efficiently:
```python
from semantica.semantic_extract import NamedEntityRecognizer
+ ner = NamedEntityRecognizer(batch_size=32)
+
+ documents = [
+ "Microsoft acquired Activision for $69 billion.",
+ "Google announced Gemini AI at their Mountain View headquarters.",
+ "Amazon's Andy Jassy unveiled new AWS services in Seattle.",
+ # ... hundreds more documents
+ ]
+
+ # Process in batches for efficiency
+ all_entities = []
+ for i, doc in enumerate(documents):
+ entities = ner.extract_entities(doc)
+ all_entities.extend([
+ {**e, "doc_id": i} for e in entities
+ ])
+
+ if (i + 1) % 100 == 0:
+ print(f"Processed {i + 1}/{len(documents)} documents")
+
+ from collections import Counter
+ entity_types = Counter(e['type'] for e in all_entities)
+ print(f"Entity Distribution:")
+ for etype, count in entity_types.most_common():
+ print(f" {etype}: {count}")
++=======
+ ner = NamedEntityRecognizer(method="rule-based")
+ entities = ner.extract_entities("Apple Inc. was founded in 1976.")
+ ```
+
+ === "Machine Learning"
+ Uses trained models (spaCy, transformers) for extraction.
+
+ **Pros**: More accurate, handles variations
+
+ **Cons**: Requires training data, slower than rules
+
+ ```python
+ ner = NamedEntityRecognizer(method="spacy")
+ entities = ner.extract_entities(text)
+ ```
+
+ === "LLM-based"
+ Uses large language models (GPT-4, Claude) for extraction.
+
+ **Pros**: Most accurate, understands context
+
+ **Cons**: Slower, requires API access, costs money
+
+ ```python
+ ner = NamedEntityRecognizer(method="llm", model="gpt-4")
+ entities = ner.extract_entities(text)
++>>>>>>> origin/main
```
**Related Modules**:
@@@ -484,183 -222,6 +550,186 @@@ graph L
style F fill:#e3f2fd
```
++<<<<<<< HEAD
+**Practical Examples**:
+
+=== "Basic Relation Extraction"
+ Extract relationships between entities:
+
+ ```python
+ from semantica.semantic_extract import RelationExtractor, NamedEntityRecognizer
+
+ text = """
+ Tim Cook became CEO of Apple Inc. in 2011, succeeding Steve Jobs.
+ Apple is headquartered in Cupertino, California. The company
+ acquired Beats Electronics in 2014 for $3 billion.
+ """
+
+ # First extract entities
+ ner = NamedEntityRecognizer()
+ entities = ner.extract_entities(text)
+
+ # Then extract relationships
+ rel_extractor = RelationExtractor()
+ relations = rel_extractor.extract_relations(text, entities=entities)
+
+ print("Extracted Relationships:")
+ for rel in relations:
+ print(f" ({rel['source']}) --[{rel['type']}]--> ({rel['target']})")
+ print(f" Confidence: {rel.get('confidence', 0.0):.2f}")
+ ```
+
+=== "RelationExtractor Class"
+ Use the `RelationExtractor` for advanced control:
+
+ ```python
+ from semantica.semantic_extract import (
+ RelationExtractor,
+ NamedEntityRecognizer
+ )
+
+ # First extract entities
+ ner = NamedEntityRecognizer()
+ text = """
+ Dr. Sarah Chen published her research on quantum computing at MIT.
+ Her work was funded by DARPA and received the ACM Award in 2023.
+ """
+ entities = ner.extract_entities(text)
+
+ # Then extract relationships
+ rel_extractor = RelationExtractor(
+ relation_types=["works_at", "funded_by", "received", "published"],
+ bidirectional=False,
+ confidence_threshold=0.6
+ )
+
+ relations = rel_extractor.extract_relations(text, entities=entities)
+
+ print("Knowledge Graph Edges:")
+ for rel in relations:
+ arrow = "<->" if rel.get('bidirectional') else "->"
+ print(f" {rel['source_text']} {arrow} {rel['target_text']}")
+ print(f" Relation: {rel['type']}")
+ ```
+
+=== "Triple Extraction (RDF)"
+ Extract subject-predicate-object triples for RDF/semantic web:
+
+ ```python
+ from semantica.semantic_extract import (
+ TripleExtractor,
+ RDFSerializer,
+ TripleValidator
+ )
+
+ text = """
+ Albert Einstein was born in Ulm, Germany in 1879. He developed
+ the theory of relativity and won the Nobel Prize in Physics in 1921.
+ Einstein worked at Princeton University until his death in 1955.
+ """
+
+ # Extract RDF-style triples
+ extractor = TripleExtractor(
+ include_temporal=True, # Include time information
+ include_provenance=True # Track source sentences
+ )
+
+ triples = extractor.extract_triples(text)
+
+ print("Extracted Triples (Subject-Predicate-Object):")
+ for triple in triples:
+ print(f" Subject: {triple['subject']}")
+ print(f" Predicate: {triple['predicate']}")
+ print(f" Object: {triple['object']}")
+ if triple.get('temporal'):
+ print(f" When: {triple['temporal']}")
+ print()
+
+ validator = TripleValidator()
+ validation = validator.validate(triples)
+ print(f"Valid triples: {validation['valid_count']}/{len(triples)}")
+
+ serializer = RDFSerializer(format="turtle")
+ turtle_output = serializer.serialize(
+ triples,
+ base_uri="https://example.org/knowledge/"
+ )
+ print("Turtle Output:")
+ print(turtle_output)
+ ```
+
+=== "Event Detection"
+ Extract events with temporal information:
+
+ ```python
+ from semantica.semantic_extract import (
+ EventDetector,
+ TemporalEventProcessor
+ )
+
+ news_text = """
+ On March 15, 2024, SpaceX successfully launched Starship from
+ Boca Chica, Texas. The rocket reached orbit before splashing down
+ in the Indian Ocean. CEO Elon Musk announced plans for a Mars
+ mission by 2026.
+ """
+
+ # Detect events
+ detector = EventDetector(
+ event_types=["launch", "announcement", "achievement"],
+ extract_participants=True,
+ extract_location=True,
+ extract_time=True
+ )
+
+ events = detector.detect_events(news_text)
+
+ print("Detected Events:")
+ for event in events:
+ print(f" Event: {event['description']}")
+ print(f" Type: {event['type']}")
+ print(f" When: {event.get('datetime', 'Unknown')}")
+ print(f" Where: {event.get('location', 'Unknown')}")
+ print(f" Who: {', '.join(event.get('participants', []))}")
+ print()
+
+ # Process temporal relationships between events
+ temporal = TemporalEventProcessor()
+ timeline = temporal.build_timeline(events)
+
+ print("Event Timeline:")
+ for i, evt in enumerate(timeline, 1):
+ print(f" {i}. {evt['datetime']}: {evt['description']}")
+ ```
+
+=== "Coreference Resolution"
+ Resolve pronouns and entity references:
+
+ ```python
+ from semantica.semantic_extract import CoreferenceResolver
+
+ text = """
+ Apple Inc. announced their new iPhone. The company said it would
+ be available in September. Tim Cook presented the device at their
+ headquarters. He emphasized its improved camera capabilities.
+ """
+
+ resolver = CoreferenceResolver()
+ result = resolver.resolve(text)
+
+ print("Coreference Chains:")
+ for chain in result['chains']:
+ print(f" Entity: {chain['canonical']}")
+ print(f" Mentions: {', '.join(chain['mentions'])}")
+ print()
+
+ resolved_text = resolver.get_resolved_text(text)
+ print("Resolved Text:")
+ print(resolved_text)
+ ```
+
++=======
++>>>>>>> origin/main
**Related Modules**:
- [`semantic_extract` Module](reference/semantic_extract.md) - Relationship extraction
- [`kg` Module](reference/kg.md) - Building graphs from relationships
@@@ -700,228 -261,6 +769,231 @@@ Embedding: [0.123, -0.456, 0.789, ...,
| **HuggingFace** | sentence-transformers | 384-768 | Medium | Free | Development, open source |
| **Local** | Various | Variable | Slow | Free | Privacy, offline use |
++<<<<<<< HEAD
+**Practical Examples**:
+
+=== "Quick Start"
+ Generate embeddings in one call:
+
+ ```python
+ from semantica.embeddings import EmbeddingGenerator, embed_text
+
+ # Using EmbeddingGenerator class
+ texts = [
+ "Machine learning is transforming industries",
+ "Artificial intelligence powers modern applications",
+ "Deep learning enables image recognition",
+ "Cooking recipes are delicious" # Different topic
+ ]
+
+ generator = EmbeddingGenerator()
+
+ # Generate embeddings for multiple texts
+ embeddings = []
+ for text in texts:
+ emb = generator.generate_embeddings(text, data_type="text")
+ embeddings.append(emb)
+
+ print(f"Generated {len(embeddings)} embeddings")
+ print(f"Dimensions: {embeddings[0].shape}")
+
+ # Or use the convenience function for single text
+ embedding = embed_text("Hello, world!", method="sentence_transformers")
+ print(f"Single embedding shape: {embedding.shape}")
+ ```
+
+=== "Similarity Search"
+ Calculate semantic similarity between texts:
+
+ ```python
+ from semantica.embeddings import (
+ EmbeddingGenerator,
+ calculate_similarity
+ )
+ import numpy as np
+
+ generator = EmbeddingGenerator()
+
+ # Generate embeddings
+ query = "How does photosynthesis work?"
+ documents = [
+ "Plants convert sunlight into energy through photosynthesis",
+ "The process of photosynthesis occurs in chloroplasts",
+ "Dogs are popular household pets",
+ "Solar panels convert sunlight to electricity",
+ "Chlorophyll absorbs light for photosynthesis"
+ ]
+
+ query_emb = generator.generate_embeddings(query, data_type="text")
+ doc_embs = [generator.generate_embeddings(d, data_type="text") for d in documents]
+
+ print("Semantic Similarity Search:")
+ print(f"Query: \"{query}\"")
+
+ similarities = []
+ for i, doc_emb in enumerate(doc_embs):
+ sim = calculate_similarity(query_emb, doc_emb, method="cosine")
+ similarities.append((sim, documents[i]))
+
+ for sim, doc in sorted(similarities, reverse=True):
+ relevance = "HIGH" if sim > 0.6 else "MED" if sim > 0.3 else "LOW"
+ print(f" [{relevance}] {sim:.3f}: {doc[:50]}...")
+ ```
+
+=== "Multiple Embedding Types"
+ Work with text, image, and audio embeddings:
+
+ ```python
+ from semantica.embeddings import (
+ TextEmbedder,
+ ImageEmbedder,
+ AudioEmbedder,
+ MultimodalEmbedder
+ )
+
+ text_embedder = TextEmbedder(model="all-MiniLM-L6-v2")
+ text_emb = text_embedder.embed("A beautiful sunset over the ocean")
+ print(f"Text embedding: {text_emb.shape}")
+
+ image_embedder = ImageEmbedder(model="clip")
+ image_emb = image_embedder.embed("sunset_photo.jpg")
+ print(f"Image embedding: {image_emb.shape}")
+
+ audio_embedder = AudioEmbedder()
+ audio_emb = audio_embedder.embed("ocean_waves.mp3")
+ print(f"Audio embedding: {audio_emb.shape}")
+
+ multimodal = MultimodalEmbedder()
+ combined = multimodal.embed(
+ text="sunset over ocean",
+ image="sunset_photo.jpg",
+ strategy="concatenate"
+ )
+ print(f"Combined embedding: {combined.shape}")
+
+ from semantica.embeddings import calculate_similarity
+ text_query = text_embedder.embed("beach at sunset")
+ images = ["beach.jpg", "mountain.jpg", "city.jpg"]
+
+ for img in images:
+ img_emb = image_embedder.embed(img)
+ sim = calculate_similarity(text_query, img_emb, method="cosine")
+ print(f" {img}: {sim:.3f}")
+ ```
+
+=== "Embedding Optimization"
+ Optimize embeddings for storage and performance:
+
+ ```python
+ from semantica.embeddings import EmbeddingOptimizer
+ import numpy as np
+
+ optimizer = EmbeddingOptimizer()
+
+ # Generate some embeddings
+ embeddings = np.random.randn(1000, 768).astype(np.float32)
+ print(f"Original size: {embeddings.nbytes / 1024:.1f} KB")
+
+ # Dimension reduction with PCA
+ reduced = optimizer.reduce_dimensions(
+ embeddings,
+ method="pca",
+ target_dims=256
+ )
+ print(f"After PCA (256d): {reduced.nbytes / 1024:.1f} KB")
+
+ # Quantization for storage efficiency
+ quantized = optimizer.quantize(
+ embeddings,
+ bits=8 # 8-bit quantization
+ )
+ print(f"After 8-bit quantization: {quantized.nbytes / 1024:.1f} KB")
+
+ # Normalize for cosine similarity
+ normalized = optimizer.normalize(embeddings, method="l2")
+ print(f"Normalized: unit vectors ready for dot product")
+ ```
+
+=== "Pooling Strategies"
+ Aggregate embeddings using different strategies:
+
+ ```python
+ from semantica.embeddings import (
+ MeanPooling,
+ MaxPooling,
+ AttentionPooling,
+ HierarchicalPooling
+ )
+ import numpy as np
+
+ # Simulate token-level embeddings (e.g., from a transformer)
+ # Shape: (sequence_length, embedding_dim)
+ token_embeddings = np.random.randn(128, 768)
+
+ # Mean pooling - average all tokens
+ mean_pool = MeanPooling()
+ mean_result = mean_pool.pool(token_embeddings)
+ print(f"Mean pooling: {mean_result.shape}") # (768,)
+
+ # Max pooling - take max across tokens
+ max_pool = MaxPooling()
+ max_result = max_pool.pool(token_embeddings)
+ print(f"Max pooling: {max_result.shape}") # (768,)
+
+ # Attention-based pooling - learned weights
+ attn_pool = AttentionPooling(hidden_dim=768)
+ attn_result = attn_pool.pool(token_embeddings)
+ print(f"Attention pooling: {attn_result.shape}") # (768,)
+
+ # Hierarchical pooling for long documents
+ hier_pool = HierarchicalPooling(chunk_size=32)
+ document_embeddings = np.random.randn(10, 128, 768) # 10 paragraphs
+ hier_result = hier_pool.pool(document_embeddings)
+ print(f"Hierarchical pooling: {hier_result.shape}") # (768,)
+ ```
+
+=== "Context Management"
+ Handle long texts with context windows:
+
+ ```python
+ from semantica.embeddings import ContextManager, EmbeddingGenerator
+
+ # Long document that exceeds model context
+ long_document = "..." * 10000 # Very long text
+
+ # Manage context windows
+ context_manager = ContextManager(
+ max_window_size=512, # Tokens per window
+ overlap=50, # Overlap between windows
+ preserve_sentences=True
+ )
+
+ windows = context_manager.split(long_document)
+ print(f"Split into {len(windows)} windows")
+
+ # Generate embeddings for each window
+ generator = EmbeddingGenerator()
+ window_embeddings = []
+
+ for i, window in enumerate(windows):
+ emb = generator.generate_embeddings(window.text, data_type="text")
+ window_embeddings.append({
+ 'embedding': emb,
+ 'start_char': window.start_char,
+ 'end_char': window.end_char
+ })
+
+ # Merge windows for document-level embedding
+ from semantica.embeddings import pool_embeddings
+ import numpy as np
+
+ all_embs = np.array([w['embedding'] for w in window_embeddings])
+ doc_embedding = pool_embeddings(all_embs, method="mean")
+ print(f"Document embedding shape: {doc_embedding.shape}")
+ ```
+
++=======
++>>>>>>> origin/main
**Related Modules**:
- [`embeddings` Module](reference/embeddings.md) - Embedding generation
- [`vector_store` Module](reference/vector_store.md) - Vector storage and search
@@@ -955,535 -294,56 +1027,541 @@@ timelin
: Relationship A->B expired
```
-**Related Modules**:
-- [`kg` Module](reference/kg.md) - Temporal graph support
-- [`visualization` Module](reference/visualization.md) - Temporal visualization
-
----
-
-### 6. GraphRAG
-
-!!! abstract "Definition"
- **GraphRAG (Graph-Augmented Retrieval Augmented Generation)** is an advanced RAG approach that combines vector search with knowledge graph traversal to provide more accurate and contextually relevant information to LLMs.
++<<<<<<< HEAD
+**Practical Examples**:
-**How GraphRAG Works**:
-
-```mermaid
-flowchart TD
- subgraph Query["Query Processing"]
- Q[User Query] --> VS[Vector Search]
- Q --> KE[Keyword Extraction]
- end
+=== "Building Temporal Graphs"
+ Create a knowledge graph with time-aware edges:
- subgraph Retrieval["Hybrid Retrieval"]
- VS --> Docs[Relevant Documents]
- KE --> Nodes[Start Nodes]
- Nodes --> Trav[Graph Traversal]
- Trav --> Context[Graph Context]
- end
+ ```python
+ from semantica.kg import GraphBuilder
+ from datetime import datetime, timedelta
- subgraph Synthesis["Answer Generation"]
- Docs --> Prompt[Enhanced Prompt]
- Context --> Prompt
- Prompt --> LLM[LLM Generation]
- LLM --> A[Accurate Answer]
- end
+ # Build a temporal knowledge graph
+ builder = GraphBuilder(
+ enable_temporal=True,
+ temporal_granularity="day", # day, hour, minute, second
+ track_history=True,
+ version_snapshots=True
+ )
- style Q fill:#e1f5fe
- style LLM fill:#e8f5e9
- style A fill:#fff9c4
-```
+ # Add time-stamped data
+ sources = [{
+ "entities": [
+ {
+ "id": "e1",
+ "text": "Satya Nadella",
+ "type": "Person",
+ "valid_from": "2014-02-04" # Became CEO
+ },
+ {
+ "id": "e2",
+ "text": "Microsoft",
+ "type": "Organization"
+ },
+ {
+ "id": "e3",
+ "text": "Steve Ballmer",
+ "type": "Person",
+ "valid_from": "2000-01-13",
+ "valid_until": "2014-02-04" # Was CEO until
+ }
+ ],
+ "relationships": [
+ {
+ "source": "e1",
+ "target": "e2",
+ "type": "CEO_OF",
+ "valid_from": "2014-02-04",
+ "valid_until": None # Still active
+ },
+ {
+ "source": "e3",
+ "target": "e2",
+ "type": "CEO_OF",
+ "valid_from": "2000-01-13",
+ "valid_until": "2014-02-04"
+ }
+ ]
+ }]
+
+ kg = builder.build(sources)
+ print(f"Built temporal graph with {kg['metadata']['num_entities']} entities")
+ ```
-**Advantages over Traditional RAG**:
+=== "Temporal Queries"
+ Query the graph at specific points in time:
+
+ ```python
+ from semantica.kg import TemporalGraphQuery
+ from datetime import datetime
+
+ # Initialize temporal query engine
+ temporal_query = TemporalGraphQuery(kg)
+
+ # Query 1: Who was CEO in 2010?
+ state_2010 = temporal_query.query_at_time(
+ datetime(2010, 6, 1),
+ query_type="relationships",
+ relationship_type="CEO_OF"
+ )
+ print(f"CEO in 2010: {state_2010['results']}")
+
+ state_2020 = temporal_query.query_at_time(
+ datetime(2020, 6, 1),
+ query_type="relationships",
+ relationship_type="CEO_OF"
+ )
+ print(f"CEO in 2020: {state_2020['results']}")
+
+ ceo_history = temporal_query.query_time_range(
+ start_time=datetime(2000, 1, 1),
+ end_time=datetime(2024, 1, 1),
+ relationship_type="CEO_OF"
+ )
+
+ print("CEO History:")
+ for rel in ceo_history['results']:
+ print(f" {rel['source']} -> {rel['valid_from']} to {rel.get('valid_until', 'present')}")
+ ```
-| Feature | Traditional RAG | GraphRAG |
-| :--- | :--- | :--- |
-| **Query Understanding** | Keyword matching | Semantic + structural |
-| **Context Retrieval** | Document chunks | Documents + relationships |
+=== "Pattern Detection"
+ Detect temporal patterns in your graph:
+
+ ```python
+ from semantica.kg import TemporalPatternDetector
+
+ # Initialize pattern detector
+ detector = TemporalPatternDetector(kg)
+
+ # Detect sequences: A happened, then B, then C
+ sequences = detector.detect_sequences(
+ event_types=["HIRED", "PROMOTED", "RESIGNED"],
+ max_gap_days=365 # Events must be within 1 year
+ )
+
+ print("Detected Sequences:")
+ for seq in sequences:
+ print(f" {' -> '.join(seq['events'])}")
+ print(f" Entity: {seq['entity']}")
+ print(f" Duration: {seq['duration_days']} days")
+
+ cycles = detector.detect_cycles(
+ min_occurrences=2,
+ relationship_types=["QUARTERLY_REPORT"]
+ )
+
+ print("Detected Cycles:")
+ for cycle in cycles:
+ print(f" Pattern: {cycle['pattern']}")
+ print(f" Period: {cycle['period_days']} days")
+ print(f" Occurrences: {cycle['count']}")
+
+ trends = detector.detect_trends(
+ metric="employee_count",
+ entity_type="Organization",
+ window_days=90
+ )
+
+ for trend in trends:
+ direction = "UP" if trend['direction'] == 'increasing' else "DOWN"
+ print(f"[{direction}] {trend['entity']}: {trend['change_percent']:.1f}% over {trend['period']}")
+ ```
+
+=== "Version Management"
+ Track and manage graph versions over time:
+
+ ```python
+ from semantica.kg import TemporalVersionManager
+ from datetime import datetime
+
+ # Initialize version manager
+ version_mgr = TemporalVersionManager(kg)
+
+ # Create a snapshot of current state
+ snapshot_id = version_mgr.create_snapshot(
+ description="Q4 2024 knowledge graph",
+ timestamp=datetime.now()
+ )
+ print(f"Created snapshot: {snapshot_id}")
+
+ diff = version_mgr.compare_versions(
+ version_a=snapshot_id,
+ version_b="current"
+ )
+
+ print("Changes since snapshot:")
+ print(f" Added entities: {len(diff['added_entities'])}")
+ print(f" Removed entities: {len(diff['removed_entities'])}")
+ print(f" Modified entities: {len(diff['modified_entities'])}")
+ print(f" Added relationships: {len(diff['added_relationships'])}")
+ print(f" Removed relationships: {len(diff['removed_relationships'])}")
+
+ evolution = version_mgr.analyze_evolution(
+ start_date=datetime(2024, 1, 1),
+ end_date=datetime(2024, 12, 31)
+ )
+
+ print("Graph Evolution (2024):")
+ print(f" Total snapshots: {evolution['snapshot_count']}")
+ print(f" Net entity growth: {evolution['entity_growth']}")
+ print(f" Net relationship growth: {evolution['relationship_growth']}")
+ ```
+
+=== "Graph Evolution Analysis"
+ Analyze how your knowledge graph changes over time:
+
+ ```python
+ from semantica.kg import GraphAnalyzer
+
+ analyzer = GraphAnalyzer()
+
+ # Analyze temporal evolution
+ evolution = analyzer.analyze_temporal_evolution(
+ kg,
+ time_periods=[
+ ("2022-01-01", "2022-06-30"),
+ ("2022-07-01", "2022-12-31"),
+ ("2023-01-01", "2023-06-30"),
+ ("2023-07-01", "2023-12-31")
+ ]
+ )
+
+ print("Graph Evolution Analysis:")
+ for period in evolution['periods']:
+ print(f"Period: {period['start']} to {period['end']}")
+ print(f" Entities: {period['entity_count']} (+{period['entity_growth']})")
+ print(f" Relationships: {period['relationship_count']} (+{period['rel_growth']})")
+ print(f" Density: {period['density']:.4f}")
+ print(f" New entity types: {period['new_types']}")
+ print()
+
+ stability = analyzer.calculate_stability(kg, window_days=30)
+ print(f"Graph Stability Score: {stability['score']:.2f}")
+ print(f" Most stable entities: {stability['most_stable'][:3]}")
+ print(f" Most volatile entities: {stability['most_volatile'][:3]}")
+ ```
+
++=======
++>>>>>>> origin/main
+**Related Modules**:
+- [`kg` Module](reference/kg.md) - Temporal graph support
+- [`visualization` Module](reference/visualization.md) - Temporal visualization
+
+---
+
+### 6. GraphRAG
+
+!!! abstract "Definition"
+ **GraphRAG (Graph-Augmented Retrieval Augmented Generation)** is an advanced RAG approach that combines vector search with knowledge graph traversal to provide more accurate and contextually relevant information to LLMs.
+
+**How GraphRAG Works**:
+
+```mermaid
+flowchart TD
+ subgraph Query["Query Processing"]
+ Q[User Query] --> VS[Vector Search]
+ Q --> KE[Keyword Extraction]
+ end
+
+ subgraph Retrieval["Hybrid Retrieval"]
+ VS --> Docs[Relevant Documents]
+ KE --> Nodes[Start Nodes]
+ Nodes --> Trav[Graph Traversal]
+ Trav --> Context[Graph Context]
+ end
+
+ subgraph Synthesis["Answer Generation"]
+ Docs --> Prompt[Enhanced Prompt]
+ Context --> Prompt
+ Prompt --> LLM[LLM Generation]
+ LLM --> A[Accurate Answer]
+ end
+
+ style Q fill:#e1f5fe
+ style LLM fill:#e8f5e9
+ style A fill:#fff9c4
+```
+
+**Advantages over Traditional RAG**:
+
+| Feature | Traditional RAG | GraphRAG |
+| :--- | :--- | :--- |
+| **Query Understanding** | Keyword matching | Semantic + structural |
+| **Context Retrieval** | Document chunks | Documents + relationships |
| **Answer Accuracy** | Good | Better (grounded in graph) |
| **Hallucination Risk** | Medium | Lower |
| **Complex Queries** | Limited | Excellent |
| **Relationship Awareness** | No | Yes |
++<<<<<<< HEAD
+**Practical Examples**:
+
+=== "Basic GraphRAG"
+ Build a knowledge base and query with GraphRAG:
+
+ ```python
+ from semantica import Semantica
+ from semantica.vector_store import VectorStore, store_vectors, search_vectors
+ from semantica.semantic_extract import NamedEntityRecognizer
+ from semantica.embeddings import embed_text
+
+ # Initialize Semantica
+ semantica = Semantica()
+
+ # Build knowledge base from documents
+ result = semantica.build_knowledge_base(
+ sources=["company_docs/", "research_papers/"],
+ embeddings=True,
+ graph=True
+ )
+
+ kg = result["knowledge_graph"]
+ embeddings_data = result["embeddings"]
+
+ # Initialize vector store
+ vector_store = VectorStore(backend="faiss", dimension=768)
+
+ # Store embeddings
+ vector_ids = vector_store.store_vectors(
+ vectors=embeddings_data["vectors"],
+ metadata=embeddings_data["metadata"]
+ )
+
+ # Initialize NER for query processing
+ ner = NamedEntityRecognizer()
+
+ # Process a query
+ query = "Who is the CEO of Apple?"
+
+ # Get query embedding and search
+ query_embedding = embed_text(query, method="sentence_transformers")
+ vector_results = vector_store.search(query_embedding, k=5)
+
+ # Extract entities from query
+ query_entities = ner.extract_entities(query)
+
+ # Get graph context for query entities
+ graph_context = []
+ for entity in query_entities:
+ for rel in kg["relationships"]:
+ if entity["text"].lower() in rel.get("source_text", "").lower():
+ graph_context.append(rel)
+
+ print(f"Vector results: {len(vector_results)}")
+ print(f"Graph context: {len(graph_context)} relevant relationships")
+ ```
+
+=== "Context Retrieval"
+ Use the context module for agent memory and retrieval:
+
+ ```python
+ from semantica.context import (
+ ContextRetriever,
+ AgentMemory,
+ ContextGraphBuilder,
+ build_context
+ )
+ from semantica.vector_store import VectorStore
+
+ # Initialize vector store
+ vector_store = VectorStore(backend="faiss", dimension=768)
+
+ # Build context graph
+ context_result = build_context(
+ entities=kg["entities"],
+ relationships=kg["relationships"],
+ vector_store=vector_store,
+ knowledge_graph=kg,
+ store_initial_memories=True
+ )
+
+ print(f"Built context with {context_result['statistics']['graph'].get('node_count', 0)} nodes")
+
+ # Initialize agent memory
+ memory = AgentMemory(
+ vector_store=vector_store,
+ knowledge_graph=kg
+ )
+
+ # Store facts in memory
+ memory_id = memory.store(
+ "Tim Cook is the CEO of Apple Inc.",
+ metadata={"type": "fact", "source": "document"}
+ )
+ print(f"Stored memory: {memory_id}")
+
+ # Initialize context retriever
+ retriever = ContextRetriever(
+ vector_store=vector_store,
+ knowledge_graph=kg
+ )
+
+ # Retrieve relevant context
+ results = retriever.retrieve(
+ query="Who leads Apple?",
+ max_results=10
+ )
+
+ print("Retrieved context:")
+ for r in results:
+ print(f" {r.content} (score: {r.score:.2f})")
+ ```
+
+=== "Hybrid Search"
+ Combine vector and metadata search:
+
+ ```python
+ from semantica.vector_store import (
+ VectorStore,
+ HybridSearch,
+ MetadataFilter,
+ MetadataStore
+ )
+ from semantica.embeddings import embed_text
+
+ # Initialize stores
+ vector_store = VectorStore(backend="faiss", dimension=768)
+ metadata_store = MetadataStore()
+ hybrid_search = HybridSearch()
+
+ # Generate query embedding
+ query_embedding = embed_text("Apple CEO responsibilities", method="sentence_transformers")
+
+ # Create metadata filter
+ metadata_filter = MetadataFilter()
+ metadata_filter.eq("entity_type", "Person")
+ metadata_filter.eq("relationship", "CEO_OF")
+
+ # Get stored data
+ all_vectors = vector_store.get_all_vectors()
+ all_metadata = metadata_store.get_all()
+ all_ids = vector_store.get_all_ids()
+
+ # Perform hybrid search
+ results = hybrid_search.search(
+ query_vector=query_embedding,
+ vectors=all_vectors,
+ metadata=all_metadata,
+ vector_ids=all_ids,
+ filter=metadata_filter,
+ top_k=10
+ )
+
+ print("Hybrid search results:")
+ for result in results:
+ print(f" ID: {result['id']}, Score: {result['score']:.3f}")
+ ```
+
+=== "Reasoning with Inference"
+ Use the reasoning module for graph inference:
+
+ ```python
+ from semantica.reasoning import (
+ InferenceEngine,
+ RuleManager,
+ Rule,
+ ExplanationGenerator
+ )
+
+ # Initialize engine and rule manager
+ engine = InferenceEngine()
+ rule_manager = RuleManager()
+
+ # Add inference rules
+ rule_manager.add_rule(Rule(
+ name="ceo_works_for",
+ conditions=["?person CEO_OF ?company"],
+ conclusions=["?person WORKS_FOR ?company"],
+ priority=1
+ ))
+
+ rule_manager.add_rule(Rule(
+ name="transitivity",
+ conditions=["?a PART_OF ?b", "?b PART_OF ?c"],
+ conclusions=["?a PART_OF ?c"],
+ priority=2
+ ))
+
+ # Define facts
+ facts = [
+ {"subject": "Tim Cook", "predicate": "CEO_OF", "object": "Apple"},
+ {"subject": "iPhone", "predicate": "PART_OF", "object": "Apple"},
+ {"subject": "A15 Chip", "predicate": "PART_OF", "object": "iPhone"}
+ ]
+
+ # Run inference
+ inferred = engine.infer(
+ facts=facts,
+ rules=rule_manager.get_rules(),
+ strategy="forward"
+ )
+
+ print(f"Original facts: {len(facts)}")
+ print(f"After inference: {len(inferred.facts)}")
+
+ # Generate explanations
+ explainer = ExplanationGenerator()
+ for new_fact in inferred.new_facts:
+ explanation = explainer.generate_explanation(
+ conclusion=new_fact,
+ reasoning_path=inferred.reasoning_path
+ )
+ print(f" {new_fact}: {explanation.summary}")
+ ```
+
+=== "LLM-Enhanced Retrieval"
+ Integrate with LLM providers for answer generation:
+
+ ```python
+ from semantica import Semantica
+ from semantica.semantic_extract import create_provider, OpenAIProvider
+ from semantica.context import ContextRetriever
+ from semantica.vector_store import VectorStore
+
+ # Initialize components
+ vector_store = VectorStore(backend="faiss", dimension=768)
+
+ # Create LLM provider
+ provider = create_provider(
+ provider_type="openai",
+ model="gpt-4o"
+ )
+
+ # Initialize context retriever
+ retriever = ContextRetriever(
+ vector_store=vector_store,
+ knowledge_graph=kg
+ )
+
+ # Define question
+ question = "What products does Apple manufacture?"
+
+ # Retrieve relevant context
+ context = retriever.retrieve(query=question, max_results=5)
+
+ # Format context for prompt
+ context_text = "\n".join([
+ f"- {c.content}" for c in context
+ ])
+
+ # Build prompt
+ prompt = f"""Based on this context, answer the question.
+
+Context:
+{context_text}
+
+Question: {question}
+
+Answer:"""
+
+ # Generate response
+ response = provider.generate(prompt)
+ print(f"Answer: {response}")
+ ```
+
++=======
++>>>>>>> origin/main
**Related Modules**:
- [`kg` Module](reference/kg.md) - Knowledge graph construction
- [`vector_store` Module](reference/vector_store.md) - Vector search
@@@ -1526,327 -386,6 +1604,330 @@@ classDiagra
Company --> Location : locatedIn
```
++<<<<<<< HEAD
+**Practical Examples**:
+
+=== "Automatic Ontology Generation"
+ Generate an ontology from your knowledge graph:
+
+ ```python
+ from semantica.ontology import OntologyGenerator, generate_ontology
+
+ # Your knowledge graph data
+ kg_data = {
+ "entities": [
+ {"id": "e1", "text": "Apple Inc.", "type": "Company"},
+ {"id": "e2", "text": "Tim Cook", "type": "Person"},
+ {"id": "e3", "text": "iPhone", "type": "Product"},
+ {"id": "e4", "text": "Cupertino", "type": "Location"}
+ ],
+ "relationships": [
+ {"source": "e2", "target": "e1", "type": "CEO_OF"},
+ {"source": "e1", "target": "e3", "type": "MANUFACTURES"},
+ {"source": "e1", "target": "e4", "type": "HEADQUARTERED_IN"}
+ ]
+ }
+
+ # Method 1: Using convenience function
+ ontology = generate_ontology(kg_data, method="default")
+ print(f"Quick generation: {len(ontology.get('classes', []))} classes")
+
+ # Method 2: Using OntologyGenerator class for more control
+ generator = OntologyGenerator(
+ base_uri="https://example.org/ontology/",
+ version="1.0.0"
+ )
+
+ ontology = generator.generate_ontology(kg_data)
+
+ print(f"Generated Ontology:")
+ print(f" Classes: {len(ontology['classes'])}")
+ print(f" Properties: {len(ontology['properties'])}")
+ print(f" Axioms: {len(ontology.get('axioms', []))}")
+
+ # Display class details
+ print("Classes:")
+ for cls in ontology['classes']:
+ print(f" {cls['name']}")
+ print(f" URI: {cls['uri']}")
+ if cls.get('parent'):
+ print(f" Parent: {cls['parent']}")
+ ```
+
+=== "Class and Property Inference"
+ Automatically infer classes and properties from data:
+
+ ```python
+ from semantica.ontology import (
+ ClassInferrer,
+ PropertyGenerator,
+ infer_classes,
+ infer_properties
+ )
+
+ # Sample entities
+ entities = [
+ {"text": "Apple", "type": "Company"},
+ {"text": "Microsoft", "type": "Company"},
+ {"text": "Google", "type": "Company"},
+ {"text": "Tim Cook", "type": "Person"},
+ {"text": "Satya Nadella", "type": "Person"},
+ {"text": "iPhone", "type": "Product"},
+ {"text": "Windows", "type": "Product"},
+ ]
+
+ # Method 1: Using convenience function
+ classes = infer_classes(entities, method="default")
+
+ # Method 2: Using ClassInferrer for more control
+ class_inferrer = ClassInferrer(
+ min_occurrence=2, # Minimum entities to create a class
+ merge_similar=True,
+ similarity_threshold=0.8
+ )
+
+ classes = class_inferrer.infer_classes(entities)
+
+ print("Inferred Classes:")
+ for cls in classes:
+ print(f" {cls['name']}: {cls['instance_count']} instances")
+
+ # Infer properties from relationships
+ relationships = [
+ {"source_type": "Person", "target_type": "Company", "type": "CEO_OF"},
+ {"source_type": "Company", "target_type": "Product", "type": "MANUFACTURES"},
+ {"source_type": "Person", "target_type": "Company", "type": "WORKS_FOR"},
+ ]
+
+ # Using PropertyGenerator
+ prop_generator = PropertyGenerator()
+ properties = prop_generator.infer_properties(entities, relationships, classes)
+
+ print("Inferred Properties:")
+ for prop in properties:
+ print(f" {prop['name']}")
+ print(f" Domain: {prop['domain']} -> Range: {prop['range']}")
+ print(f" Type: {prop['property_type']}")
+ ```
+
+=== "OWL/RDF Generation"
+ Generate OWL ontologies in various formats:
+
+ ```python
+ from semantica.ontology import OWLGenerator, generate_owl
+
+ # Initialize OWL generator
+ owl_gen = OWLGenerator(
+ base_uri="https://example.org/onto/",
+ output_format="turtle" # turtle, rdf-xml, json-ld, n3
+ )
+
+ # Define ontology classes
+ owl_gen.add_class("Person", parent="Thing")
+ owl_gen.add_class("Company", parent="Thing")
+ owl_gen.add_class("CEO", parent="Person")
+
+ # Add object properties
+ owl_gen.add_object_property(
+ name="worksFor",
+ domain="Person",
+ range="Company"
+ )
+
+ owl_gen.add_object_property(
+ name="isCEOOf",
+ domain="CEO",
+ range="Company",
+ functional=True # A CEO can only be CEO of one company
+ )
+
+ # Add data properties
+ owl_gen.add_data_property(
+ name="hasName",
+ domain="Person",
+ range="xsd:string"
+ )
+
+ owl_gen.add_data_property(
+ name="foundedYear",
+ domain="Company",
+ range="xsd:integer"
+ )
+
+ # Add axioms/constraints
+ owl_gen.add_axiom(
+ class_name="CEO",
+ axiom="SubClassOf: worksFor exactly 1 Company"
+ )
+
+ # Generate Turtle output
+ turtle_output = owl_gen.serialize()
+ print(turtle_output)
+
+ # Example output:
+ # @prefix : <https://example.org/onto/> .
+ # @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ # :Person a owl:Class .
+ # :Company a owl:Class .
+ # :CEO a owl:Class ; rdfs:subClassOf :Person .
+
+ # Save to file
+ owl_gen.save("company_ontology.ttl")
+ print("Ontology saved to company_ontology.ttl")
+ ```
+
+=== "Ontology Validation"
+ Validate ontologies with symbolic reasoners:
+
+ ```python
+ from semantica.ontology import OntologyValidator, validate_ontology
+
+ # Load or create ontology
+ ontology_file = "company_ontology.ttl"
+
+ # Method 1: Using the convenience function
+ result = validate_ontology(ontology_file, method="default")
+ print(f"Quick validation: {'Valid' if result['valid'] else 'Invalid'}")
+
+ # Method 2: Using OntologyValidator for more control
+ validator = OntologyValidator(
+ reasoner="hermit", # hermit, pellet, or auto
+ check_consistency=True,
+ check_satisfiability=True
+ )
+
+ # Validate the ontology
+ validation_result = validator.validate(ontology_file)
+
+ print(f"Validation Results:")
+ print(f" Consistent: {'Yes' if validation_result.consistent else 'No'}")
+ print(f" Satisfiable: {'Yes' if validation_result.satisfiable else 'No'}")
+
+ if validation_result.errors:
+ print(f"Errors ({len(validation_result.errors)}):")
+ for error in validation_result.errors:
+ print(f" - {error}")
+
+ if validation_result.warnings:
+ print(f"Warnings ({len(validation_result.warnings)}):")
+ for warning in validation_result.warnings:
+ print(f" - {warning}")
+
+ # Check specific constraints
+ constraints = [
+ "Every CEO must work for exactly one Company",
+ "A Person cannot be their own manager"
+ ]
+
+ for constraint in constraints:
+ is_valid = validator.check_constraint(constraint)
+ status = "PASS" if is_valid else "FAIL"
+ print(f" [{status}] {constraint}")
+ ```
+
+=== "Competency Questions"
+ Define and evaluate competency questions:
+
+ ```python
+ from semantica.ontology import (
+ CompetencyQuestionsManager,
+ CompetencyQuestion,
+ OntologyEvaluator
+ )
+
+ # Initialize competency questions manager
+ cq_manager = CompetencyQuestionsManager()
+
+ # Add questions your ontology should be able to answer
+ cq_manager.add_question(CompetencyQuestion(
+ question="Who is the CEO of a given company?",
+ category="organizational",
+ priority=1, # 1=high, 2=medium, 3=low
+ expected_elements=["Person", "Company", "isCEOOf"]
+ ))
+
+ cq_manager.add_question(CompetencyQuestion(
+ question="What products does a company manufacture?",
+ category="products",
+ priority=1,
+ expected_elements=["Company", "Product", "manufactures"]
+ ))
+
+ cq_manager.add_question(CompetencyQuestion(
+ question="Where is a company headquartered?",
+ category="location",
+ priority=2,
+ expected_elements=["Company", "Location", "headquarteredIn"]
+ ))
+
+ # Get all questions
+ questions = cq_manager.get_questions()
+ print(f"Defined {len(questions)} competency questions")
+
+ # Evaluate ontology against competency questions
+ evaluator = OntologyEvaluator()
+ evaluation = evaluator.evaluate(
+ ontology="company_ontology.ttl",
+ competency_questions=questions
+ )
+
+ print(f"Ontology Evaluation:")
+ print(f" Coverage Score: {evaluation.coverage_score:.1%}")
+ print(f" Completeness Score: {evaluation.completeness_score:.1%}")
+
+ print("Question Coverage:")
+ for result in evaluation.question_results:
+ status = "YES" if result['answerable'] else "NO"
+ print(f" [{status}] {result['question']}")
+ if not result['answerable'] and result.get('missing_elements'):
+ print(f" Missing: {', '.join(result['missing_elements'])}")
+ ```
+
+=== "Domain Ontologies"
+ Use pre-built domain ontologies:
+
+ ```python
+ from semantica.ontology import DomainOntologies, OWLGenerator
+
+ # Access pre-built domain ontologies
+ domains = DomainOntologies()
+
+ # List available domains
+ print("Available Domain Ontologies:")
+ for domain in domains.list_domains():
+ print(f" - {domain['name']}: {domain['description']}")
+
+ # Load healthcare ontology
+ healthcare_onto = domains.load("healthcare")
+
+ print(f"Healthcare Ontology:")
+ print(f" Classes: {len(healthcare_onto.get('classes', []))}")
+ print(f" Properties: {len(healthcare_onto.get('properties', []))}")
+
+ # Extend the ontology
+ owl_gen = OWLGenerator(base_uri="https://example.org/healthcare/")
+ owl_gen.add_class("MedicalDevice", parent="Equipment")
+
+ # Load and merge multiple ontologies
+ finance_onto = domains.load("finance")
+ merged = domains.merge([healthcare_onto, finance_onto])
+
+ print(f"Merged ontology: {len(merged.get('classes', []))} classes")
+
+ # Find alignments between ontologies
+ alignments = domains.find_alignments(
+ healthcare_onto,
+ finance_onto,
+ similarity_threshold=0.7
+ )
+
+ print(f"Found {len(alignments)} concept alignments:")
+ for align in alignments[:5]:
+ print(f" {align['source']} ~ {align['target']} ({align['similarity']:.2f})")
+ ```
+
++=======
++>>>>>>> origin/main
**Related Modules**:
- [`ontology` Module](reference/ontology.md) - Ontology generation and management
- [`kg` Module](reference/kg.md) - Knowledge graph construction
@@@ -1868,177 -407,6 +1949,180 @@@
| **Coverage** | Breadth of domain coverage | Entity diversity, relationship types |
| **Freshness** | How up-to-date the data is | Last update timestamp, staleness |
++<<<<<<< HEAD
+**Practical Examples**:
+
+=== "Quality Assessment"
+ Assess the quality of your knowledge graph:
+
+ ```python
+ from semantica import (
+ KGQualityAssessor,
+ QualityMetrics,
+ CompletenessMetrics,
+ ConsistencyMetrics
+ )
+
+ # Initialize quality assessor
+ assessor = KGQualityAssessor()
+
+ # Run comprehensive quality assessment
+ quality_report = assessor.assess(kg)
+
+ print("Knowledge Graph Quality Report")
+ print(f"Overall Score: {quality_report['overall_score']:.1%}")
+
+ # Completeness analysis
+ completeness = quality_report['completeness']
+ print(f"Completeness: {completeness['score']:.1%}")
+ print(f" Entities with all required fields: {completeness['complete_entities']}/{completeness['total_entities']}")
+ print(f" Missing fields: {completeness['missing_fields']}")
+
+ # Consistency analysis
+ consistency = quality_report['consistency']
+ print(f"Consistency: {consistency['score']:.1%}")
+ print(f" Conflicts detected: {consistency['conflict_count']}")
+ print(f" Type mismatches: {consistency['type_mismatches']}")
+
+ # Coverage analysis
+ coverage = quality_report['coverage']
+ print(f"Coverage: {coverage['score']:.1%}")
+ print(f" Entity types: {coverage['entity_type_count']}")
+ print(f" Relationship types: {coverage['relationship_type_count']}")
+ print(f" Orphaned entities: {coverage['orphaned_count']}")
+ ```
+
+=== "Validation and Constraints"
+ Validate your graph against rules and constraints:
+
+ ```python
+ from semantica import ValidationEngine, ConstraintValidator
+ from semantica.kg import GraphValidator
+
+ # Initialize validation engine
+ validator = ValidationEngine()
+ graph_validator = GraphValidator()
+
+ # Define custom validation rules
+ rules = [
+ {
+ "name": "entity_has_type",
+ "description": "Every entity must have a type",
+ "check": lambda e: "type" in e and e["type"]
+ },
+ {
+ "name": "relationship_has_valid_endpoints",
+ "description": "Relationships must reference existing entities",
+ "check": lambda r, entities: r["source"] in entities and r["target"] in entities
+ },
+ {
+ "name": "person_has_name",
+ "description": "Person entities must have a name property",
+ "check": lambda e: e.get("type") != "Person" or "name" in e.get("properties", {})
+ }
+ ]
+
+ # Run validation with custom rules
+ results = validator.validate(kg, rules=rules)
+
+ print("Validation Results:")
+ for rule_name, result in results['rule_results'].items():
+ status = "PASS" if result['passed'] else "FAIL"
+ print(f"[{status}] {rule_name}")
+ if not result['passed']:
+ print(f" Failed: {len(result['violations'])} violations")
+ for v in result['violations'][:3]:
+ print(f" - {v['entity_id']}: {v['message']}")
+
+ # Validate graph structure
+ graph_result = graph_validator.validate(kg)
+ print(f"Graph Valid: {graph_result['valid']}")
+ if graph_result['errors']:
+ for error in graph_result['errors'][:3]:
+ print(f" Error: {error}")
+
+ # Check cardinality constraints
+ constraint_validator = ConstraintValidator()
+ constraint_results = constraint_validator.validate(kg, [
+ {"property": "CEO_OF", "max_cardinality": 1},
+ {"property": "WORKS_FOR", "min_cardinality": 0, "max_cardinality": 3}
+ ])
+ ```
+
+=== "Automated Fixes"
+ Automatically fix common quality issues:
+
+ ```python
+ from semantica import AutomatedFixer, IssueTracker, KGQualityAssessor
+
+ # Track and find issues
+ tracker = IssueTracker()
+ issues = tracker.find_issues(kg)
+
+ print(f"Found {len(issues)} issues:")
+ for issue in issues[:5]:
+ print(f" [{issue['severity']}] {issue['type']}: {issue['message']}")
+
+ # Initialize fixer
+ fixer = AutomatedFixer()
+
+ # Apply automated fixes
+ fixed_kg, fix_report = fixer.fix(
+ kg,
+ fix_types=[
+ "missing_entity_type",
+ "orphaned_relationships",
+ "duplicate_relationships",
+ "empty_properties"
+ ],
+ dry_run=False
+ )
+
+ print(f"Applied {fix_report['fixes_applied']} fixes:")
+ for fix_type, count in fix_report['by_type'].items():
+ print(f" {fix_type}: {count}")
+
+ # Measure quality improvement
+ assessor = KGQualityAssessor()
+ quality_after = assessor.assess(fixed_kg)
+ print(f"Quality after fixes: {quality_after['overall_score']:.1%}")
+ ```
+
+=== "Quality Reporting"
+ Generate detailed quality reports:
+
+ ```python
+ from semantica import QualityReporter, ImprovementSuggestions
+
+ # Initialize reporter
+ reporter = QualityReporter()
+
+ # Generate HTML report
+ reporter.generate_report(
+ kg,
+ output_path="quality_report.html",
+ format="html",
+ include_visualizations=True
+ )
+
+ # Generate JSON report for programmatic use
+ json_report = reporter.generate_report(kg, format="json")
+
+ print(f"Report generated with {len(json_report.get('sections', []))} sections")
+
+ # Get improvement suggestions
+ suggestions = ImprovementSuggestions()
+ recommendations = suggestions.analyze(kg)
+
+ print("Improvement Suggestions:")
+ for rec in recommendations:
+ print(f" Priority {rec['priority']}: {rec['suggestion']}")
+ print(f" Impact: {rec['expected_improvement']}")
+ print(f" Effort: {rec['effort_level']}")
+ ```
+
++=======
++>>>>>>> origin/main
**Related Modules**:
- [`kg_qa` Module](reference/evals.md) - Quality assurance and evaluation
- [`conflicts` Module](../semantica/conflicts/conflicts_usage.md) - Conflict detection
@@@ -2060,212 -428,6 +2144,215 @@@
Deduplication works by calculating similarity between entities. If similarity exceeds a threshold, entities are merged; otherwise, they remain separate.
++<<<<<<< HEAD
+**Practical Examples**:
+
+=== "Entity Resolution"
+ Identify and resolve duplicate entities:
+
+ ```python
+ from semantica.kg import EntityResolver, Deduplicator, resolve_entities
+
+ # Sample entities with potential duplicates
+ entities = [
+ {"id": "e1", "text": "Apple Inc.", "type": "Organization"},
+ {"id": "e2", "text": "Apple", "type": "Organization"},
+ {"id": "e3", "text": "Apple Computer, Inc.", "type": "Organization"},
+ {"id": "e4", "text": "Microsoft", "type": "Organization"},
+ {"id": "e5", "text": "MSFT", "type": "Organization"},
+ {"id": "e6", "text": "Microsoft Corporation", "type": "Organization"},
+ ]
+
+ # Method 1: Using convenience function
+ resolved = resolve_entities(entities, method="fuzzy")
+
+ # Method 2: Using EntityResolver class for more control
+ resolver = EntityResolver(
+ strategy="fuzzy", # "exact", "fuzzy", or "semantic"
+ similarity_threshold=0.85,
+ use_embeddings=True
+ )
+
+ # Find duplicate groups
+ duplicate_groups = resolver.find_duplicates(entities)
+
+ print("Duplicate Groups Found:")
+ for i, group in enumerate(duplicate_groups, 1):
+ print(f"Group {i}:")
+ for entity in group['entities']:
+ print(f" - {entity['text']} (id: {entity['id']})")
+ print(f" Confidence: {group['confidence']:.2f}")
+ ```
+
+=== "Semantic Matching"
+ Use embeddings for semantic similarity matching:
+
+ ```python
+ from semantica.kg import EntityResolver
+ from semantica.embeddings import EmbeddingGenerator
+
+ # Initialize with semantic matching
+ generator = EmbeddingGenerator()
+
+ resolver = EntityResolver(
+ strategy="semantic",
+ embedding_generator=generator,
+ similarity_threshold=0.8
+ )
+
+ # Entities with semantic variations
+ entities = [
+ {"id": "e1", "text": "Chief Executive Officer", "type": "Title"},
+ {"id": "e2", "text": "CEO", "type": "Title"},
+ {"id": "e3", "text": "Managing Director", "type": "Title"},
+ {"id": "e4", "text": "Head of the Company", "type": "Title"},
+ {"id": "e5", "text": "Software Developer", "type": "Title"},
+ {"id": "e6", "text": "Programmer", "type": "Title"},
+ ]
+
+ # Find semantically similar entities
+ semantic_matches = resolver.find_semantic_matches(entities)
+
+ print("Semantic Matches:")
+ for match in semantic_matches:
+ print(f" {match['entity1']['text']} ~ {match['entity2']['text']}")
+ print(f" Similarity: {match['similarity']:.3f}")
+
+ clusters = resolver.cluster_entities(
+ entities,
+ method="semantic",
+ min_cluster_size=2
+ )
+
+ print(f"Found {len(clusters)} semantic clusters")
+ ```
+
+=== "Graph Deduplication"
+ Deduplicate an entire knowledge graph:
+
+ ```python
+ from semantica.kg import Deduplicator, deduplicate_graph
+
+ # Method 1: Using convenience function
+ dedup_result = deduplicate_graph(kg, method="default")
+
+ # Method 2: Using Deduplicator class for more control
+ deduplicator = Deduplicator(
+ entity_similarity_threshold=0.85,
+ relationship_merge_strategy="union", # "union", "intersection", "first"
+ preserve_provenance=True
+ )
+
+ # Deduplicate the knowledge graph
+ dedup_result = deduplicator.deduplicate(kg)
+
+ print("Deduplication Results:")
+ print(f" Original entities: {dedup_result['original_entity_count']}")
+ print(f" After dedup: {dedup_result['final_entity_count']}")
+ print(f" Duplicates merged: {dedup_result['merged_count']}")
+ print(f" Reduction: {dedup_result['reduction_percent']:.1f}%")
+
+ # Get deduplicated graph
+ clean_kg = dedup_result['graph']
+
+ print("Merge Details:")
+ for merge in dedup_result['merges'][:5]:
+ print(f" Merged {len(merge['source_ids'])} entities -> {merge['canonical_id']}")
+ print(f" Canonical: {merge['canonical_text']}")
+ print(f" Aliases: {', '.join(merge['aliases'])}")
+ ```
+
+=== "Custom Matching Rules"
+ Define custom matching rules for your domain:
+
+ ```python
+ from semantica.kg import EntityResolver
+
+ # Define custom matching rules
+ custom_rules = {
+ "Organization": {
+ "normalize": [
+ ("Inc.", ""),
+ ("Corp.", ""),
+ ("Corporation", ""),
+ ("LLC", ""),
+ ("Ltd.", ""),
+ ],
+ "abbreviations": {
+ "IBM": "International Business Machines",
+ "GE": "General Electric",
+ "HP": "Hewlett-Packard",
+ },
+ "threshold": 0.8
+ },
+ "Person": {
+ "match_fields": ["name", "email"],
+ "normalize_case": True,
+ "threshold": 0.9
+ },
+ "Location": {
+ "normalize": [
+ ("St.", "Street"),
+ ("Ave.", "Avenue"),
+ ("Blvd.", "Boulevard"),
+ ],
+ "threshold": 0.85
+ }
+ }
+
+ resolver = EntityResolver(
+ strategy="rule_based",
+ custom_rules=custom_rules
+ )
+
+ # Apply custom rules
+ entities = [
+ {"id": "e1", "text": "Apple Inc.", "type": "Organization"},
+ {"id": "e2", "text": "Apple Corporation", "type": "Organization"},
+ {"id": "e3", "text": "International Business Machines", "type": "Organization"},
+ {"id": "e4", "text": "IBM", "type": "Organization"},
+ ]
+
+ matches = resolver.find_duplicates(entities)
+
+ print("Rule-Based Matches:")
+ for match in matches:
+ print(f" {match['entities'][0]['text']} = {match['entities'][1]['text']}")
+ print(f" Rule: {match['matched_rule']}")
+ ```
+
+=== "Merge Strategies"
+ Control how entities are merged:
+
+ ```python
+ from semantica.kg import EntityResolver
+
+ resolver = EntityResolver(strategy="fuzzy", similarity_threshold=0.85)
+
+ # Define merge strategy
+ merged_entity = resolver.merge_entities(
+ entities=[
+ {"id": "e1", "text": "Apple", "properties": {"founded": 1976}},
+ {"id": "e2", "text": "Apple Inc.", "properties": {"ceo": "Tim Cook"}},
+ {"id": "e3", "text": "Apple Computer", "properties": {"founded": 1976, "industry": "Tech"}}
+ ],
+ strategy={
+ "id": "keep_first", # Use first entity's ID
+ "text": "most_complete", # Use longest/most complete text
+ "properties": "merge_all", # Combine all properties
+ "conflicts": "keep_latest" # For conflicting values, keep latest
+ }
+ )
+
+ print("Merged Entity:")
+ print(f" ID: {merged_entity['id']}")
+ print(f" Text: {merged_entity['text']}")
+ print(f" Properties: {merged_entity['properties']}")
+ print(f" Source IDs: {merged_entity['source_ids']}")
+ ```
+
++=======
++>>>>>>> origin/main
**Related Modules**:
- [`deduplication` Module](../semantica/deduplication/deduplication_usage.md) - Deduplication and merging
- [`embeddings` Module](reference/embeddings.md) - Similarity calculation
@@@ -2291,208 -453,6 +2378,211 @@@ flowchart L
style Normalized fill:#c8e6c9
```
++<<<<<<< HEAD
+**Practical Examples**:
+
+=== "Text Normalization"
+ Clean and normalize text data:
+
+ ```python
+ from semantica.normalize import TextNormalizer
+
+ normalizer = TextNormalizer(
+ lowercase=True,
+ remove_punctuation=False,
+ remove_extra_whitespace=True,
+ unicode_normalize=True,
+ expand_contractions=True
+ )
+
+ # Normalize text
+ raw_texts = [
+ " Apple Inc. was founded in 1976!! ",
+ "The iPhone's really great, isn't it?",
+ "Microsoft™ announced Windows® 11",
+ "café, naïve, résumé — special chars"
+ ]
+
+ for raw in raw_texts:
+ normalized = normalizer.normalize(raw)
+ print(f"Before: {raw!r}")
+ print(f"After: {normalized!r}\n")
+
+ # Batch normalization
+ normalized_batch = normalizer.normalize_batch(raw_texts)
+ ```
+
+=== "Entity Normalization"
+ Standardize entity names and types:
+
+ ```python
+ from semantica.normalize import EntityNormalizer
+
+ normalizer = EntityNormalizer(
+ case_style="title", # "title", "upper", "lower", "preserve"
+ remove_suffixes=["Inc.", "Corp.", "LLC", "Ltd."],
+ remove_prefixes=["The"],
+ normalize_whitespace=True
+ )
+
+ # Normalize entity names
+ entities = [
+ {"text": " THE apple INC. ", "type": "Organization"},
+ {"text": "MICROSOFT CORPORATION", "type": "Organization"},
+ {"text": "tim cook", "type": "Person"},
+ {"text": " new york city ", "type": "Location"}
+ ]
+
+ normalized = normalizer.normalize_entities(entities)
+
+ print("Normalized Entities:")
+ for orig, norm in zip(entities, normalized):
+ print(f" {orig['text']!r} -> {norm['text']!r}")
+ ```
+
+=== "Date Normalization"
+ Parse and normalize date formats:
+
+ ```python
+ from semantica.normalize import DateNormalizer
+
+ normalizer = DateNormalizer(
+ output_format="ISO8601", # "ISO8601", "US", "EU", "unix"
+ infer_missing=True,
+ handle_relative=True
+ )
+
+ # Various date formats
+ dates = [
+ "January 15, 2024",
+ "15/01/2024",
+ "01-15-2024",
+ "2024-01-15",
+ "last Tuesday",
+ "3 days ago",
+ "Q1 2024",
+ "mid-2023",
+ ]
+
+ print("Date Normalization:")
+ for date_str in dates:
+ result = normalizer.normalize(date_str)
+ print(f" {date_str:20} -> {result['normalized']}")
+ if result.get('is_range'):
+ print(f" Range: {result['start']} to {result['end']}")
+ ```
+
+=== "Number Normalization"
+ Standardize numeric formats:
+
+ ```python
+ from semantica.normalize import NumberNormalizer
+
+ normalizer = NumberNormalizer(
+ output_format="numeric", # "numeric", "text", "scientific"
+ handle_currencies=True,
+ handle_percentages=True
+ )
+
+ # Various number formats
+ numbers = [
+ "1,234,567",
+ "one million",
+ "$3.5 billion",
+ "45%",
+ "1.5M",
+ "three hundred twenty-one",
+ "€50,000",
+ "12.5 percent"
+ ]
+
+ print("Number Normalization:")
+ for num_str in numbers:
+ result = normalizer.normalize(num_str)
+ print(f" {num_str:25} -> {result['value']:>15,.2f}")
+ if result.get('currency'):
+ print(f" Currency: {result['currency']}")
+ if result.get('is_percentage'):
+ print(f" Percentage: {result['decimal']:.4f}")
+ ```
+
+=== "Full Pipeline"
+ Run complete normalization pipeline:
+
+ ```python
+ from semantica.normalize import (
+ TextNormalizer,
+ EntityNormalizer,
+ DateNormalizer,
+ NumberNormalizer
+ )
+
+ # Initialize normalizers
+ text_norm = TextNormalizer(remove_extra_whitespace=True)
+ entity_norm = EntityNormalizer(case_style="title", remove_suffixes=["Inc.", "Corp."])
+ date_norm = DateNormalizer(output_format="ISO8601")
+ number_norm = NumberNormalizer(handle_currencies=True)
+
+ # Raw knowledge graph data
+ raw_kg = {
+ "entities": [
+ {"id": "e1", "text": " APPLE INC. ", "type": "Organization",
+ "properties": {"founded": "April 1, 1976", "revenue": "$394.3 billion"}},
+ {"id": "e2", "text": "tim cook", "type": "Person"},
+ ],
+ "relationships": [
+ {"source": "e2", "target": "e1", "type": "CEO_OF",
+ "properties": {"since": "August 24, 2011"}}
+ ]
+ }
+
+ # Normalize entities
+ normalized_entities = []
+ for entity in raw_kg['entities']:
+ norm_entity = entity.copy()
+
+ # Normalize text
+ norm_entity['text'] = text_norm.normalize(entity['text'])
+ norm_entity['text'] = entity_norm.normalize_entity_name(
+ norm_entity['text'],
+ entity_type=entity['type']
+ )
+
+ # Normalize properties
+ if 'properties' in entity:
+ props = entity['properties'].copy()
+ if 'founded' in props:
+ props['founded'] = date_norm.normalize(props['founded'])['normalized']
+ if 'revenue' in props:
+ props['revenue'] = number_norm.normalize(props['revenue'])
+ norm_entity['properties'] = props
+
+ normalized_entities.append(norm_entity)
+
+ # Normalize relationship properties
+ normalized_rels = []
+ for rel in raw_kg['relationships']:
+ norm_rel = rel.copy()
+ if 'properties' in rel and 'since' in rel['properties']:
+ norm_rel['properties']['since'] = date_norm.normalize(
+ rel['properties']['since']
+ )['normalized']
+ normalized_rels.append(norm_rel)
+
+ normalized_kg = {
+ "entities": normalized_entities,
+ "relationships": normalized_rels
+ }
+
+ print("Normalized Knowledge Graph:")
+ for entity in normalized_kg['entities']:
+ print(f" Entity: {entity['text']}")
+ for key, value in entity.get('properties', {}).items():
+ print(f" {key}: {value}")
+ ```
+
++=======
++>>>>>>> origin/main
**Related Modules**:
- [`normalize` Module](reference/normalize.md) - Data normalization
- [`parse` Module](reference/parse.md) - Document parsing
@@@ -2513,291 -473,41 +2603,329 @@@
| **Type Conflict** | Different entity types | "Apple: Company" vs "Apple: Product" |
| **Temporal Conflict** | Conflicting time information | "Active: 2020-2023" vs "Active: 2021-2024" |
++<<<<<<< HEAD
+**Practical Examples**:
+
+=== "Detecting Conflicts"
+ Find conflicts in your knowledge graph:
+
+ ```python
+ from semantica.kg import ConflictDetector
+ from semantica.conflicts import ConflictAnalyzer, detect_conflicts
+
+ # Sample knowledge graph with conflicts
+ kg = {
+ "entities": [
+ {
+ "id": "e1",
+ "text": "Apple Inc.",
+ "type": "Organization",
+ "properties": {"founded": "1976", "employees": "160000"},
+ "source": "wikipedia"
+ },
+ {
+ "id": "e2",
+ "text": "Apple Inc.",
+ "type": "Organization",
+ "properties": {"founded": "1977", "employees": "164000"},
+ "source": "bloomberg"
+ },
+ ],
+ "relationships": [
+ {"source": "p1", "target": "e1", "type": "CEO_OF",
+ "properties": {"since": "2011"}, "data_source": "sec_filing"},
+ {"source": "p2", "target": "e1", "type": "CEO_OF",
+ "properties": {"since": "2011"}, "data_source": "news"}
+ ]
+ }
+
+ # Method 1: Using convenience function
+ conflicts = detect_conflicts(
+ kg["entities"],
+ method="value",
+ property_name="founded"
+ )
+
+ # Method 2: Using ConflictDetector class
+ detector = ConflictDetector()
+ all_conflicts = detector.detect_value_conflicts(kg["entities"], "founded")
+
+ print(f"Found {len(all_conflicts)} conflicts:")
+ for conflict in all_conflicts:
+ print(f" Type: {conflict.conflict_type.value}")
+ print(f" Entity: {conflict.entity_id}")
+ print(f" Property: {conflict.property_name}")
+ print(f" Values: {[v['value'] for v in conflict.values]}")
+ print(f" Sources: {conflict.sources}")
+
+ # Analyze conflicts
+ analyzer = ConflictAnalyzer()
+ analysis = analyzer.analyze(all_conflicts)
+
+ print(f"Conflict Analysis:")
+ print(f" Total conflicts: {analysis['total_conflicts']}")
+ print(f" By type: {analysis['by_type']}")
+ print(f" By severity: {analysis['by_severity']}")
+ ```
+
+=== "Resolution Strategies"
+ Resolve conflicts using different strategies:
+
+ ```python
+ from semantica.conflicts import (
+ ConflictResolver,
+ ResolutionStrategy,
+ Conflict,
+ ConflictType
+ )
+
+ # Create sample conflicts
+ conflicts = [
+ Conflict(
+ conflict_id="c1",
+ entity_id="e1",
+ conflict_type=ConflictType.VALUE,
+ property_name="founded",
+ values=[
+ {"value": "1976", "source": "wikipedia", "confidence": 0.95},
+ {"value": "1976", "source": "sec_filing", "confidence": 0.99},
+ {"value": "1977", "source": "news_article", "confidence": 0.70}
+ ],
+ sources=["wikipedia", "sec_filing", "news_article"]
+ )
+ ]
+
+ # Strategy 1: Voting (most common value wins)
+ resolver_voting = ConflictResolver(strategy=ResolutionStrategy.VOTING)
+ resolved_voting = resolver_voting.resolve(conflicts)
+
+ print("Voting Resolution:")
+ for r in resolved_voting:
+ print(f" {r.property_name}: {r.resolved_value}")
+
+ # Strategy 2: Highest confidence
+ resolver_conf = ConflictResolver(strategy=ResolutionStrategy.HIGHEST_CONFIDENCE)
+ resolved_conf = resolver_conf.resolve(conflicts)
+
+ print("Highest Confidence Resolution:")
+ for r in resolved_conf:
+ print(f" {r.property_name}: {r.resolved_value} (confidence: {r.confidence:.2f})")
+
+ # Strategy 3: Source priority
+ resolver_priority = ConflictResolver(
+ strategy=ResolutionStrategy.SOURCE_PRIORITY,
+ source_priority=["sec_filing", "wikipedia", "news_article"]
+ )
+ resolved_priority = resolver_priority.resolve(conflicts)
+
+ print("Source Priority Resolution:")
+ for r in resolved_priority:
+ print(f" {r.property_name}: {r.resolved_value} (source: {r.selected_source})")
+ ```
+
+=== "Custom Resolution Rules"
+ Define custom resolution rules per property:
+
+ ```python
+ from semantica.conflicts import (
+ ConflictResolver,
+ ResolutionStrategy,
+ resolve_conflicts
+ )
+
+ # Define property-specific resolution rules
+ resolution_config = {
+ "founded": {
+ "strategy": ResolutionStrategy.SOURCE_PRIORITY,
+ "source_priority": ["official_records", "sec_filing", "wikipedia"]
+ },
+ "revenue": {
+ "strategy": ResolutionStrategy.MOST_RECENT,
+ },
+ "employees": {
+ "strategy": ResolutionStrategy.VOTING,
+ },
+ "ceo": {
+ "strategy": ResolutionStrategy.HIGHEST_CONFIDENCE,
+ }
+ }
+
+ # Create resolver with custom config
+ resolver = ConflictResolver(
+ strategy=ResolutionStrategy.HIGHEST_CONFIDENCE,
+ min_confidence=0.7
+ )
+
+ # Resolve conflicts for each property
+ resolved_values = {}
+ for property_name, config in resolution_config.items():
+ property_resolver = ConflictResolver(
+ strategy=config["strategy"],
+ source_priority=config.get("source_priority")
+ )
+
+ # Get conflicts for this property
+ property_conflicts = [c for c in conflicts if c.property_name == property_name]
+
+ if property_conflicts:
+ results = property_resolver.resolve(property_conflicts)
+ for result in results:
+ resolved_values[property_name] = {
+ "value": result.resolved_value,
+ "strategy": config["strategy"].value,
+ "confidence": result.confidence
+ }
+
+ print("Resolved Values:")
+ for prop, info in resolved_values.items():
+ print(f" {prop}: {info['value']} (via {info['strategy']})")
+ ```
+
+=== "Source Tracking"
+ Track the origin of resolved values:
+
+ ```python
+ from semantica.conflicts import SourceTracker, SourceReference
+
+ # Initialize source tracker
+ tracker = SourceTracker()
+
+ # Add entities from different sources
+ tracker.add_source(SourceReference(
+ entity_id="e1",
+ property_name="founded",
+ value="1976",
+ source="wikipedia",
+ timestamp="2024-01-15",
+ confidence=0.95
+ ))
+
+ tracker.add_source(SourceReference(
+ entity_id="e1",
+ property_name="founded",
+ value="1976",
+ source="sec_filing",
+ timestamp="2024-03-01",
+ confidence=0.99
+ ))
+
+ tracker.add_source(SourceReference(
+ entity_id="e1",
+ property_name="founded",
+ value="1977",
+ source="news_article",
+ timestamp="2024-02-20",
+ confidence=0.70
+ ))
+
+ # Get all sources for an entity
+ sources = tracker.get_sources("e1")
+
+ print("Entity Sources:")
+ for source in sources:
+ print(f" Source: {source.source}")
+ print(f" Property: {source.property_name}")
+ print(f" Value: {source.value}")
+ print(f" Confidence: {source.confidence}")
+
+ # Get property-specific sources
+ property_sources = tracker.get_property_sources("e1", "founded")
+
+ print("Property Sources for 'founded':")
+ for ps in property_sources:
+ print(f" {ps.value} from {ps.source} ({ps.timestamp})")
+ ```
+
+=== "Conflict Investigation"
+ Deep dive into specific conflicts:
+
+ ```python
+ from semantica.conflicts import (
+ InvestigationGuideGenerator,
+ ConflictDetector,
+ Conflict,
+ ConflictType
+ )
+
+ # Initialize investigation guide generator
+ guide_generator = InvestigationGuideGenerator()
+
+ # Create a conflict object
+ conflict = Conflict(
+ conflict_id="c1",
+ entity_id="e1",
+ conflict_type=ConflictType.VALUE,
+ property_name="founded",
+ values=[
+ {"value": "1976", "source": "wikipedia", "confidence": 0.95},
+ {"value": "1977", "source": "news", "confidence": 0.70}
+ ],
+ sources=["wikipedia", "news"],
+ severity=0.6
+ )
+
+ # Generate investigation guide
+ guide = guide_generator.generate_guide(conflict)
+
+ print("Conflict Investigation Guide:")
+ print(f" Conflict ID: {guide.conflict_id}")
+ print(f" Title: {guide.title}")
+ print(f" Summary: {guide.summary}")
+
+ print("Investigation Steps:")
+ for i, step in enumerate(guide.steps, 1):
+ print(f" {i}. {step.description}")
+ print(f" Priority: {step.priority}")
+ if step.expected_outcome:
+ print(f" Expected: {step.expected_outcome}")
+
+ print("Checklist:")
+ for item in guide.checklist:
+ print(f" [ ] {item}")
+
+ # Get context for the conflict
+ context = guide_generator.get_conflict_context(conflict)
+ print(f"Context:")
+ print(f" Entity: {context.get('entity_text', 'Unknown')}")
+ print(f" Property: {context.get('property', 'Unknown')}")
+ print(f" Value count: {len(conflict.values)}")
++=======
+ **Conflict Resolution Strategies**:
+
+ === "Voting"
+ Use the most common value across sources.
+
+ ```python
+ resolver = ConflictResolver(strategy="voting")
+ resolved = resolver.resolve(conflicts)
+ ```
+
+ === "Highest Confidence"
+ Use the value with the highest confidence score.
+
+ ```python
+ resolver = ConflictResolver(strategy="highest_confidence")
+ resolved = resolver.resolve(conflicts)
+ ```
+
+ === "Most Recent"
+ Use the most recently updated value.
+
+ ```python
+ resolver = ConflictResolver(strategy="most_recent")
+ resolved = resolver.resolve(conflicts)
+ ```
+
+ === "Source Priority"
+ Use values from trusted sources first.
+
+ ```python
+ resolver = ConflictResolver(
+ strategy="source_priority",
+ source_priority=["trusted_source", "other_source"]
+ )
+ resolved = resolver.resolve(conflicts)
++>>>>>>> origin/main
```
**Related Modules**:
diff --cc docs/reference/embeddings.md
index e1665ec3,47e638b6..8de2b32e
--- a/docs/reference/embeddings.md
+++ b/docs/reference/embeddings.md
@@@ -131,15 -131,13 +131,25 @@@ Optimizes vectors
## Convenience Functions
```python
++<<<<<<< HEAD
+from semantica.embeddings import EmbeddingGenerator, embed_text, calculate_similarity
+
+# Generate embeddings
+generator = EmbeddingGenerator()
+emb1 = generator.generate_embeddings("text1", data_type="text")
+emb2 = generator.generate_embeddings("text2", data_type="text")
+
+# Similarity
+score = calculate_similarity(emb1, emb2)
++=======
+ from semantica.embeddings import build, embed_text, calculate_similarity
+
+ # One-line generation
+ result = build(["text1", "text2"])
+
+ # Similarity
+ score = calculate_similarity(vec1, vec2)
++>>>>>>> origin/main
```
---
diff --cc docs/reference/kg.md
index 7f6e662d,5d00970c..be9a7fb2
--- a/docs/reference/kg.md
+++ b/docs/reference/kg.md
@@@ -121,11 -121,10 +121,18 @@@ Queries time-aware graphs
## Convenience Functions
```python
++<<<<<<< HEAD
+from semantica.kg import GraphBuilder, analyze_graph
+
+# Build using GraphBuilder
+builder = GraphBuilder(resolve_conflicts=True)
+kg = builder.build(sources)
++=======
+ from semantica.kg import build, analyze_graph
+
+ # Build
+ kg = build(sources, resolve_conflicts=True)
++>>>>>>> origin/main
# Analyze
stats = analyze_graph(kg)
diff --cc docs/reference/semantic_extract.md
index ed1a51fe,e99cf05b..9295f107
--- a/docs/reference/semantic_extract.md
+++ b/docs/reference/semantic_extract.md
@@@ -83,15 -83,6 +83,18 @@@
### NamedEntityRecognizer
Coordinator for entity extraction.
++<<<<<<< HEAD
+
+**Parameters:**
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `methods` | list | `["spacy"]` | Extraction methods to use |
+| `confidence_threshold` | float | `0.5` | Minimum confidence score |
+| `merge_overlapping` | bool | `True` | Merge overlapping entities |
+| `include_standard_types` | bool | `True` | Include Person, Org, Location |
++=======
++>>>>>>> origin/main
**Methods:**
@@@ -105,32 -96,14 +108,41 @@@
```python
from semantica.semantic_extract import NamedEntityRecognizer
++<<<<<<< HEAD
+# Basic usage
ner = NamedEntityRecognizer()
entities = ner.extract_entities("Elon Musk leads SpaceX.")
# [Entity(text="Elon Musk", label="PERSON"), Entity(text="SpaceX", label="ORG")]
+
+# With configuration
+ner = NamedEntityRecognizer(
+ methods=["spacy", "rule-based"],
+ confidence_threshold=0.7,
+ merge_overlapping=True
+)
+entities = ner.extract_entities("Apple Inc. was founded in 1976.")
++=======
++ner = NamedEntityRecognizer()
++entities = ner.extract_entities("Elon Musk leads SpaceX.")
++# [Entity(text="Elon Musk", label="PERSON"), Entity(text="SpaceX", label="ORG")]
++>>>>>>> origin/main
```
### RelationExtractor
Extracts relationships between entities.
++<<<<<<< HEAD
+
+**Parameters:**
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `relation_types` | list | `None` | Specific relation types to extract |
+| `bidirectional` | bool | `False` | Extract bidirectional relations |
+| `confidence_threshold` | float | `0.6` | Minimum confidence score |
+| `max_distance` | int | `50` | Max token distance between entities |
++=======
++>>>>>>> origin/main
**Methods:**
@@@ -141,39 -114,16 +153,49 @@@
**Example:**
```python
-from semantica.semantic_extract import RelationExtractor
+from semantica.semantic_extract import RelationExtractor, NamedEntityRecognizer
++<<<<<<< HEAD
+# First extract entities
+ner = NamedEntityRecognizer()
+text = "Elon Musk founded SpaceX in 2002."
+entities = ner.extract_entities(text)
+
+# Basic relation extraction
+rel_extractor = RelationExtractor()
+relations = rel_extractor.extract_relations(text, entities=entities)
+# [Relation(source="Elon Musk", target="SpaceX", type="founded")]
+
+# With configuration
+rel_extractor = RelationExtractor(
+ relation_types=["founded", "leads", "works_at"],
+ confidence_threshold=0.7,
+ bidirectional=False
+)
+relations = rel_extractor.extract_relations(text, entities=entities)
++=======
+ re = RelationExtractor()
+ relations = re.extract_relations(text, entities)
+ # [Relation(source="Elon Musk", target="SpaceX", type="leads")]
++>>>>>>> origin/main
```
### EventDetector
++<<<<<<< HEAD
+Identifies events with temporal information and participants.
+
+**Parameters:**
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `event_types` | list | `None` | Specific event types to detect |
+| `extract_participants` | bool | `True` | Extract event participants |
+| `extract_location` | bool | `True` | Extract event locations |
+| `extract_time` | bool | `True` | Extract temporal information |
++=======
+ Identifies events.
++>>>>>>> origin/main
**Methods:**
@@@ -181,88 -131,32 +203,111 @@@
|--------|-------------|
| `detect_events(text)` | Find events |
++<<<<<<< HEAD
+**Example:**
+
+```python
+from semantica.semantic_extract import EventDetector
+
+detector = EventDetector(
+ event_types=["launch", "acquisition", "announcement"],
+ extract_participants=True,
+ extract_time=True
+)
+events = detector.detect_events("SpaceX launched Starship on March 14, 2024.")
+```
+
+### TripleExtractor
+
+Extracts RDF triples (Subject-Predicate-Object).
+
+**Parameters:**
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `include_temporal` | bool | `False` | Include time information |
+| `include_provenance` | bool | `False` | Track source sentences |
++=======
+ ### TripleExtractor
+
+ Extracts RDF triples.
++>>>>>>> origin/main
**Methods:**
| Method | Description |
|--------|-------------|
| `extract_triples(text)` | Get (S, P, O) tuples |
++<<<<<<< HEAD
+
+**Example:**
+
+```python
+from semantica.semantic_extract import TripleExtractor
+
+extractor = TripleExtractor(
+ include_temporal=True,
+ include_provenance=True
+)
+triples = extractor.extract_triples("Steve Jobs founded Apple in 1976.")
+# [Triple(subject="Steve Jobs", predicate="founded", object="Apple", temporal="1976")]
+```
++=======
++>>>>>>> origin/main
---
## Convenience Functions
```python
++<<<<<<< HEAD
+from semantica.semantic_extract import (
+ NamedEntityRecognizer,
+ RelationExtractor,
+ TripleExtractor,
+ EventDetector,
+ CoreferenceResolver
+)
+
+text = "Apple released the iPhone in 2007. Steve Jobs announced it at Macworld."
+
+# Extract entities with confidence filtering
+ner = NamedEntityRecognizer(confidence_threshold=0.7)
+entities = ner.extract_entities(text)
+
+# Resolve coreferences (recommended before relation extraction)
+coref = CoreferenceResolver()
+resolved = coref.resolve(text)
+
+# Extract relations
+rel_extractor = RelationExtractor(confidence_threshold=0.6)
+relations = rel_extractor.extract_relations(text, entities=entities)
+
+# Extract triples for KG
+triple_extractor = TripleExtractor(include_temporal=True)
+triples = triple_extractor.extract_triples(text)
+
+# Detect events
+event_detector = EventDetector(extract_time=True)
+events = event_detector.detect_events(text)
+
+print(f"Entities: {len(entities)}")
+print(f"Relations: {len(relations)}")
+print(f"Triples: {len(triples)}")
+print(f"Events: {len(events)}")
++=======
+ from semantica.semantic_extract import build
+
+ # All-in-one extraction
+ result = build(
+ "Apple released the iPhone in 2007.",
+ extract_entities=True,
+ extract_relations=True,
+ extract_events=True
+ )
+
+ print(result['triples'])
++>>>>>>> origin/main
```
---
@@@ -299,23 -193,21 +344,41 @@@ semantic_extract
### KG Population Pipeline
```python
++<<<<<<< HEAD
+from semantica.semantic_extract import NamedEntityRecognizer, RelationExtractor, TripleExtractor
+from semantica.kg import GraphBuilder
+
+# 1. Extract
+text = "Google was founded by Larry Page and Sergey Brin."
+ner = NamedEntityRecognizer()
+entities = ner.extract_entities(text)
+triple_extractor = TripleExtractor()
+triples = triple_extractor.extract_triples(text)
+
+# 2. Populate KG using GraphBuilder
+builder = GraphBuilder()
+sources = [{
+ "entities": entities,
+ "relationships": [{"source": t.subject, "target": t.object, "type": t.predicate} for t in triples]
+}]
+kg = builder.build(sources)
++=======
+ from semantica.semantic_extract import build
+ from semantica.kg import KnowledgeGraph
+
+ # 1. Extract
+ text = "Google was founded by Larry Page and Sergey Brin."
+ data = build(text, extract_triples=True)
+
+ # 2. Populate KG
+ kg = KnowledgeGraph()
+ for triple in data['triples']:
+ kg.add_triple(
+ subject=triple.subject,
+ predicate=triple.predicate,
+ object=triple.object
+ )
++>>>>>>> origin/main
```
---
diff --cc semantica/__init__.py
index c7cf9449,618a44ac..15d5292d
--- a/semantica/__init__.py
+++ b/semantica/__init__.py
@@@ -216,6 -217,64 +216,67 @@@ class _SemanticaModules
# Create singleton instance for module access
_modules = _SemanticaModules()
++<<<<<<< HEAD
++=======
+ # Singleton Semantica instance for module-level build()
+ _semantica_instance: Optional[Semantica] = None
+
+
+ def _get_semantica_instance(
+ config: Optional[Union[Config, Dict[str, Any]]] = None, **kwargs
+ ) -> Semantica:
+ """Get or create singleton Semantica instance."""
+ global _semantica_instance
+ if _semantica_instance is None:
+ _semantica_instance = Semantica(config=config, **kwargs)
+ return _semantica_instance
+
+
+ def build(
+ sources: Union[List[Union[str, Path]], str, Path],
+ config: Optional[Union[Config, Dict[str, Any]]] = None,
+ **kwargs,
+ ) -> Dict[str, Any]:
+ """
+ Build knowledge base from data sources (module-level convenience function).
+
+ This is a user-friendly wrapper around Semantica.build_knowledge_base()
+ that handles initialization automatically.
+
+ Args:
+ sources: Data source(s) - can be a single path/URL or list of paths/URLs
+ config: Optional configuration object or dict
+ **kwargs: Additional processing options:
+ - embeddings: Whether to generate embeddings (default: True)
+ - graph: Whether to build knowledge graph (default: True)
+ - normalize: Whether to normalize data (default: True)
+ - pipeline: Custom pipeline configuration
+ - fail_fast: Whether to fail on first error (default: False)
+
+ Returns:
+ Dictionary containing:
+ - knowledge_graph: Knowledge graph data
+ - embeddings: Embedding vectors
+ - metadata: Processing metadata
+ - statistics: Processing statistics
+ - results: Processing results
+
+ Examples:
+ >>> from semantica import build
+ >>> result = build(["doc1.pdf", "doc2.docx"], embeddings=True, graph=True)
+ >>> print(result["statistics"])
+ """
+ # Normalize sources to list
+ if isinstance(sources, (str, Path)):
+ sources = [sources]
+
+ # Get or create Semantica instance
+ semantica = _get_semantica_instance(config=config, **kwargs)
+
+ # Build knowledge base (auto-initializes if needed)
+ return semantica.build_knowledge_base(sources, **kwargs)
++>>>>>>> origin/main
+
__all__ = [
# Core
diff --cc semantica/core/__init__.py
index 25cdf9b2,b89c9c4d..b4a63210
--- a/semantica/core/__init__.py
+++ b/semantica/core/__init__.py
@@@ -86,4 -90,72 +86,76 @@@ __all__ =
"get_status",
"get_orchestration_method",
"list_available_methods",
++<<<<<<< HEAD
+]
++=======
+ # Convenience
+ "build",
+ ]
+
+
+ def build(
+ sources: Union[str, List[Union[str, Path]]],
+ extract_entities: bool = True,
+ extract_relations: bool = True,
+ embeddings: bool = True,
+ graph: bool = True,
+ **options,
+ ) -> Dict[str, Any]:
+ """
+ Build knowledge base from sources (module-level convenience function).
+
+ This is a user-friendly wrapper that performs comprehensive knowledge base
+ construction including entity extraction, relation extraction, embeddings,
+ and knowledge graph building.
+
+ Args:
+ sources: Input source or list of sources (files, URLs, streams)
+ extract_entities: Whether to extract named entities (default: True)
+ extract_relations: Whether to extract relationships (default: True)
+ embeddings: Whether to generate embeddings (default: True)
+ graph: Whether to build knowledge graph (default: True)
+ **options: Additional processing options
+
+ Returns:
+ Dictionary containing:
+ - knowledge_graph: Knowledge graph data
+ - embeddings: Embedding vectors
+ - results: Processing results
+ - statistics: Processing statistics
+ - metadata: Processing metadata
+
+ Examples:
+ >>> import semantica
+ >>> result = semantica.core.build(
+ ... sources=["doc1.pdf", "doc2.docx"],
+ ... extract_entities=True,
+ ... extract_relations=True,
+ ... embeddings=True,
+ ... graph=True
+ ... )
+ >>> print(f"Processed {result['statistics']['sources_processed']} sources")
+ """
+ # Normalize sources to list
+ if isinstance(sources, str):
+ sources = [sources]
+
+ # Build pipeline configuration from options
+ pipeline_config = options.get("pipeline", {})
+ if extract_entities or extract_relations:
+ pipeline_config.setdefault("extract", {})
+ if extract_entities:
+ pipeline_config["extract"]["entities"] = True
+ if extract_relations:
+ pipeline_config["extract"]["relations"] = True
+
+ # Build knowledge base
+ return build_knowledge_base(
+ sources=sources,
+ method=options.get("method", "default"),
+ embeddings=embeddings,
+ graph=graph,
+ pipeline=pipeline_config,
+ **{k: v for k, v in options.items() if k not in ["pipeline", "method"]},
+ )
++>>>>>>> origin/main
diff --cc semantica/embeddings/__init__.py
index d72544e7,b62a32a7..7414fea4
--- a/semantica/embeddings/__init__.py
+++ b/semantica/embeddings/__init__.py
@@@ -188,4 -188,92 +188,93 @@@ __all__ =
# Configuration
"EmbeddingsConfig",
"embeddings_config",
- # Convenience Functions
- "build",
]
++<<<<<<< HEAD
++=======
+
+
+ def build(
+ data: Union[str, Path, List[Union[str, Path]]],
+ data_type: Optional[str] = None,
+ model: Optional[str] = None,
+ batch_size: int = 32,
+ **options,
+ ) -> Dict[str, Any]:
+ """
+ Generate embeddings from data (module-level convenience function).
+
+ This is a user-friendly wrapper around EmbeddingGenerator.generate_embeddings()
+ that creates an EmbeddingGenerator instance and generates embeddings.
+
+ Args:
+ data: Input data - can be text string, file path, or list of texts/paths
+ data_type: Data type - "text", "image", "audio" (auto-detected if None)
+ model: Embedding model to use (default: None, uses default model)
+ batch_size: Batch size for processing multiple items (default: 32)
+ **options: Additional generation options
+
+ Returns:
+ Dictionary containing:
+ - embeddings: Generated embeddings (numpy array or list of arrays)
+ - metadata: Embedding metadata
+ - statistics: Generation statistics
+
+ Examples:
+ >>> import semantica
+ >>> result = semantica.embeddings.build(
+ ... data=["text1", "text2", "text3"],
+ ... data_type="text",
+ ... model="sentence-transformers"
+ ... )
+ >>> print(f"Generated {len(result['embeddings'])} embeddings")
+ """
+ # Create EmbeddingGenerator instance
+ config = {}
+ if model:
+ config["model"] = model
+ config.update(options)
+
+ generator = EmbeddingGenerator(config=config, **options)
+
+ # Normalize data to list if single item
+ is_single = not isinstance(data, list)
+ if is_single:
+ data = [data]
+
+ # Generate embeddings
+ if len(data) == 1:
+ # Single item
+ embeddings = generator.generate_embeddings(
+ data[0], data_type=data_type, **options
+ )
+ if is_single:
+ # Return single embedding array
+ return {
+ "embeddings": embeddings,
+ "metadata": {
+ "data_type": data_type or generator._detect_data_type(data[0]),
+ "model": model or "default",
+ "shape": embeddings.shape
+ if isinstance(embeddings, np.ndarray)
+ else None,
+ },
+ "statistics": {"total_items": 1, "successful": 1, "failed": 0},
+ }
+ else:
+ # Batch processing
+ results = generator.process_batch(data, **options)
+ return {
+ "embeddings": results["embeddings"],
+ "metadata": {
+ "data_type": data_type or "auto-detected",
+ "model": model or "default",
+ "batch_size": batch_size,
+ },
+ "statistics": {
+ "total_items": results["total"],
+ "successful": results["success_count"],
+ "failed": results["failure_count"],
+ },
+ "failed_items": results.get("failed", []),
+ }
++>>>>>>> origin/main
diff --cc semantica/ingest/__init__.py
index 9f135c72,3a8f75b0..91e6e061
--- a/semantica/ingest/__init__.py
+++ b/semantica/ingest/__init__.py
@@@ -233,4 -233,116 +233,117 @@@ __all__ =
# Configuration
"IngestConfig",
"ingest_config",
- # Legacy
- "build",
]
++<<<<<<< HEAD
++=======
+
+
+ def build(
+ sources: Union[List[Union[str, Path]], str, Path],
+ source_type: str = "file",
+ recursive: bool = True,
+ read_content: bool = True,
+ **options,
+ ) -> Dict[str, Any]:
+ """
+ Ingest data from sources (module-level convenience function).
+
+ This is a user-friendly wrapper that automatically selects the appropriate
+ ingestor based on source type and ingests the data.
+
+ Args:
+ sources: Data source(s) - can be file paths, URLs, directories, etc.
+ source_type: Type of source - "file", "web", "feed", "stream", "repo", "email", "db" (default: "file")
+ recursive: For directories, whether to ingest recursively (default: True)
+ read_content: Whether to read file content (default: True)
+ **options: Additional ingestion options
+
+ Returns:
+ Dictionary containing:
+ - files: List of ingested file objects (for file ingestion)
+ - content: Ingested content (for web/feed ingestion)
+ - metadata: Ingestion metadata
+ - statistics: Ingestion statistics
+
+ Examples:
+ >>> import semantica
+ >>> result = semantica.ingest.build(
+ ... sources=["doc1.pdf", "doc2.docx"],
+ ... source_type="file",
+ ... read_content=True
+ ... )
+ >>> print(f"Ingested {len(result['files'])} files")
+ """
+ # Normalize sources to list
+ if isinstance(sources, (str, Path)):
+ sources = [sources]
+
+ results = {"files": [], "content": [], "metadata": {}, "statistics": {}}
+
+ if source_type == "file":
+ # Use FileIngestor
+ ingestor = FileIngestor(config=options.get("config", {}), **options)
+
+ file_objects = []
+ for source in sources:
+ source_path = Path(source)
+ if source_path.is_dir():
+ # Ingest directory
+ files = ingestor.ingest_directory(
+ source_path, recursive=recursive, **options
+ )
+ file_objects.extend(files)
+ elif source_path.is_file():
+ # Ingest single file
+ file_obj = ingestor.ingest_file(
+ source_path, read_content=read_content, **options
+ )
+ file_objects.append(file_obj)
+ else:
+ # Try as file path string
+ try:
+ file_obj = ingestor.ingest_file(
+ source, read_content=read_content, **options
+ )
+ file_objects.append(file_obj)
+ except Exception as e:
+ results["statistics"].setdefault("errors", []).append(
+ {"source": str(source), "error": str(e)}
+ )
+
+ results["files"] = file_objects
+ results["statistics"] = {
+ "total_sources": len(sources),
+ "ingested_files": len(file_objects),
+ "errors": len(results["statistics"].get("errors", [])),
+ }
+
+ elif source_type == "web":
+ # Use WebIngestor
+ from .web_ingestor import WebIngestor
+
+ ingestor = WebIngestor(config=options.get("config", {}), **options)
+
+ web_contents = []
+ for source in sources:
+ if isinstance(source, str) and (
+ source.startswith("http://") or source.startswith("https://")
+ ):
+ content = ingestor.ingest_url(source, **options)
+ web_contents.append(content)
+
+ results["content"] = web_contents
+ results["statistics"] = {
+ "total_urls": len(sources),
+ "ingested_pages": len(web_contents),
+ }
+
+ else:
+ # For other types, return placeholder
+ results["statistics"] = {
+ "message": f"Source type '{source_type}' ingestion not yet implemented in build() function",
+ "suggestion": f"Use {source_type.capitalize()}Ingestor class directly",
+ }
+
+ return results
++>>>>>>> origin/main
diff --cc semantica/kg/__init__.py
index f04622e5,15697790..0664505b
--- a/semantica/kg/__init__.py
+++ b/semantica/kg/__init__.py
@@@ -207,4 -207,73 +207,74 @@@ __all__ =
# Configuration
"KGConfig",
"kg_config",
- # Convenience Functions
- "build",
]
++<<<<<<< HEAD
++=======
+
+
+ def build(
+ sources: Union[List[Any], Any],
+ merge_entities: bool = True,
+ entity_resolution_strategy: str = "fuzzy",
+ resolve_conflicts: bool = True,
+ enable_temporal: bool = False,
+ temporal_granularity: str = "day",
+ track_history: bool = False,
+ version_snapshots: bool = False,
+ entity_resolver: Optional[EntityResolver] = None,
+ **options,
+ ) -> Dict[str, Any]:
+ """
+ Build knowledge graph from sources (module-level convenience function).
+
+ This is a user-friendly wrapper around GraphBuilder.build() that creates
+ a GraphBuilder instance and builds the knowledge graph.
+
+ Args:
+ sources: List of sources (documents, entities, relationships, or dicts with entities/relationships)
+ merge_entities: Whether to merge duplicate entities (default: True)
+ entity_resolution_strategy: Strategy for entity resolution - "fuzzy", "exact", "semantic" (default: "fuzzy")
+ resolve_conflicts: Whether to resolve conflicts (default: True)
+ enable_temporal: Enable temporal knowledge graph features (default: False)
+ temporal_granularity: Time granularity - "second", "minute", "hour", "day", etc. (default: "day")
+ track_history: Track historical changes (default: False)
+ version_snapshots: Create version snapshots (default: False)
+ entity_resolver: Optional EntityResolver instance (default: None, creates one if needed)
+ **options: Additional build options
+
+ Returns:
+ Dictionary containing:
+ - entities: List of entities
+ - relationships: List of relationships
+ - metadata: Graph metadata including counts and timestamps
+
+ Examples:
+ >>> import semantica
+ >>> result = semantica.kg.build(
+ ... sources=[{"entities": [...], "relationships": [...]}],
+ ... merge_entities=True,
+ ... resolve_conflicts=True
+ ... )
+ >>> print(f"Built graph with {result['metadata']['num_entities']} entities")
+ """
+ # Normalize sources to list
+ if not isinstance(sources, list):
+ sources = [sources]
+
+ # Create GraphBuilder instance
+ graph_builder = GraphBuilder(
+ merge_entities=merge_entities,
+ entity_resolution_strategy=entity_resolution_strategy,
+ resolve_conflicts=resolve_conflicts,
+ enable_temporal=enable_temporal,
+ temporal_granularity=temporal_granularity,
+ track_history=track_history,
+ version_snapshots=version_snapshots,
+ **options,
+ )
+
+ # Build knowledge graph
+ graph = graph_builder.build(sources, entity_resolver=entity_resolver, **options)
+
+ return graph
++>>>>>>> origin/main
diff --cc semantica/semantic_extract/__init__.py
index bff092f8,a8d3850f..44a4c534
--- a/semantica/semantic_extract/__init__.py
+++ b/semantica/semantic_extract/__init__.py
@@@ -183,4 -178,154 +183,158 @@@ __all__ =
"get_entity_method",
"get_relation_method",
"get_triple_method",
++<<<<<<< HEAD
+]
++=======
+ # Convenience
+ "build",
+ ]
+
+
+ def build(
+ text: Union[str, List[str]],
+ extract_entities: bool = True,
+ extract_relations: bool = True,
+ extract_events: bool = False,
+ extract_triples: bool = False,
+ resolve_coreferences: bool = False,
+ **options,
+ ) -> Dict[str, Any]:
+ """
+ Extract semantic information from text (module-level convenience function).
+
+ This is a user-friendly wrapper that performs comprehensive semantic extraction
+ including entities, relations, events, and triples.
+
+ Args:
+ text: Input text or list of texts to process
+ extract_entities: Whether to extract named entities (default: True)
+ extract_relations: Whether to extract relationships (default: True)
+ extract_events: Whether to extract events (default: False)
+ extract_triples: Whether to extract RDF triples (default: False)
+ resolve_coreferences: Whether to resolve coreferences (default: False)
+ **options: Additional extraction options
+
+ Returns:
+ Dictionary containing:
+ - entities: List of extracted entities
+ - relations: List of extracted relationships
+ - events: List of extracted events (if enabled)
+ - triples: List of extracted triples (if enabled)
+ - coreferences: Coreference resolution results (if enabled)
+ - metadata: Extraction metadata
+ - statistics: Extraction statistics
+
+ Examples:
+ >>> import semantica
+ >>> result = semantica.semantic_extract.build(
+ ... text="Apple Inc. was founded by Steve Jobs in 1976.",
+ ... extract_entities=True,
+ ... extract_relations=True
+ ... )
+ >>> print(f"Extracted {len(result['entities'])} entities")
+ """
+ # Normalize text to list
+ is_single = isinstance(text, str)
+ if is_single:
+ texts = [text]
+ else:
+ texts = text
+
+ results = {
+ "entities": [],
+ "relations": [],
+ "events": [],
+ "triples": [],
+ "coreferences": [],
+ "metadata": {},
+ "statistics": {},
+ }
+
+ # Initialize extractors
+ if extract_entities:
+ ner = NamedEntityRecognizer(config=options.get("ner_config", {}), **options)
+
+ if extract_relations:
+ from .relation_extractor import RelationExtractor
+
+ rel_extractor = RelationExtractor(
+ **options.get("relation_config", {}), **options
+ )
+
+ if extract_events:
+ from .event_detector import EventDetector
+
+ event_detector = EventDetector(**options.get("event_config", {}), **options)
+
+ if extract_triples:
+ from .triple_extractor import TripleExtractor
+
+ triple_extractor = TripleExtractor(
+ **options.get("triple_config", {}), **options
+ )
+
+ if resolve_coreferences:
+ from .coreference_resolver import CoreferenceResolver
+
+ coref_resolver = CoreferenceResolver(
+ **options.get("coref_config", {}), **options
+ )
+
+ # Process texts
+ all_entities = []
+ all_relations = []
+ all_events = []
+ all_triples = []
+
+ for txt in texts:
+ if extract_entities:
+ entities = ner.extract_entities(txt, **options)
+ all_entities.extend(entities)
+
+ if extract_relations:
+ # Relations typically need entities, so extract if not already done
+ if not extract_entities:
+ entities = (
+ ner.extract_entities(txt, **options) if "ner" in locals() else []
+ )
+ relations = rel_extractor.extract_relations(
+ txt, entities=entities if extract_entities else [], **options
+ )
+ all_relations.extend(relations)
+
+ if extract_events:
+ events = event_detector.detect_events(txt, **options)
+ all_events.extend(events)
+
+ if extract_triples:
+ triples = triple_extractor.extract_triples(txt, **options)
+ all_triples.extend(triples)
+
+ if resolve_coreferences:
+ corefs = coref_resolver.resolve(txt, **options)
+ results["coreferences"].append(corefs)
+
+ results["entities"] = all_entities
+ results["relations"] = all_relations
+ results["events"] = all_events
+ results["triples"] = all_triples
+
+ results["statistics"] = {
+ "texts_processed": len(texts),
+ "entities_extracted": len(all_entities),
+ "relations_extracted": len(all_relations),
+ "events_extracted": len(all_events),
+ "triples_extracted": len(all_triples),
+ }
+
+ results["metadata"] = {
+ "extract_entities": extract_entities,
+ "extract_relations": extract_relations,
+ "extract_events": extract_events,
+ "extract_triples": extract_triples,
+ "resolve_coreferences": resolve_coreferences,
+ }
+
+ return results
++>>>>>>> origin/main
diff --cc semantica/semantic_extract/coreference_resolver.py
index b49e660b,5d0e6bcd..1541a7a8
--- a/semantica/semantic_extract/coreference_resolver.py
+++ b/semantica/semantic_extract/coreference_resolver.py
@@@ -177,19 -177,6 +177,22 @@@ class CoreferenceResolver
)
raise
++<<<<<<< HEAD
+ def resolve(self, text: str, **options) -> List[CoreferenceChain]:
+ """
+ Resolve coreferences in text (alias for resolve_coreferences).
+
+ Args:
+ text: Input text
+ **options: Resolution options
+
+ Returns:
+ list: List of coreference chains
+ """
+ return self.resolve_coreferences(text, **options)
+
++=======
++>>>>>>> origin/main
def _extract_mentions(self, text: str) -> List[Mention]:
"""Extract all mentions from text."""
mentions = []
diff --cc semantica/semantic_extract/event_detector.py
index 3a547464,93e4f03d..9c81ea82
--- a/semantica/semantic_extract/event_detector.py
+++ b/semantica/semantic_extract/event_detector.py
@@@ -85,16 -85,7 +85,20 @@@ class Event
class EventDetector:
"""Event detection and extraction handler."""
++<<<<<<< HEAD
+ def __init__(
+ self,
+ event_types: Optional[List[str]] = None,
+ extract_participants: bool = True,
+ extract_location: bool = True,
+ extract_time: bool = True,
+ method: Union[str, List[str]] = None,
+ config=None,
+ **kwargs
+ ):
++=======
+ def __init__(self, method: Union[str, List[str]] = None, config=None, **kwargs):
++>>>>>>> origin/main
"""
Initialize event detector.
@@@ -116,12 -103,6 +120,15 @@@
self.config.update(kwargs)
self.progress_tracker = get_progress_tracker()
++<<<<<<< HEAD
+ # Store parameters
+ self.event_types_filter = event_types
+ self.extract_participants = extract_participants
+ self.extract_location = extract_location
+ self.extract_time = extract_time
+
++=======
++>>>>>>> origin/main
# Store method for passing to extractors if needed
if method is not None:
self.config["ner_method"] = method
@@@ -164,39 -145,19 +171,51 @@@
try:
events = []
++<<<<<<< HEAD
+ # Determine which event types to detect
+ event_patterns_to_use = self.event_patterns
+ if self.event_types_filter:
+ event_patterns_to_use = {
+ k: v for k, v in self.event_patterns.items()
+ if k in self.event_types_filter
+ }
+
++=======
++>>>>>>> origin/main
# Detect events using patterns
self.progress_tracker.update_tracking(
tracking_id, message="Scanning text for event patterns..."
)
++<<<<<<< HEAD
+ for event_type, pattern in event_patterns_to_use.items():
++=======
+ for event_type, pattern in self.event_patterns.items():
++>>>>>>> origin/main
for match in re.finditer(pattern, text, re.IGNORECASE):
# Extract surrounding context
start = max(0, match.start() - 50)
end = min(len(text), match.end() + 50)
context = text[start:end]
++<<<<<<< HEAD
+ # Extract participants if enabled
+ participants = []
+ if self.extract_participants:
+ participants = self._extract_participants(context)
+
+ # Extract location if enabled
+ location = None
+ if self.extract_location:
+ location = self._extract_location(context)
+
+ # Extract time if enabled
+ time_info = None
+ if self.extract_time:
+ time_info = self._extract_time(context)
++=======
+ # Extract participants (simplified)
+ participants = self._extract_participants(context)
++>>>>>>> origin/main
event = Event(
text=match.group(0),
diff --cc semantica/semantic_extract/named_entity_recognizer.py
index 084c22ad,27fa1b24..664e67ae
--- a/semantica/semantic_extract/named_entity_recognizer.py
+++ b/semantica/semantic_extract/named_entity_recognizer.py
@@@ -66,16 -66,7 +66,20 @@@ class NamedEntityRecognizer
• Processes batch text collections
"""
++<<<<<<< HEAD
+ def __init__(
+ self,
+ methods: Optional[List[str]] = None,
+ confidence_threshold: float = 0.5,
+ merge_overlapping: bool = True,
+ include_standard_types: bool = True,
+ method=None,
+ config=None,
+ **kwargs
+ ):
++=======
+ def __init__(self, method=None, config=None, **kwargs):
++>>>>>>> origin/main
"""
Initialize named entity recognizer.
@@@ -93,20 -80,10 +97,23 @@@
self.config.update(kwargs)
self.progress_tracker = get_progress_tracker()
++<<<<<<< HEAD
+ # Store parameters
+ self.methods = methods or ["spacy"]
+ self.confidence_threshold = confidence_threshold
+ self.merge_overlapping = merge_overlapping
+ self.include_standard_types = include_standard_types
+
++=======
++>>>>>>> origin/main
# Use NERExtractor for actual extraction
ner_config = self.config.get("ner", {})
+ ner_config["confidence_threshold"] = confidence_threshold
+ ner_config["merge_overlapping"] = merge_overlapping
if method is not None:
ner_config["method"] = method
+ elif methods:
+ ner_config["method"] = methods[0] if len(methods) == 1 else methods
self.ner_extractor = NERExtractor(**ner_config, **self.config)
self.entity_classifier = EntityClassifier(**self.config.get("classifier", {}))
self.confidence_scorer = EntityConfidenceScorer(**self.config.get("scorer", {}))
diff --cc semantica/semantic_extract/relation_extractor.py
index f4484164,d417a422..8b76d4ea
--- a/semantica/semantic_extract/relation_extractor.py
+++ b/semantica/semantic_extract/relation_extractor.py
@@@ -88,15 -88,7 +88,19 @@@ class Relation
class RelationExtractor:
"""Relation extractor for entity relationships."""
++<<<<<<< HEAD
+ def __init__(
+ self,
+ method: Union[str, List[str]] = "pattern",
+ relation_types: Optional[List[str]] = None,
+ bidirectional: bool = False,
+ confidence_threshold: float = 0.6,
+ max_distance: int = 50,
+ **config
+ ):
++=======
+ def __init__(self, method: Union[str, List[str]] = "pattern", **config):
++>>>>>>> origin/main
"""
Initialize relation extractor.
@@@ -125,15 -114,9 +129,18 @@@
self.config = config
self.progress_tracker = get_progress_tracker()
++<<<<<<< HEAD
+ # Store parameters
+ self.relation_types = relation_types
+ self.bidirectional = bidirectional
+ self.confidence_threshold = confidence_threshold
+ self.max_distance = max_distance
+
++=======
++>>>>>>> origin/main
# Method configuration
self.method = method if isinstance(method, list) else [method]
- self.min_confidence = config.get("min_confidence", 0.5)
+ self.min_confidence = config.get("min_confidence", confidence_threshold)
self.validate = config.get("validate", False)
# Common relation patterns
diff --cc semantica/semantic_extract/triple_extractor.py
index 9a05019d,052c805a..13c0ff9d
--- a/semantica/semantic_extract/triple_extractor.py
+++ b/semantica/semantic_extract/triple_extractor.py
@@@ -90,12 -90,7 +90,16 @@@ class TripleExtractor
"""RDF triple extraction handler."""
def __init__(
++<<<<<<< HEAD
+ self,
+ method: Union[str, List[str]] = "pattern",
+ include_temporal: bool = False,
+ include_provenance: bool = False,
+ config=None,
+ **kwargs
++=======
+ self, method: Union[str, List[str]] = "pattern", config=None, **kwargs
++>>>>>>> origin/main
):
"""
Initialize triple extractor.
@@@ -124,10 -117,6 +128,13 @@@
self.config.update(kwargs)
self.progress_tracker = get_progress_tracker()
++<<<<<<< HEAD
+ # Store parameters
+ self.include_temporal = include_temporal
+ self.include_provenance = include_provenance
+
++=======
++>>>>>>> origin/main
# Method configuration
self.method = method if isinstance(method, list) else [method]
self.min_confidence = self.config.get("min_confidence", 0.5)