Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
docs: improve formatting and structure across all guide pages
KaifAhmad141184da242de
diff --git a/docs/concepts.md b/docs/concepts.mdindex 3ab703cc..1a4cc156 100644--- a/docs/concepts.md+++ b/docs/concepts.md@@ -2,143 +2,569 @@Understand the fundamental concepts behind Semantica. This guide covers the theoretical foundations, key components, and best practices for building semantic applications.-## π§ Core Concepts+!!! info "About This Guide"+ This guide provides a comprehensive overview of the core concepts in Semantica. Each concept includes definitions, visual diagrams, practical examples, and guidance on when to use them.++---++## Table of Contents++- [Prerequisites](#prerequisites)+- [Learning Objectives](#learning-objectives)+- [Concept Map](#concept-map)+- [Core Concepts](#core-concepts)+ - [Knowledge Graphs](#1-knowledge-graphs)+ - [Entity Extraction (NER)](#2-entity-extraction-ner)+ - [Relationship Extraction](#3-relationship-extraction)+ - [Embeddings](#4-embeddings)+ - [Temporal Graphs](#5-temporal-graphs)+ - [GraphRAG](#6-graphrag)+ - [Ontology](#7-ontology)+ - [Quality Assurance](#8-quality-assurance)+ - [Deduplication & Entity Resolution](#9-deduplication--entity-resolution)+ - [Data Normalization](#10-data-normalization)+ - [Conflict Detection](#11-conflict-detection)+- [Comparison Tables](#comparison-tables)+- [Best Practices](#best-practices)+- [Troubleshooting](#troubleshooting)++---++## Prerequisites++Before diving into the core concepts, you should have:++- Basic understanding of Python programming+- Familiarity with data structures (lists, dictionaries, graphs)+- General knowledge of machine learning concepts (helpful but not required)+- Understanding of text processing basics++!!! tip "New to Knowledge Graphs?"+ If you're completely new to knowledge graphs, start with the [Getting Started Guide](getting-started.md) and [Quickstart Tutorial](quickstart.md) before reading this guide.++---++## Learning Objectives++By the end of this guide, you will understand:++- What knowledge graphs are and how they represent information+- How entity and relationship extraction works+- The role of embeddings in semantic understanding+- How temporal graphs track changes over time+- How GraphRAG enhances LLM applications+- The importance of ontologies and quality assurance+- How to resolve conflicts and deduplicate entities+- When to use each concept in your applications++---++## Concept Map++The following diagram shows how the core concepts in Semantica relate to each other:++```mermaid+graph TB+ subgraph Data["Data Sources"]+ Raw[Raw Data]+ end++ subgraph Processing["Processing Pipeline"]+ Ingest[Ingestion]+ Parse[Parsing]+ Norm[Normalization]+ Extract[Entity/Relation Extraction]+ end++ subgraph Core["Core Concepts"]+ KG[Knowledge Graph]+ Embed[Embeddings]+ Temp[Temporal Graphs]+ Onto[Ontology]+ end++ subgraph Quality["Quality Assurance"]+ Dedup[Deduplication]+ Conflict[Conflict Detection]+ QA[Quality Metrics]+ end++ subgraph Application["Applications"]+ GraphRAG[GraphRAG]+ Search[Semantic Search]+ Reason[Reasoning]+ end++ Raw --> Ingest+ Ingest --> Parse+ Parse --> Norm+ Norm --> Extract+ Extract --> KG+ Extract --> Embed+ KG --> Temp+ KG --> Onto+ KG --> Dedup+ KG --> Conflict+ Dedup --> QA+ Conflict --> QA+ KG --> GraphRAG+ Embed --> Search+ KG --> Reason+ Onto --> QA++ style KG fill:#e3f2fd,stroke:#1565c0,stroke-width:3px+ style Embed fill:#fff3e0,stroke:#ef6c00,stroke-width:2px+ style GraphRAG fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px+```++---++## Core Concepts### 1. Knowledge Graphs-**Definition**: A knowledge graph is a structured representation of entities (nodes) and their relationships (edges) with properties and attributes.+!!! abstract "Definition"+ A **knowledge graph** is a structured representation of entities (nodes) and their relationships (edges) with properties and attributes. It transforms unstructured data into a queryable, interconnected knowledge base.++**Key Components**:-- **Nodes**: Represent entities (people, places, concepts, events)-- **Edges**: Represent relationships (works_for, located_in, causes)+- **Nodes (Entities)**: Represent real-world objects, concepts, or events+ - Examples: People, Organizations, Locations, Concepts+- **Edges (Relationships)**: Represent connections between entities+ - Examples: `works_for`, `located_in`, `founded_by`, `causes`- **Properties**: Attributes of entities and relationships-- **Metadata**: Additional information (sources, timestamps, confidence)+ - Examples: Name, Date, Confidence Score, Source+- **Metadata**: Additional information about the data+ - Examples: Source documents, timestamps, extraction methods??? info "Deep Dive: Graph Theory Basics"At its core, a knowledge graph is a directed multigraph $G = (V, E)$ where:- $V$ is a set of vertices (entities)- $E$ is a set of edges (relationships)- - Edges are directed: $(u, v) \in E$ implies a relationship from $u$ to $v$.- - Multigraph property allows multiple edges between the same pair of vertices (e.g., "Friend" and "Colleague").+ - Edges are directed: $(u, v) \in E$ implies a relationship from $u$ to $v$+ - Multigraph property allows multiple edges between the same pair of vertices (e.g., "Friend" and "Colleague")-**Benefits**:-- Structured representation of unstructured data-- Enables complex queries and reasoning-- Supports temporal tracking-- Facilitates knowledge discovery+**Visual Example**:```mermaidgraph LR- A[Apple Inc.<br/>Organization] -->|founded_by| B[Steve Jobs<br/>Person]- A -->|located_in| C[Cupertino<br/>Location]- C -->|in_state| D[California<br/>Location]+ A[Apple Inc.<br/>Organization<br/>Founded: 1976] -->|founded_by| B[Steve Jobs<br/>Person<br/>1955-2011]+ A -->|located_in| C[Cupertino<br/>Location<br/>City]+ C -->|in_state| D[California<br/>Location<br/>State]+ A -->|has_ceo| E[Tim Cook<br/>Person<br/>CEO since 2011]- style A fill:#e3f2fd,stroke:#1565c0- style B fill:#fff3e0,stroke:#ef6c00- style C fill:#f3e5f5,stroke:#7b1fa2- style D fill:#f3e5f5,stroke:#7b1fa2+ style A fill:#e3f2fd,stroke:#1565c0,stroke-width:2px+ style B fill:#fff3e0,stroke:#ef6c00,stroke-width:2px+ style C fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px+ style D fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px+ style E fill:#fff3e0,stroke:#ef6c00,stroke-width:2px```+**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')}")+```++**When to Use**:++- You need to model complex relationships between entities+- You want to query data using graph patterns+- You need to track how information changes over time+- You're building a semantic search or RAG application+- You need to integrate data from multiple sources++**Related Modules**:++- [`kg` Module](reference/kg.md) - Knowledge graph construction and management+- [`graph_store` Module](reference/graph_store.md) - Persistent graph storage+- [`visualization` Module](reference/visualization.md) - Graph visualization++---+### 2. Entity Extraction (NER)-**Definition**: The process of identifying and classifying named entities in text into predefined categories.+!!! abstract "Definition"+ **Named Entity Recognition (NER)** is the process of identifying and classifying named entities in text into predefined categories such as persons, organizations, locations, dates, and more.-| Entity Type | Description | Example |-| :--- | :--- | :--- |-| **Person** | Names of people | Steve Jobs, Elon Musk |-| **Organization** | Companies, institutions | Apple Inc., NASA |-| **Location** | Places, geographic entities | Cupertino, Mars |-| **Date/Time** | Temporal expressions | 1976, next Monday |-| **Money** | Monetary values | $100 million |-| **Event** | Events and occurrences | WWDC 2024 |+**Entity Types**:++| Entity Type | Description | Example |+| :--------------- | :----------------------------- | :------------------------------- |+| **Person** | Names of people | Steve Jobs, Elon Musk, Marie Curie |+| **Organization** | Companies, institutions | Apple Inc., NASA, MIT |+| **Location** | Places, geographic entities | Cupertino, Mars, Pacific Ocean |+| **Date/Time** | Temporal expressions | 1976, next Monday, Q1 2024 |+| **Money** | Monetary values | $100 million, β¬50,000 |+| **Event** | Events and occurrences | WWDC 2024, World War II |+| **Product** | Products and services | iPhone 15, Tesla Model S |+| **Technology** | Technologies and methods | Machine Learning, Python |!!! tip "Custom Entities"- Semantica allows you to define custom entity types via the `Ontology` module. You aren't limited to the standard set!+ Semantica allows you to define custom entity types via the [`Ontology`](reference/ontology.md) module. You aren't limited to the standard set!++**Extraction Methods**:++=== "Rule-based"+ Uses pattern matching (regex) to identify entities.++ **Pros**: Fast, deterministic, no training data needed++ **Cons**: Limited to predefined patterns, less flexible++ ```python+ from semantica.semantic_extract import NamedEntityRecognizer++ 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)+ ```++**Practical Example**:++```python+from semantica.semantic_extract import NamedEntityRecognizer++# Initialize NER+ner = NamedEntityRecognizer()++# Extract entities from text+text = """+Apple Inc. was founded by Steve Jobs in Cupertino, California in 1976.+The company designs and manufactures consumer electronics and software.+Tim Cook is the current CEO of Apple.+"""++entities = ner.extract_entities(text)++print("Extracted Entities:")+for entity in entities:+ print(f" - {entity.text} ({entity.label}) - Confidence: {entity.confidence:.2f}")+```++**When to Use**:-**Methods**:-- **Rule-based**: Pattern matching (Regex)-- **Machine Learning**: Trained models (spaCy, transformers)-- **LLM-based**: Using large language models (GPT-4, Claude)+- You need to identify key entities in unstructured text+- You're building a knowledge graph from documents+- You want to extract structured information from text+- You need to categorize mentions in your data++**Related Modules**:+- [`semantic_extract` Module](reference/semantic_extract.md) - Entity and relationship extraction+- [`ontology` Module](reference/ontology.md) - Custom entity type definitions++---### 3. Relationship Extraction-**Definition**: Identifying and extracting relationships between entities in text.+!!! abstract "Definition"+ **Relationship Extraction** is the process of identifying and extracting semantic relationships between entities in text. It connects entities to form meaningful knowledge structures.-=== "Semantic"- Relationships that define meaning and connection.- - `works_for`- - `located_in`- - `founded_by`+**Relationship Types**:++=== "Semantic Relationships"+ Relationships that define meaning and connection between entities.++ - `works_for` - Employment relationships+ - `located_in` - Geographic relationships+ - `founded_by` - Creation relationships+ - `owns` - Ownership relationships+ - `part_of` - Hierarchical relationships++ ```python+ # Example: "Tim Cook works for Apple Inc."+ # Extracted: (Tim Cook) --[works_for]--> (Apple Inc.)+ ```-=== "Temporal"- Relationships defined by time.- - `happened_before`- - `happened_after`- - `during`+=== "Temporal Relationships"+ Relationships defined by time and sequence.++ - `happened_before` - Temporal precedence+ - `happened_after` - Temporal succession+ - `during` - Temporal containment+ - `overlaps_with` - Temporal overlap++ ```python+ # Example: "WWDC 2023 happened before WWDC 2024"+ # Extracted: (WWDC 2023) --[happened_before]--> (WWDC 2024)+ ```-=== "Causal"+=== "Causal Relationships"Cause and effect relationships.- - `causes`- - `results_in`- - `prevents`++ - `causes` - Direct causation+ - `results_in` - Outcome relationships+ - `prevents` - Prevention relationships+ - `influences` - Indirect influence++ ```python+ # Example: "High inflation causes economic instability"+ # Extracted: (High inflation) --[causes]--> (Economic instability)+ ```++**Visual Example**:++```mermaid+graph LR+ A[Apple Inc.] -->|founded_by| B[Steve Jobs]+ A -->|located_in| C[Cupertino]+ A -->|has_ceo| D[Tim Cook]+ C -->|in_state| E[California]+ B -->|co-founded| F[Apple Inc.]++ style A fill:#e3f2fd+ style B fill:#fff3e0+ style C fill:#f3e5f5+ style D fill:#fff3e0+ style E fill:#f3e5f5+ style F fill:#e3f2fd+```++**Practical Example**:++```python+from semantica.semantic_extract import NamedEntityRecognizer, RelationExtractor++# Extract entities first+ner = NamedEntityRecognizer()+entities = ner.extract_entities(text)++# Extract relationships+rel_extractor = RelationExtractor()+relationships = rel_extractor.extract_relations(text, entities=entities)++print("Extracted Relationships:")+for rel in relationships:+ print(f" {rel.subject.text} --[{rel.predicate}]--> {rel.object.text}")+ print(f" Confidence: {rel.confidence:.2f}, Source: {rel.source}")+```++**When to Use**:++- You need to connect entities in your knowledge graph+- You want to understand how entities relate to each other+- You're building a semantic network+- You need to model complex relationships++**Related Modules**:+- [`semantic_extract` Module](reference/semantic_extract.md) - Relationship extraction+- [`kg` Module](reference/kg.md) - Building graphs from relationships++---### 4. Embeddings-**Definition**: Dense vector representations of text, images, or other data that capture semantic meaning in a continuous vector space.+!!! abstract "Definition"+ **Embeddings** are dense vector representations of text, images, or other data that capture semantic meaning in a continuous vector space. They enable machines to understand similarity and meaning.++!!! note "The Bridge Between Language and Understanding"+ Embeddings are the bridge between human language and machine understanding. They convert text into numerical vectors that preserve semantic relationships.-> [!NOTE]-> Embeddings are the bridge between human language and machine understanding.+**How Embeddings Work**:++Embeddings convert text into numerical vectors that capture semantic meaning. Similar texts have similar vectors, enabling semantic search and similarity calculations.**Example**:+```pythonText: "machine learning"-Embedding: [0.123, -0.456, 0.789, ..., 0.234]-# (vector of 1536 dimensions)+Embedding: [0.123, -0.456, 0.789, ..., 0.234] # (vector of 1536 dimensions)++# Similar texts will have similar vectors+"artificial intelligence" β [0.145, -0.432, 0.801, ..., 0.221] # Close in vector space+"cooking recipes" β [-0.234, 0.567, -0.123, ..., -0.456] # Far in vector space+```++**Embedding Providers**:++| Provider | Model | Dimensions | Speed | Cost | Best For |+| :--- | :--- | :--- | :--- | :--- | :--- |+| **OpenAI** | text-embedding-3-large | 3072 | Fast | Paid | Production, high accuracy |+| **OpenAI** | text-embedding-3-small | 1536 | Fast | Paid | Balanced performance |+| **Cohere** | embed-english-v3.0 | 1024 | Fast | Paid | Multilingual support |+| **HuggingFace** | sentence-transformers | 384-768 | Medium | Free | Development, open source |+| **Local** | Various | Variable | Slow | Free | Privacy, offline use |++**Practical Example**:++```python+from semantica.embeddings import EmbeddingGenerator++# Initialize embedding generator+generator = EmbeddingGenerator(+ provider="openai",+ model="text-embedding-3-small"+)++# Generate embeddings+texts = [+ "Machine learning is a subset of artificial intelligence",+ "Deep learning uses neural networks",+ "Python is a programming language"+]++embeddings = generator.generate(texts)++# Find similar texts+similarity = generator.similarity(embeddings[0], embeddings[1])+print(f"Similarity: {similarity:.2f}") # High similarity```+**When to Use**:++- You need semantic search capabilities+- You want to find similar documents or concepts+- You're building a RAG application+- You need to cluster or classify text+- You want to measure semantic similarity++**Related Modules**:+- [`embeddings` Module](reference/embeddings.md) - Embedding generation+- [`vector_store` Module](reference/vector_store.md) - Vector storage and search++---+### 5. Temporal Graphs-**Definition**: Knowledge graphs that track changes over time, allowing queries about the state of the graph at specific time points.+!!! abstract "Definition"+ **Temporal Graphs** are knowledge graphs that track changes over time, allowing queries about the state of the graph at specific time points. They enable time-aware reasoning and analysis.++**Key Features**:++- **Time-stamped Entities**: Entities have creation and modification timestamps+- **Time-stamped Relationships**: Relationships have validity periods+- **Historical Queries**: Query the graph state at any point in time+- **Change Tracking**: Track how entities and relationships evolve++**Visual Timeline**:```mermaidtimelinetitle Temporal Graph Evolution2020 : Entity A created- : Relationship A->B+ : Relationship A->B established2021 : Entity B updated- : Relationship B->C+ : Relationship B->C created2022 : Entity A deleted: New Relationship D->C+ 2023 : Entity C properties updated+ : Relationship A->B expired+```++**Practical Example**:++```python+from semantica import Semantica++semantica = Semantica(temporal=True)++# Build temporal knowledge graph+result = semantica.build_knowledge_base(+ sources=["historical_data.pdf"],+ temporal=True+)++kg = result["knowledge_graph"]++# Query graph at specific time+historical_state = semantica.kg.query_at_time(+ kg,+ timestamp="2022-01-01",+ query="MATCH (e:Entity) RETURN e"+)++# Track entity changes+changes = semantica.kg.get_entity_history(+ kg,+ entity_id="entity_123",+ start_time="2020-01-01",+ end_time="2023-12-31"+)```+**When to Use**:++- You need to track how information changes over time+- You're analyzing historical data+- You need to query past states of your knowledge+- You're building time-aware applications+- You need to detect trends and patterns over time++**Related Modules**:+- [`kg` Module](reference/kg.md) - Temporal graph support+- [`visualization` Module](reference/visualization.md) - Temporal visualization++---+### 6. GraphRAG-**Definition**: An advanced RAG (Retrieval Augmented Generation) approach that combines vector search with knowledge graph traversal to provide more accurate and contextually relevant information to LLMs.+!!! 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.-**Advantages over Traditional RAG**:-- Better handling of complex queries-- Relationship-aware retrieval-- Reduced hallucinations-- More accurate answers+**How GraphRAG Works**:```mermaidflowchart TD- subgraph Query [Query Processing]+ subgraph Query["Query Processing"]Q[User Query] --> VS[Vector Search]Q --> KE[Keyword Extraction]end-- subgraph Retrieval [Hybrid Retrieval]- VS --> Docs[Relevant Docs]++ 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++ subgraph Synthesis["Answer Generation"]+ Docs --> Prompt[Enhanced Prompt]Context --> PromptPrompt --> LLM[LLM Generation]- LLM --> A[Answer]+ LLM --> A[Accurate Answer]endstyle Q fill:#e1f5fe@@ -146,94 +572,569 @@ flowchart TDstyle 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 |++**Practical Example**:++```python+from semantica import Semantica++semantica = Semantica()++# Build knowledge base with graph+result = semantica.build_knowledge_base(+ sources=["documents/"],+ embeddings=True,+ graph=True+)++# Use GraphRAG for querying+answer = semantica.graphrag.query(+ query="What is the relationship between Company A and Company B?",+ knowledge_graph=result["knowledge_graph"],+ embeddings=result["embeddings"],+ top_k=5+)++print(answer)+```++**When to Use**:++- You're building a RAG application+- You need accurate, context-aware answers+- You want to reduce LLM hallucinations+- You need to answer complex, multi-hop questions+- You need relationship-aware retrieval++**Related Modules**:+- [`kg` Module](reference/kg.md) - Knowledge graph construction+- [`vector_store` Module](reference/vector_store.md) - Vector search+- [`reasoning` Module](reference/reasoning.md) - Graph reasoning++---+### 7. Ontology-**Definition**: A formal specification of concepts, relationships, and constraints in a domain, typically expressed in OWL (Web Ontology Language).+!!! abstract "Definition"+ An **Ontology** is a formal specification of concepts, relationships, and constraints in a domain, typically expressed in OWL (Web Ontology Language). It defines the schema and structure of your knowledge domain.++**Key Components**:++- **Classes**: Categories of entities (e.g., `Person`, `Company`, `Location`)+- **Properties**: Relationships and attributes (e.g., `worksFor`, `hasName`)+- **Individuals**: Specific instances (e.g., `John Doe`, `Apple Inc.`)+- **Axioms**: Rules and constraints (e.g., "A Person can only workFor one Company")++**Ontology Structure**:++```mermaid+classDiagram+ class Person {+ +String name+ +Date birthDate+ +worksFor Company+ }+ class Company {+ +String name+ +Date founded+ +locatedIn Location+ }+ class Location {+ +String city+ +String country+ }++ Person --> Company : worksFor+ Company --> Location : locatedIn+```++**Practical Example**:++```python+from semantica.ontology import OntologyGenerator-- **Classes**: Categories of entities (e.g., `Person`, `Company`)-- **Properties**: Relationships and attributes (e.g., `worksFor`)-- **Individuals**: Specific instances (e.g., `John Doe`)-- **Axioms**: Rules and constraints+# Generate ontology from knowledge graph+generator = OntologyGenerator()++ontology = generator.generate_from_graph(+ knowledge_graph=kg,+ base_uri="https://example.org/ontology/"+)++# Validate ontology+validator = generator.validate(ontology)++# Export to OWL+generator.export_owl(ontology, "output.owl")+```++**When to Use**:++- You need to define a consistent schema for your domain+- You want to ensure data consistency+- You're integrating with other systems+- You need to enforce constraints and rules+- You want to enable reasoning++**Related Modules**:+- [`ontology` Module](reference/ontology.md) - Ontology generation and management+- [`kg` Module](reference/kg.md) - Knowledge graph construction++---### 8. Quality Assurance-**Definition**: Processes and metrics to ensure knowledge graph quality.+!!! abstract "Definition"+ **Quality Assurance** encompasses processes and metrics to ensure knowledge graph quality, including completeness, consistency, accuracy, and coverage validation.++**Quality Dimensions**:++| Dimension | Description | Metrics |+| :--- | :--- | :--- |+| **Completeness** | Percentage of entities with required properties | Property coverage, missing fields |+| **Consistency** | Absence of contradictions | Conflict count, validation errors |+| **Accuracy** | Correctness of extracted information | Precision, recall, F1-score |+| **Coverage** | Breadth of domain coverage | Entity diversity, relationship types |+| **Freshness** | How up-to-date the data is | Last update timestamp, staleness |++**Quality Metrics Example**:++```python+from semantica.kg_qa import KGQualityAssessor++# Assess knowledge graph quality+assessor = KGQualityAssessor()+metrics = assessor.assess(kg)++print(f"Completeness: {metrics.completeness:.2%}")+print(f"Consistency: {metrics.consistency:.2%}")+print(f"Accuracy: {metrics.accuracy:.2%}")+print(f"Coverage: {metrics.coverage:.2%}")++# Get quality report+report = assessor.generate_report(kg)+print(report)+```-- **Completeness**: Percentage of entities with required properties-- **Consistency**: Absence of contradictions-- **Accuracy**: Correctness of extracted information-- **Coverage**: Breadth of domain coverage+**When to Use**:++- You need to validate your knowledge graph+- You want to ensure data quality+- You're preparing data for production+- You need to identify data issues+- You want to measure improvement over time++**Related Modules**:+- [`kg_qa` Module](reference/evals.md) - Quality assurance and evaluation+- [`conflicts` Module](../semantica/conflicts/conflicts_usage.md) - Conflict detection++---++### 9. Deduplication & Entity Resolution++!!! abstract "Definition"+ **Deduplication** and **Entity Resolution** are processes that identify and merge duplicate entities in a knowledge graph, ensuring that the same real-world entity is represented by a single node.++**Why It Matters**:++- Multiple sources may refer to the same entity differently+- "Apple Inc." vs "Apple" vs "Apple Computer" β Same entity+- Prevents graph fragmentation and improves query accuracy++**Resolution Process**:++Deduplication works by calculating similarity between entities. If similarity exceeds a threshold, entities are merged; otherwise, they remain separate.++**Practical Example**:++```python+from semantica.deduplication import Deduplicator++# Initialize deduplicator+deduplicator = Deduplicator(+ similarity_threshold=0.85,+ method="embedding"+)++# Detect duplicates+duplicates = deduplicator.detect_duplicates(kg)++# Merge duplicates+merged_kg = deduplicator.merge(kg, duplicates)++print(f"Original entities: {len(kg['entities'])}")+print(f"Merged entities: {len(merged_kg['entities'])}")+print(f"Duplicates found: {len(duplicates)}")+```++**When to Use**:++- You're integrating data from multiple sources+- You have variations in entity names+- You want to reduce graph redundancy+- You need to improve query accuracy+- You're cleaning your knowledge graph++**Related Modules**:+- [`deduplication` Module](../semantica/deduplication/deduplication_usage.md) - Deduplication and merging+- [`embeddings` Module](reference/embeddings.md) - Similarity calculation----## π Best Practices+### 10. Data Normalization++!!! abstract "Definition"+ **Data Normalization** is the process of cleaning and standardizing data into a consistent format, ensuring uniformity across your knowledge graph.++**Normalization Steps**:++1. **Text Cleaning**: Remove noise, fix encoding issues+2. **Entity Normalization**: Standardize entity names and formats+3. **Date Normalization**: Convert dates to ISO format+4. **Number Normalization**: Standardize numeric formats+5. **Language Detection**: Identify and handle multiple languages++**Normalization Pipeline**:++```mermaid+flowchart LR+ Raw[Raw Text] --> Clean[Text Cleaning]+ Clean --> Entity[Entity<br/>Normalization]+ Entity --> Date[Date<br/>Normalization]+ Date --> Number[Number<br/>Normalization]+ Number --> Normalized[Normalized<br/>Data]++ style Raw fill:#ffcdd2+ style Normalized fill:#c8e6c9+```++**Practical Example**:++```python+from semantica.normalize import TextNormalizer++# Initialize normalizer+normalizer = TextNormalizer()++# Normalize text+raw_text = "Apple Inc. was founded on April 1, 1976 in Cupertino, CA."+normalized = normalizer.normalize(raw_text)++# Normalize entities+entities = [+ {"text": "Apple Inc.", "type": "ORG"},+ {"text": "apple inc", "type": "ORG"}, # Duplicate with different case+]++normalized_entities = normalizer.normalize_entities(entities)+# Result: Both normalized to "Apple Inc."+```++**When to Use**:++- You have inconsistent data formats+- You're processing data from multiple sources+- You need to standardize entity names+- You want to improve extraction accuracy+- You're preparing data for deduplication++**Related Modules**:+- [`normalize` Module](reference/normalize.md) - Data normalization+- [`parse` Module](reference/parse.md) - Document parsing++---++### 11. Conflict Detection++!!! abstract "Definition"+ **Conflict Detection** identifies contradictory information in a knowledge graph, such as conflicting facts about the same entity from different sources.++**Conflict Types**:++| Type | Description | Example |+| :--- | :--- | :--- |+| **Value Conflict** | Different values for same property | "Founded: 1976" vs "Founded: 1977" |+| **Relationship Conflict** | Conflicting relationships | "CEO: Tim Cook" vs "CEO: Steve Jobs" |+| **Type Conflict** | Different entity types | "Apple: Company" vs "Apple: Product" |+| **Temporal Conflict** | Conflicting time information | "Active: 2020-2023" vs "Active: 2021-2024" |++**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)+ ```++**Practical Example**:++```python+from semantica.conflicts import ConflictDetector, ConflictResolver++# Detect conflicts+detector = ConflictDetector()+conflicts = detector.detect(kg)++print(f"Found {len(conflicts)} conflicts")++# Resolve conflicts+resolver = ConflictResolver(strategy="voting")+resolved_kg = resolver.resolve_conflicts(kg, conflicts)++# Investigate specific conflicts+for conflict in conflicts[:5]:+ print(f"Conflict: {conflict.entity}")+ print(f" Sources: {conflict.sources}")+ print(f" Values: {conflict.values}")+```++**When to Use**:++- You're integrating data from multiple sources+- You have conflicting information+- You need to ensure data consistency+- You want to track data provenance+- You're building a reliable knowledge base++**Related Modules**:+- [`conflicts` Module](../semantica/conflicts/conflicts_usage.md) - Conflict detection and resolution+- [`kg_qa` Module](reference/evals.md) - Quality assurance++---++## Comparison Tables++### Embedding Providers Comparison++| Provider | Model | Dimensions | Speed | Cost | Accuracy | Best For |+| :--- | :--- | :--- | :--- | :--- | :--- | :--- |+| Provider | Model | Dimensions | Speed | Cost | Accuracy | Best For |+| :------------ | :--------------------- | :--------- | :------ | :---- | :------- | :-------------------------- |+| **OpenAI** | text-embedding-3-large | 3072 | Fast | Paid | High | Production, high accuracy |+| **OpenAI** | text-embedding-3-small | 1536 | Fast | Paid | High | Balanced performance |+| **Cohere** | embed-english-v3.0 | 1024 | Fast | Paid | High | Multilingual support |+| **HuggingFace**| all-MiniLM-L6-v2 | 384 | Medium | Free | Medium | Development, open source |+| **Local** | sentence-transformers | 384-768 | Slow | Free | Medium | Privacy, offline use |++### Graph Backend Comparison++| Backend | Type | Speed | Scalability | Query Language | Best For |+| :--- | :--- | :--- | :--- | :--- | :--- |+| Backend | Type | Speed | Scalability | Query Language | Best For |+| :--------- | :---------- | :-------- | :---------- | :------------- | :-------------------------------- |+| **NetworkX**| In-memory | Fast | Small-medium| Python API | Development, small graphs |+| **Neo4j** | Database | Medium | Large | Cypher | Production, complex queries |+| **KuzuDB** | Embedded | Fast | Medium | Cypher | Embedded applications |+| **FalkorDB**| Redis-based| Very Fast | Large | Cypher | Real-time, high throughput |++---++## Best PracticesFollowing these practices will help you build high-quality knowledge graphs and avoid common pitfalls.### 1. Start Small+!!! tip "Iterative Approach"Don't try to model the entire world at once. Start with a small, well-defined domain and expand incrementally.+**Example**:+```python+# Start with a single document+kg1 = semantica.build_knowledge_base(["doc1.pdf"])++# Validate and refine+quality = assessor.assess(kg1)++# Then expand+kg2 = semantica.build_knowledge_base(["doc2.pdf", "doc3.pdf"])+merged = semantica.kg.merge([kg1, kg2])+```+### 2. Configure Properly-- Use environment variables for sensitive data.-- Set up proper logging.-- Configure appropriate model sizes.++- Use environment variables for sensitive data+- Set up proper logging+- Configure appropriate model sizes+- Use configuration files for complex setups++```python+# Good: Use environment variables+import os+api_key = os.getenv("OPENAI_API_KEY")++# Good: Use config files+from semantica import Config+config = Config.from_file("config.yaml")+semantica = Semantica(config=config)+```### 3. Validate Data+!!! warning "Garbage In, Garbage Out"Always validate extracted entities. A knowledge graph with incorrect facts is worse than no graph at all.+**Validation Checklist**:+- Check entity extraction accuracy+- Validate relationships make sense+- Verify confidence scores+- Review source attribution+- Test with sample queries+### 4. Handle Errors-- Implement error handling.-- Use retry mechanisms.-- Log errors for debugging.++- Implement error handling+- Use retry mechanisms+- Log errors for debugging+- Gracefully handle API failures++```python+from semantica import Semantica+import logging++logging.basicConfig(level=logging.INFO)+semantica = Semantica()++try:+ result = semantica.build_knowledge_base(["doc.pdf"])+except Exception as e:+ logging.error(f"Error building KG: {e}")+ # Handle error appropriately+```### 5. Optimize Performance-- Use batch processing for large datasets.-- Enable parallel processing where possible.-- Cache embeddings and results.++- Use batch processing for large datasets+- Enable parallel processing where possible+- Cache embeddings and results+- Use appropriate backend for your scale++```python+# Batch processing+sources = ["doc1.pdf", "doc2.pdf", ..., "doc100.pdf"]+batch_size = 10++for i in range(0, len(sources), batch_size):+ batch = sources[i:i+batch_size]+ result = semantica.build_knowledge_base(batch)+ # Process and save results+```### 6. Document Workflows-- Document data sources.-- Track processing steps.-- Maintain metadata.++- Document data sources+- Track processing steps+- Maintain metadata+- Version your knowledge graphs----## π§ Troubleshooting+## TroubleshootingCommon issues and solutions:!!! failure "Import Errors"**Solution**:- - Ensure Semantica is properly installed.- - Check Python version (3.8+).- - Verify virtual environment is activated.+ - Ensure Semantica is properly installed: `pip install semantica`+ - Check Python version (3.8+): `python --version`+ - Verify virtual environment is activated- Install missing dependencies: `pip install -r requirements.txt`!!! failure "API Key Errors"**Solution**:- - Set environment variables: `export SEMANTICA_API_KEY=your_key`- - Check config file for correct key format.- - Verify API key is valid and has sufficient credits.+ - Set environment variables: `export OPENAI_API_KEY=your_key`+ - Check config file for correct key format+ - Verify API key is valid and has sufficient credits+ - Test API connection: `curl https://api.openai.com/v1/models`!!! failure "Memory Issues"**Solution**:- - Process documents in batches.- - Use smaller embedding models.- - Enable garbage collection.- - Consider using streaming for large datasets.+ - Process documents in batches+ - Use smaller embedding models+ - Enable garbage collection+ - Consider using streaming for large datasets+ - Use graph store backends (Neo4j, KuzuDB) instead of in-memory!!! failure "Low Quality Extractions"**Solution**:- - Preprocess and normalize text.- - Use domain-specific models.- - Adjust extraction parameters.- - Validate and clean extracted entities.+ - Preprocess and normalize text+ - Use domain-specific models+ - Adjust extraction parameters+ - Validate and clean extracted entities+ - Use LLM-based extraction for better accuracy+ - Fine-tune models on your domain!!! failure "Slow Processing"**Solution**:- - Enable parallel processing.- - Use GPU acceleration if available.- - Cache intermediate results.- - Optimize batch sizes.+ - Enable parallel processing+ - Use GPU acceleration if available+ - Cache embeddings and results+ - Optimize batch sizes+ - Use faster embedding models+ - Consider using local models for development++!!! failure "Graph Too Large"+ **Solution**:+ - Use graph store backends (Neo4j, KuzuDB) instead of NetworkX+ - Implement graph partitioning+ - Use incremental building+ - Filter entities by confidence threshold+ - Remove low-value relationships++---++## Next Steps++Now that you understand the core concepts:++1. **[Getting Started](getting-started.md)** - Set up Semantica and build your first knowledge graph+2. **[Modules Guide](modules.md)** - Learn about the available modules+3. **[Use Cases](use-cases.md)** - Explore real-world applications+4. **[Examples](examples.md)** - See practical code examples+5. **[API Reference](reference/core.md)** - Detailed API documentation++---++!!! info "Contribute"+ Found an issue or want to improve this guide? [Contribute on GitHub](https://github.com/Hawksight-AI/semantica)++**Last Updated**: 2024diff --git a/docs/examples.md b/docs/examples.mdindex 3534954b..4fcada8e 100644--- a/docs/examples.md+++ b/docs/examples.md@@ -5,14 +5,35 @@ Real-world examples and use cases for Semantica.!!! tip "Interactive Learning"For hands-on interactive tutorials, check out our [Cookbook](cookbook.md) with Jupyter notebooks covering everything from basics to advanced use cases.-## Basic Examples+----!!! note "Code Examples"- All examples assume you have Semantica installed and imported. See the [Installation Guide](installation.md) if you need to set it up first.+## Table of Contents++- [Getting Started (5 min examples)](#getting-started-5-min-examples)+- [Core Workflows (15 min examples)](#core-workflows-15-min-examples)+- [Advanced Patterns (30+ min examples)](#advanced-patterns-30-min-examples)+- [Production Patterns](#production-patterns)++---++!!! note "Prerequisites"+ All examples assume you have Semantica installed. See the [Installation Guide](installation.md) if you need to set it up first.++---++## Getting Started (5 min examples)++Quick examples to get you up and running with Semantica.### Example 1: Basic Knowledge Graph-Build a knowledge graph from a single document:+**Difficulty**: Beginner+**Time**: 5 minutes+**Prerequisites**: Semantica installed, sample PDF++Build a knowledge graph from a single document.++**Code**:```pythonfrom semantica import Semantica@@ -31,9 +52,34 @@ print(f"Entities: {len(kg['entities'])}")print(f"Relationships: {len(kg['relationships'])}")```+**Expected Output**:++```+Entities: 45+Relationships: 32+```++**Common Errors**:++- `FileNotFoundError`: Ensure the PDF file exists in the current directory+- `ImportError`: Make sure Semantica is installed: `pip install semantica`++**Next Steps**:++- [Example 2: Entity Extraction](#example-2-entity-extraction)+- [Core Workflows](#core-workflows-15-min-examples)++---+### Example 2: Entity Extraction-Extract entities from text:+**Difficulty**: Beginner+**Time**: 5 minutes+**Prerequisites**: Semantica installed++Extract entities from text using Named Entity Recognition.++**Code**:```pythonfrom semantica import Semantica@@ -51,7 +97,8 @@ for entity in entities["entities"]:print(f"{entity['text']}: {entity['type']}")```-**Output:**+**Expected Output**:+```Apple Inc.: ORGANIZATIONSteve Jobs: PERSON@@ -60,9 +107,27 @@ California: LOCATIONTim Cook: PERSON```+**Common Errors**:++- `AttributeError`: Ensure you're using the correct API: `semantica.semantic_extract.extract_entities()`+- Empty results: Check that your text contains named entities++**Next Steps**:++- [Example 3: Multi-Source Integration](#example-3-multi-source-integration)+- [Core Workflows](#core-workflows-15-min-examples)++---+### Example 3: Multi-Source Integration-Combine data from multiple sources:+**Difficulty**: Beginner+**Time**: 5 minutes+**Prerequisites**: Multiple data sources++Combine data from multiple sources into a unified knowledge graph.++**Code**:```pythonfrom semantica import Semantica@@ -81,9 +146,32 @@ kg = result["knowledge_graph"]print(f"Unified knowledge graph with {len(kg['entities'])} entities")```+**Expected Output**:++```+Unified knowledge graph with 120 entities+```++**Common Errors**:++- Network errors for URLs: Check internet connection and URL accessibility+- File format errors: Ensure all file formats are supported++**Next Steps**:++- [Core Workflows](#core-workflows-15-min-examples)++---+### Example 4: Export Formats-Export knowledge graph to multiple formats:+**Difficulty**: Beginner+**Time**: 5 minutes+**Prerequisites**: Knowledge graph built++Export knowledge graph to multiple formats.++**Code**:```pythonfrom semantica import Semantica@@ -98,11 +186,21 @@ semantica.export.to_csv(kg, "output.csv")semantica.export.to_owl(kg, "output.owl")```-## Advanced Examples+---++## Core Workflows (15 min examples)++Common workflows for building production-ready knowledge graphs.### Example 5: Conflict Resolution-Resolve conflicts in data from multiple sources:+**Difficulty**: Intermediate+**Time**: 15 minutes+**Prerequisites**: Multiple data sources with potential conflicts++Resolve conflicts in data from multiple sources.++**Code**:```pythonfrom semantica import Semantica@@ -129,7 +227,13 @@ print(f"Resolved {len(resolved)} conflicts")### Example 6: Custom Configuration-Use custom configuration for specific use cases:+**Difficulty**: Intermediate+**Time**: 15 minutes+**Prerequisites**: Understanding of configuration options++Use custom configuration for specific use cases.++**Code**:```pythonfrom semantica import Semantica, Config@@ -148,7 +252,13 @@ result = semantica.build_knowledge_base(["document.pdf"])### Example 7: Incremental Graph Building-Build knowledge graph incrementally:+**Difficulty**: Intermediate+**Time**: 15 minutes+**Prerequisites**: Multiple data sources to process incrementally++Build knowledge graph incrementally.++**Code**:```pythonfrom semantica import Semantica@@ -168,7 +278,13 @@ print(f"Merged graph: {len(merged_kg['entities'])} entities")### Example 8: Visualization-Create interactive visualizations:+**Difficulty**: Beginner+**Time**: 10 minutes+**Prerequisites**: Knowledge graph built++Create interactive visualizations.++**Code**:```pythonfrom semantica import Semantica@@ -188,9 +304,21 @@ print(f"Graph density: {analysis['density']}")print(f"Connected components: {analysis['components']}")```+---++## Advanced Patterns (30+ min examples)++Advanced patterns for complex use cases and production deployments.+### Example 9: Graph Store (Persistent Storage)-Store and query knowledge graphs in a persistent graph database:+**Difficulty**: Intermediate+**Time**: 30 minutes+**Prerequisites**: Neo4j or KuzuDB installed++Store and query knowledge graphs in a persistent graph database.++**Code**:```pythonfrom semantica.graph_store import GraphStore@@ -235,7 +363,13 @@ store.close()### Example 10: Using KuzuDB (Embedded)-For embedded graph storage without external dependencies:+**Difficulty**: Intermediate+**Time**: 20 minutes+**Prerequisites**: KuzuDB installed++For embedded graph storage without external dependencies.++**Code**:```pythonfrom semantica.graph_store import GraphStore@@ -255,7 +389,13 @@ store.close()### Example 11: FalkorDB for Real-Time Applications-Ultra-fast graph queries for LLM applications:+**Difficulty**: Intermediate+**Time**: 25 minutes+**Prerequisites**: Redis and FalkorDB installed++Ultra-fast graph queries for LLM applications.++**Code**:```pythonfrom semantica.graph_store import GraphStore@@ -279,6 +419,109 @@ results = store.execute_query("""store.close()```+---++## Production Patterns++Production-ready patterns for scalable deployments.++### Example 12: Streaming Data Processing++**Difficulty**: Advanced+**Time**: 45 minutes+**Prerequisites**: Understanding of streaming architectures++Process data streams in real-time.++**Code**:++```python+from semantica.ingest import StreamIngestor+from semantica import Semantica++semantica = Semantica()++# Set up stream ingestor+stream_ingestor = StreamIngestor(stream_uri="kafka://localhost:9092/topic")++# Process stream+for batch in stream_ingestor.stream(batch_size=100):+ result = semantica.build_knowledge_base(+ sources=batch,+ embeddings=True,+ graph=True+ )+ # Process and store results+ process_results(result)+```++**Expected Output**:+```+Processing batch 1: 100 documents+Processing batch 2: 100 documents+...+```++---++### Example 13: Custom Extractors++**Difficulty**: Advanced+**Time**: 60 minutes+**Prerequisites**: Understanding of extraction patterns++Create custom entity extractors for domain-specific entities.++**Code**:++```python+from semantica.semantic_extract import BaseExtractor++class CustomProductExtractor(BaseExtractor):+ def extract(self, text):+ # Your custom extraction logic+ products = []+ # Pattern matching or ML model+ return products++# Use custom extractor+extractor = CustomProductExtractor()+entities = extractor.extract(text)+```++---++### Example 14: Batch Processing Large Datasets++**Difficulty**: Intermediate+**Time**: 30 minutes+**Prerequisites**: Large dataset to process++Process large datasets efficiently with batching.++**Code**:++```python+from semantica import Semantica+import os++semantica = Semantica()+sources = [f"data/doc_{i}.pdf" for i in range(1000)]+batch_size = 50++for i in range(0, len(sources), batch_size):+ batch = sources[i:i+batch_size]+ result = semantica.build_knowledge_base(+ sources=batch,+ embeddings=True,+ graph=True+ )+ # Save intermediate results+ save_batch_result(result, batch_num=i//batch_size)+```++---+## Use Case Examples### Research Paper Analysis@@ -361,9 +604,30 @@ For more interactive examples and tutorials, check out our [Cookbook](cookbook.m- **Advanced**: Advanced techniques and patterns- **Use Cases**: Real-world applications in various domains+---++## Example Gallery++Visual previews of what you can build with Semantica:++- **Knowledge Graph Visualization**: Interactive network graphs+- π **Analytics Dashboards**: Quality metrics and insights+- π **Semantic Search**: Vector-based document retrieval+- π§ **GraphRAG Applications**: Enhanced LLM responses++---+## More Resources- **[Quick Start Guide](quickstart.md)** - Step-by-step tutorial-- **[API Reference](api.md)** - Complete API documentation+- **[API Reference](reference/core.md)** - Complete API documentation- **[Cookbook](cookbook.md)** - Interactive Jupyter notebooks-- **[Code Examples](../CodeExamples.md)** - Additional code samples+- **[Use Cases](use-cases.md)** - Real-world applications+- **[Modules Guide](modules.md)** - Module documentation++---++!!! info "Contribute"+ Have an example to share? [Contribute on GitHub](https://github.com/Hawksight-AI/semantica)++**Last Updated**: 2024diff --git a/docs/learning-more.md b/docs/learning-more.mdindex b0b72654..7e6b6488 100644--- a/docs/learning-more.md+++ b/docs/learning-more.md@@ -2,172 +2,643 @@Additional resources, tutorials, and advanced learning materials for Semantica.-## Additional Tutorials+!!! info "About This Guide"+ This guide provides structured learning paths, quick references, troubleshooting guides, and advanced topics to help you master Semantica.-### Video Tutorials+----Coming soon! We're working on video tutorials covering:+## Table of Contents-- Getting started with Semantica-- Building your first knowledge graph-- Advanced techniques and patterns-- Real-world use cases+- [Structured Learning Paths](#structured-learning-paths)+- [Quick Reference](#quick-reference)+- [Troubleshooting Guide](#troubleshooting-guide)+- [Migration Guide](#migration-guide)+- [Performance Optimization](#performance-optimization)+- [Security Best Practices](#security-best-practices)+- [FAQ Expansion](#faq-expansion)+- [Glossary Quick Reference](#glossary-quick-reference)-### Blog Posts & Articles+----Stay tuned for blog posts covering:+## Structured Learning Paths-- Best practices for knowledge graph construction-- Performance optimization tips-- Integration guides-- Case studies and success stories+Follow these structured paths based on your experience level.++### Beginner Path (1-2 hours)++Perfect for those new to Semantica and knowledge graphs.++**Step 1: Installation & Setup** (15 min)+- [Installation Guide](installation.md)+- [Configuration Basics](cookbook/introduction/Configuration_Basics.ipynb)+- Verify installation: `import semantica; print(semantica.__version__)`++**Step 2: Core Concepts** (30 min)+- [Core Concepts](concepts.md) - Read sections 1-5+- [Getting Started Guide](getting-started.md)+- Understand: Knowledge Graphs, Entities, Relationships++**Step 3: First Knowledge Graph** (30 min)+- [Quickstart Tutorial](quickstart.md)+- [Your First Knowledge Graph](cookbook/introduction/Your_First_Knowledge_Graph.ipynb)+- Build a simple KG from a document++**Step 4: Basic Operations** (30 min)+- [Examples](examples.md) - Examples 1-3+- Extract entities and relationships+- Visualize your graph++**Completion Checklist**:+- Semantica installed and configured+- Built your first knowledge graph+- Understand basic concepts+- Can extract entities and relationships++**Next**: Move to [Intermediate Path](#intermediate-path-4-6-hours)++---++### Intermediate Path (4-6 hours)-## Best Practices+For users comfortable with basics who want to build production applications.-### Knowledge Graph Design+**Step 1: Advanced Concepts** (1 hour)+- [Core Concepts](concepts.md) - Complete guide+- [Modules Guide](modules.md) - All 13 modules+- Understand: Embeddings, GraphRAG, Ontologies-1. **Start with Clear Objectives**- - Define what you want to extract- - Identify key entities and relationships- - Plan your schema before processing+**Step 2: Use Cases** (1 hour)+- [Use Cases Guide](use-cases.md)+- Pick 2-3 relevant use cases+- Implement at least one complete use case-2. **Iterate and Refine**- - Start with a small dataset- - Validate extracted entities- - Refine extraction patterns- - Scale up gradually+**Step 3: Advanced Examples** (1 hour)+- [Examples](examples.md) - Examples 4-10+- Conflict resolution+- Custom configuration+- Graph stores-3. **Quality Over Quantity**- - Focus on accuracy- - Validate relationships- - Resolve conflicts early- - Maintain data quality+**Step 4: Quality & Optimization** (1 hour)+- [Quality Assurance](concepts.md#8-quality-assurance)+- [Performance Optimization](#performance-optimization)+- Learn about deduplication and conflict detection-### Performance Tips+**Step 5: Integration Patterns** (1 hour)+- [Integration Patterns](modules.md#integration-patterns)+- Build a complete pipeline+- Connect multiple modules+**Completion Checklist**:+- Understand all core concepts+- Can build complex knowledge graphs+- Know how to optimize performance+- Can integrate multiple modules+- Implemented a real-world use case++**Next**: Move to [Advanced Path](#advanced-path-8-hours)++---++### Advanced Path (8+ hours)++For experienced users building enterprise applications.++**Step 1: Advanced Architecture** (2 hours)+- [Architecture Guide](architecture.md)+- [Deep Dive](deep-dive.md)+- Custom extractors and exporters+- Plugin development++**Step 2: Production Deployment** (2 hours)+- [Performance Optimization](#performance-optimization)+- [Security Best Practices](#security-best-practices)+- Scalability patterns+- Monitoring and logging++**Step 3: Advanced Use Cases** (2 hours)+- [Use Cases](use-cases.md) - All advanced use cases+- [Examples](examples.md) - Production patterns+- Build a complete production system++**Step 4: Customization** (2 hours)+- Custom extractors+- Custom exporters+- Plugin development+- API extensions++**Completion Checklist**:+- Can design custom architectures+- Understand production deployment+- Can build custom components+- Have implemented a production system++---++## Quick Reference++### Common Operations Cheat Sheet++**Initialize Semantica**:```python-# Process in batches for large datasets-sources = ["doc1.pdf", "doc2.pdf", "doc3.pdf"]-batch_size = 10+from semantica import Semantica+semantica = Semantica()+```++**Build Knowledge Graph**:+```python+result = semantica.build_knowledge_base(+ sources=["doc.pdf"],+ embeddings=True,+ graph=True+)+```++**Extract Entities**:+```python+entities = semantica.semantic_extract.extract_entities(text)+```+**Extract Relationships**:+```python+relationships = semantica.semantic_extract.extract_relations(text, entities)+```++**Query Graph**:+```python+results = semantica.kg.query("MATCH (n) RETURN n LIMIT 10")+```++**Export Graph**:+```python+semantica.export.to_json(kg, "output.json")+semantica.export.to_rdf(kg, "output.rdf")+```++### Configuration Reference++| Setting | Environment Variable | Config File | Default |+| :--- | :--- | :--- | :--- |+| OpenAI API Key | `OPENAI_API_KEY` | `api_keys.openai` | `None` |+| Embedding Provider | `SEMANTICA_EMBEDDING_PROVIDER` | `embedding.provider` | `"openai"` |+| Graph Backend | `SEMANTICA_GRAPH_BACKEND` | `knowledge_graph.backend` | `"networkx"` |+| Temporal Graphs | `SEMANTICA_TEMPORAL` | `knowledge_graph.temporal` | `False` |++### CLI Commands Reference++```bash+# Install Semantica+pip install semantica++# Install with extras+pip install semantica[all]+pip install semantica[gpu]+pip install semantica[visualization]++# Verify installation+python -c "import semantica; print(semantica.__version__)"++# Run tests+pytest tests/++# Build documentation+mkdocs serve+```++---++## Troubleshooting Guide++### Common Issues and Solutions++#### Issue: Import Errors++**Symptoms**: `ModuleNotFoundError` or `ImportError`++**Solutions**:+1. Verify installation: `pip list | grep semantica`+2. Check Python version: `python --version` (requires 3.8+)+3. Reinstall: `pip install --upgrade semantica`+4. Check virtual environment is activated++**Code**:+```python+import sys+print(sys.version) # Should be 3.8++import semantica+print(semantica.__version__)+```++#### Issue: API Key Errors++**Symptoms**: `AuthenticationError` or `Invalid API Key`++**Solutions**:+1. Set environment variable: `export OPENAI_API_KEY=your_key`+2. Check config file: `~/.semantica/config.yaml`+3. Verify key is valid: Test with OpenAI API directly+4. Check key has sufficient credits++**Code**:+```python+import os+print(os.getenv("OPENAI_API_KEY")) # Should not be None+```++#### Issue: Memory Errors++**Symptoms**: `MemoryError` or system slowdown++**Solutions**:+1. Process in smaller batches+2. Use graph stores (Neo4j, KuzuDB) instead of NetworkX+3. Reduce batch sizes+4. Enable garbage collection+5. Use streaming for large datasets++**Code**:+```python+# Process in batches+batch_size = 10for i in range(0, len(sources), batch_size):batch = sources[i:i+batch_size]result = semantica.build_knowledge_base(batch)- # Process and save results```-### Integration Patterns+#### Issue: Slow Processing++**Symptoms**: Very long processing times++**Solutions**:+1. Enable parallel processing+2. Use faster embedding models+3. Cache embeddings+4. Use GPU acceleration+5. Optimize batch sizes++**Code**:+```python+# Enable parallel processing+result = semantica.build_knowledge_base(+ sources=sources,+ parallel=True,+ max_workers=4+)+```++#### Issue: Low Quality Extractions++**Symptoms**: Incorrect or missing entities/relationships-#### Pattern 1: Incremental Building+**Solutions**:+1. Use LLM-based extraction (more accurate)+2. Preprocess and normalize text+3. Adjust confidence thresholds+4. Use domain-specific models+5. Validate and clean extracted data+**Code**:```python-# Build knowledge graph incrementally-kg = None+# Use LLM-based extraction+extractor = NERExtractor(method="llm", model="gpt-4")+entities = extractor.extract(text)+```++#### Issue: Graph Too Large++**Symptoms**: Memory issues, slow queries++**Solutions**:+1. Use graph store backends (Neo4j, KuzuDB)+2. Filter by confidence threshold+3. Implement graph partitioning+4. Use incremental building+5. Remove low-value relationships++**Code**:+```python+# Use Neo4j for large graphs+builder = GraphBuilder(backend="neo4j")+kg = builder.build(entities, relationships)+```++---++## Migration Guide++### Migrating from Other Tools++#### From NetworkX++**Key Differences**:+- Semantica provides higher-level abstractions+- Built-in entity extraction and relationship extraction+- Integrated embeddings and vector stores++**Migration Steps**:+1. Install Semantica: `pip install semantica`+2. Convert existing graphs to Semantica format+3. Use Semantica's extraction capabilities+4. Migrate to Semantica's graph stores++**Code**:+```python+# Old: NetworkX+import networkx as nx+G = nx.DiGraph()+G.add_node("entity1")+G.add_edge("entity1", "entity2", relation="knows")++# New: Semantica+from semantica import Semantica+semantica = Semantica()+result = semantica.build_knowledge_base(["doc.pdf"])+kg = result["knowledge_graph"]+```++#### From spaCy++**Key Differences**:+- Semantica includes graph construction+- Integrated knowledge graph management+- Built-in relationship extraction++**Migration Steps**:+1. Replace spaCy NER with Semantica's extractors+2. Use Semantica's relationship extraction+3. Build knowledge graphs automatically++**Code**:+```python+# Old: spaCy+import spacy+nlp = spacy.load("en_core_web_sm")+doc = nlp(text)+entities = [(ent.text, ent.label_) for ent in doc.ents]++# New: Semantica+from semantica import Semantica+semantica = Semantica()+entities = semantica.semantic_extract.extract_entities(text)+kg = semantica.build_knowledge_base([text])+```++---++## Performance Optimization++### Optimization Strategies++#### 1. Batch Processing++Process multiple documents together for better throughput.++```python+# Good: Batch processing+sources = ["doc1.pdf", "doc2.pdf", ..., "doc100.pdf"]+result = semantica.build_knowledge_base(sources, batch_size=10)++# Bad: One at a timefor source in sources:result = semantica.build_knowledge_base([source])- if kg is None:- kg = result["knowledge_graph"]- else:- kg = semantica.kg.merge([kg, result["knowledge_graph"]])```-#### Pattern 2: Pipeline Processing+#### 2. Caching-```python-# Create a processing pipeline-pipeline = [- ("ingest", semantica.ingest.from_file),- ("parse", semantica.parse.document),- ("extract", semantica.semantic_extract.entities),- ("build", semantica.kg.build_graph)-]+Cache expensive operations like embeddings.-for step_name, step_func in pipeline:- data = step_func(data)+```python+# Enable caching+generator = EmbeddingGenerator(cache=True)+embeddings = generator.generate(texts) # Cached on second call```-## Advanced Topics+#### 3. Parallel Execution++Use parallel processing for independent operations.++```python+# Enable parallel processing+result = semantica.build_knowledge_base(+ sources=sources,+ parallel=True,+ max_workers=8+)+```-### Custom Extractors+#### 4. Backend Selection-Create custom entity extractors:+Choose appropriate backends for your scale.```python-from semantica.semantic_extract import BaseExtractor+# Small graphs: NetworkX (fast, in-memory)+builder = GraphBuilder(backend="networkx")++# Large graphs: Neo4j (persistent, scalable)+builder = GraphBuilder(backend="neo4j")+```++#### 5. Resource Limits++Set appropriate limits to prevent resource exhaustion.-class CustomExtractor(BaseExtractor):- def extract(self, text):- # Your custom extraction logic- return entities+```python+# Limit memory usage+parser = DocumentParser(max_file_size=10_000_000) # 10MB++# Limit processing time+result = semantica.build_knowledge_base(+ sources=sources,+ timeout=300 # 5 minutes+)```-### Custom Export Formats+### Performance Benchmarks++| Operation | NetworkX | Neo4j | KuzuDB | Notes |+| :--- | :--- | :--- | :--- | :--- |+| **Graph Construction** | β‘β‘β‘ | β‘β‘ | β‘β‘β‘ | NetworkX fastest for small graphs |+| **Query Performance** | β‘β‘ | β‘β‘β‘ | β‘β‘β‘ | Neo4j/KuzuDB better for complex queries |+| **Memory Usage** | High | Low | Medium | NetworkX loads all in memory |+| **Scalability** | Low | High | Medium | Neo4j best for large graphs |++---++## Security Best Practices++### API Key Management-Add custom export formats:+**DO**:+- Use environment variables for API keys+- Store keys in secure configuration files+- Rotate keys regularly+- Use separate keys for development/production+**DON'T**:+- Commit API keys to version control+- Hardcode keys in source code+- Share keys publicly+- Use production keys in development++**Code**:```python-from semantica.export import BaseExporter+# Good: Environment variables+import os+api_key = os.getenv("OPENAI_API_KEY")-class CustomExporter(BaseExporter):- def export(self, kg, path):- # Your custom export logic- pass+# Bad: Hardcoded+api_key = "sk-..." # Never do this!```-### Performance Optimization+### Data Privacy-- Use GPU acceleration when available-- Process documents in parallel-- Cache embeddings-- Optimize graph queries+**DO**:+- Encrypt sensitive data+- Use local models when possible+- Implement access controls+- Audit data access-## Community Resources+**DON'T**:+- Send sensitive data to external APIs without encryption+- Store PII in knowledge graphs without protection+- Share knowledge graphs with sensitive data-### GitHub Discussions+### Network Security-Join discussions on:-- [General Discussion](https://github.com/Hawksight-AI/semantica/discussions)-- [Q&A](https://github.com/Hawksight-AI/semantica/discussions/categories/q-a)-- [Show and Tell](https://github.com/Hawksight-AI/semantica/discussions/categories/show-and-tell)+**DO**:+- Use HTTPS for all API calls+- Validate SSL certificates+- Implement rate limiting+- Monitor for suspicious activity++**DON'T**:+- Use HTTP for API calls+- Disable SSL verification+- Ignore security warnings++---++## FAQ Expansion++### General Questions++**Q: What is Semantica?**+A: Semantica is a comprehensive framework for building knowledge graphs and semantic applications. It provides tools for entity extraction, relationship extraction, graph construction, and more.++**Q: Do I need to know graph theory?**+A: No, but basic understanding helps. Semantica abstracts away most complexity.++**Q: Is Semantica free?**+A: Yes, Semantica is open source. However, some features require paid API access (e.g., OpenAI for embeddings).++### Technical Questions++**Q: What Python version do I need?**+A: Python 3.8 or higher.++**Q: Can I use Semantica without external APIs?**+A: Yes, but with limited functionality. You can use local models for some operations.++**Q: How do I handle large datasets?**+A: Use batch processing, graph stores (Neo4j, KuzuDB), and parallel execution.++**Q: Can I customize entity extraction?**+A: Yes, you can create custom extractors by extending `BaseExtractor`.++### Performance Questions++**Q: How fast is Semantica?**+A: Depends on your setup. With proper optimization, it can process thousands of documents per hour.++**Q: How much memory does it use?**+A: Varies by graph size. Use graph stores for large graphs to reduce memory usage.++**Q: Can I use GPU acceleration?**+A: Yes, for some operations like embeddings. Install with `pip install semantica[gpu]`.++### Integration Questions++**Q: Can I use Semantica with other tools?**+A: Yes, Semantica exports to many formats (JSON, RDF, CSV, OWL) and integrates with various databases.++**Q: Does Semantica work with LangChain?**+A: Yes, you can integrate Semantica with LangChain for RAG applications.++**Q: Can I use Semantica in production?**+A: Yes, Semantica is designed for production use with proper configuration and monitoring.++----### Contributing+## Glossary Quick Reference-Want to contribute? See our [Contributing Guide](https://github.com/Hawksight-AI/semantica/blob/main/CONTRIBUTING.md).+Quick reference for common terms. See [Full Glossary](glossary.md) for complete definitions.-### Examples Repository+| Term | Definition |+| :--- | :--- |+| **Entity** | A distinct object or concept (person, place, organization) |+| **Relationship** | A connection between entities |+| **Knowledge Graph** | A structured representation of entities and relationships |+| **Embedding** | A vector representation of text or data |+| **NER** | Named Entity Recognition - identifying entities in text |+| **GraphRAG** | Graph-Augmented Retrieval Augmented Generation |+| **Ontology** | A formal specification of concepts and relationships |+| **Temporal Graph** | A knowledge graph that tracks changes over time |+| **Deduplication** | Identifying and merging duplicate entities |+| **Conflict Resolution** | Handling contradictory information |-Check out the [examples repository](https://github.com/Hawksight-AI/semantica/tree/main/examples) for more code samples.+**See Also**: [Full Glossary](glossary.md) | [Core Concepts](concepts.md)-## Related Projects+---++## Additional Resources++### Video Tutorials++Coming soon! We're working on video tutorials covering:+- Getting started with Semantica+- Building your first knowledge graph+- Advanced techniques and patterns+- Real-world use cases++### Blog Posts & Articles-### GraphRAG+Stay tuned for blog posts covering:+- Best practices for knowledge graph construction+- Performance optimization tips+- Integration guides+- Case studies and success stories++### Community Resources-Semantica works great with GraphRAG implementations. See our [GraphRAG examples](cookbook.md#advanced-rag).+**GitHub Discussions**:+- [General Discussion](https://github.com/Hawksight-AI/semantica/discussions)+- [Q&A](https://github.com/Hawksight-AI/semantica/discussions/categories/q-a)+- [Show and Tell](https://github.com/Hawksight-AI/semantica/discussions/categories/show-and-tell)-### Vector Databases+**Contributing**:+- [Contributing Guide](https://github.com/Hawksight-AI/semantica/blob/main/CONTRIBUTING.md)+- [Examples Repository](https://github.com/Hawksight-AI/semantica/tree/main/examples)-Integrate with vector databases:-- Pinecone-- Weaviate-- Qdrant-- Milvus+### Related Projects-### Knowledge Graph Databases+**GraphRAG**: Semantica works great with GraphRAG implementations. See our [GraphRAG examples](cookbook.md#advanced-rag).-Export to and work with:-- Neo4j-- Amazon Neptune-- ArangoDB-- Blazegraph+**Vector Databases**: Integrate with Pinecone, Weaviate, Qdrant, Milvus.++**Knowledge Graph Databases**: Export to Neo4j, Amazon Neptune, ArangoDB, Blazegraph.++---## Next Steps- **[Deep Dive](deep-dive.md)** - Advanced architecture and internals-- **[API Reference](api.md)** - Complete API documentation+- **[API Reference](reference/core.md)** - Complete API documentation- **[Cookbook](cookbook.md)** - Interactive tutorials- **[Examples](examples.md)** - More code examples+- **[Use Cases](use-cases.md)** - Real-world applications----Have questions or suggestions? [Open an issue](https://github.com/Hawksight-AI/semantica/issues) or [start a discussion](https://github.com/Hawksight-AI/semantica/discussions)!+!!! info "Contribute"+ Have questions or suggestions? [Open an issue](https://github.com/Hawksight-AI/semantica/issues) or [start a discussion](https://github.com/Hawksight-AI/semantica/discussions)!+**Last Updated**: 2024diff --git a/docs/modules.md b/docs/modules.mdindex 305d8f52..b1f4be58 100644--- a/docs/modules.md+++ b/docs/modules.md@@ -2,310 +2,685 @@Semantica is built with a modular architecture, designed to be flexible and extensible. This guide provides an overview of the key modules and their responsibilities.-## ποΈ Architecture Overview+!!! info "About This Guide"+ This guide covers all 13 core modules in Semantica, their purposes, architecture, usage patterns, and how they integrate together.-The framework is organized into several core layers, each handling specific aspects of the semantic processing pipeline.+---++## Table of Contents++- [Prerequisites](#prerequisites)+- [Module Dependency Diagram](#module-dependency-diagram)+- [Module Selection Guide](#module-selection-guide)+- [Core Modules](#core-modules)+- [Integration Patterns](#integration-patterns)+- [Performance Considerations](#performance-considerations)++---++## Prerequisites++Before reading this guide, you should:++- Understand basic Python programming+- Be familiar with the [Core Concepts](concepts.md)+- Have Semantica installed (see [Installation Guide](installation.md))+- Understand basic data structures and algorithms++---++## Module Dependency Diagram++The following diagram shows how modules depend on and interact with each other:```mermaid-graph TD- subgraph Ingest [Ingestion Layer]- I[Ingest Module] --> P[Parse Module]- P --> N[Normalize Module]+graph TB+ subgraph Input["Input Layer"]+ Ingest[Ingest Module]+ Parse[Parse Module]+ Norm[Normalize Module]end-- subgraph Core [Core Processing]- N --> SE[Semantic Extract]- SE --> KG[Knowledge Graph]- KG --> O[Ontology]++ subgraph Core["Core Processing"]+ Extract[Semantic Extract]+ KG[Knowledge Graph]+ Onto[Ontology]end-- subgraph Storage [Storage Layer]- KG --> VS[Vector Store]- KG --> TS[Triple Store]- KG --> GS[Graph Store]++ subgraph Storage["Storage Layer"]+ VS[Vector Store]+ TS[Triple Store]+ GS[Graph Store]end-- subgraph Output [Output & Analysis]- KG --> E[Export]- KG --> V[Visualization]- KG --> R[Reasoning]++ subgraph Output["Output Layer"]+ Export[Export Module]+ Viz[Visualization]+ Reason[Reasoning]end+ subgraph Support["Support Modules"]+ Embed[Embeddings]+ Pipeline[Pipeline]+ end++ Ingest --> Parse+ Parse --> Norm+ Norm --> Extract+ Extract --> KG+ KG --> Onto+ KG --> VS+ KG --> TS+ KG --> GS+ Extract --> Embed+ Embed --> VS+ KG --> Export+ KG --> Viz+ KG --> Reason+ Onto --> KG+ Pipeline --> Ingest+ Pipeline --> Parse+ Pipeline --> Extract+ Pipeline --> KG+style Ingest fill:#e1f5fe,stroke:#01579b- style Core fill:#e8f5e9,stroke:#1b5e20- style Storage fill:#fff3e0,stroke:#e65100- style Output fill:#f3e5f5,stroke:#4a148c+ style Extract fill:#e8f5e9,stroke:#1b5e20+ style KG fill:#fff3e0,stroke:#ef6c00,stroke-width:3px+ style VS fill:#f3e5f5,stroke:#7b1fa2+ style Pipeline fill:#ffebee,stroke:#c62828+```++---++## Module Selection Guide++Use this flowchart to determine which modules you need for your use case:++```mermaid+flowchart TD+ Start[What do you want to do?] --> Q1{Process Documents?}+ Q1 -->|Yes| Ingest[Ingest, Parse, Normalize]+ Q1 -->|No| Q2{Extract Knowledge?}++ Q2 -->|Yes| Extract[Semantic Extract, KG]+ Q2 -->|No| Q3{Store Data?}++ Q3 -->|Vectors| VS[Embeddings, Vector Store]+ Q3 -->|Graph| GS[Graph Store]+ Q3 -->|Triples| TS[Triple Store]+ Q3 -->|No| Q4{Visualize?}++ Q4 -->|Yes| Viz[Visualization]+ Q4 -->|No| Q5{Export?}++ Q5 -->|Yes| Export[Export]+ Q5 -->|No| Q6{Reason/Infer?}++ Q6 -->|Yes| Reason[Reasoning]+ Q6 -->|No| Onto[Ontology]++ style Ingest fill:#e1f5fe+ style Extract fill:#e8f5e9+ style VS fill:#f3e5f5+ style GS fill:#fff3e0```----## π¦ Core Modules+## Core ModulesSemantica is organized into 13 core modules. Below is a detailed breakdown of each.### 1. Ingest Module-**Purpose**: Ingest data from various sources into a unified format.-The `ingest` module is the entry point for data. It handles the complexity of connecting to different data sources, from local files to web streams, and supports connecting to your own MCP (Model Context Protocol) servers.+!!! abstract "Purpose"+ The `ingest` module is the entry point for data ingestion. It handles the complexity of connecting to different data sources, from local files to web streams, and supports connecting to your own MCP (Model Context Protocol) servers.-- **Components**:- - `FileIngestor`: Read files (PDF, DOCX, HTML, JSON, CSV, etc.)- - `WebIngestor`: Scrape and ingest web pages- - `FeedIngestor`: Process RSS/Atom feeds- - `StreamIngestor`: Real-time data streaming- - `DBIngestor`: Database queries and ingestion- - `EmailIngestor`: Process email messages- - `RepoIngestor`: Git repository analysis- - `MCPIngestor`: Connect to your own Python/FastMCP MCP servers via URL for resource and tool-based data ingestion+**Key Features**:-```mermaid-classDiagram- class BaseIngestor {- +ingest(source)- +validate(source)- }- class FileIngestor {- +supported_formats: List- +ingest_file(path)- }- class WebIngestor {- +scrape(url)- +extract_metadata(html)- }- BaseIngestor <|-- FileIngestor- BaseIngestor <|-- WebIngestor-```+- Support for 50+ file formats (PDF, DOCX, HTML, JSON, CSV, etc.)+- Web scraping with JavaScript rendering+- Database integration (SQL, NoSQL)+- Real-time streaming support+- MCP server integration+- Batch processing capabilities+- Metadata extraction++**Input/Output Specification**:++| Input | Type | Description |+| :--------- | :---------------- | :----------------------------------- |+| `source` | `str`, `Path`, `List` | File path, URL, directory, or list of sources |+| `recursive`| `bool` | Whether to recursively scan directories |+| `filters` | `Dict` | Filters for file types, sizes, etc. |++| Output | Type | Description |+| :--------- | :---------------- | :----------------------------------- |+| `documents`| `List[Document]` | List of Document objects with content and metadata |+| `metadata` | `Dict` | Source metadata (paths, timestamps, formats) |++**Components**:++- `FileIngestor`: Read files (PDF, DOCX, HTML, JSON, CSV, etc.)+- `WebIngestor`: Scrape and ingest web pages+- `FeedIngestor`: Process RSS/Atom feeds+- `StreamIngestor`: Real-time data streaming+- `DBIngestor`: Database queries and ingestion+- `EmailIngestor`: Process email messages+- `RepoIngestor`: Git repository analysis+- `MCPIngestor`: Connect to your own Python/FastMCP MCP servers via URL for resource and tool-based data ingestion++**Complete Code Example**:```python-from semantica.ingest import FileIngestor, WebIngestor+from semantica.ingest import FileIngestor, WebIngestor, DBIngestor, MCPIngestor-# Ingest local files+# Example 1: Ingest local filesfile_ingestor = FileIngestor()-documents = file_ingestor.ingest("data/") # (1)+documents = file_ingestor.ingest("data/", recursive=True) # (1)+print(f"Ingested {len(documents)} documents")-# Ingest web content+# Example 2: Ingest web contentweb_ingestor = WebIngestor()-web_docs = web_ingestor.ingest("https://example.com") # (2)+web_docs = web_ingestor.ingest("https://example.com") # (2)+print(f"Web content: {web_docs[0].content[:100]}...")++# Example 3: Ingest from database+db_ingestor = DBIngestor(connection_string="postgresql://user:pass@localhost/db")+db_docs = db_ingestor.ingest("SELECT * FROM documents")++# Example 4: Ingest from MCP server+mcp_ingestor = MCPIngestor()+mcp_docs = mcp_ingestor.ingest("https://your-mcp-server.com")```-1. Recursively scans the directory for supported file types (PDF, DOCX, etc.) and converts them to standard Document objects.-2. Fetches the URL, renders JavaScript if necessary, and extracts the main content while stripping boilerplate.+1. Recursively scans the directory for supported file types (PDF, DOCX, etc.) and converts them to standard Document objects.+2. Fetches the URL, renders JavaScript if necessary, and extracts the main content while stripping boilerplate.-### 2. Parse Module-**Purpose**: Parse and extract content from various raw formats.+**Configuration Options**:-Once data is ingested, the `parse` module extracts the raw text and metadata. It supports a wide range of formats and includes OCR capabilities.+| Option | Type | Default | Description |+| :--------------| :---------- | :------ | :----------------------------------- |+| `recursive` | `bool` | `False` | Recursively scan directories |+| `file_filters` | `List[str]` | `None` | Filter by file extensions |+| `max_file_size`| `int` | `None` | Maximum file size in bytes |+| `timeout` | `int` | `30` | Request timeout in seconds |+| `user_agent` | `str` | `None` | Custom user agent for web requests |-- **Components**:- - `DocumentParser`: Main parser orchestrator- - `PDFParser`: Extract text, tables, images from PDFs- - `DOCXParser`: Parse Word documents- - `HTMLParser`: Extract content from HTML- - `JSONParser`: Parse structured JSON data- - `ExcelParser`: Process spreadsheets- - `ImageParser`: OCR and image analysis- - `CodeParser`: Parse source code files+**Common Use Cases**:-```mermaid-classDiagram- class DocumentParser {- +parse(documents)- +register_parser(format, parser)- }- class PDFParser {- +extract_text()- +extract_tables()- }- class JSONParser {- +flatten()- +extract_schema()- }- DocumentParser *-- PDFParser- DocumentParser *-- JSONParser-```+- Processing document collections+- Scraping websites for content+- Extracting data from databases+- Processing email archives+- Real-time data streaming+- Integrating with MCP servers++**API Reference**: [Ingest Module](reference/ingest.md)++### 2. Parse Module++!!! abstract "Purpose"+ Once data is ingested, the `parse` module extracts the raw text and metadata. It supports a wide range of formats and includes OCR capabilities.++**Key Features**:+- 50+ file format support+- OCR for images and scanned documents+- Table extraction from PDFs and spreadsheets+- Metadata preservation+- Automatic format detection+- Structured data parsing (JSON, CSV, XML)++**Input/Output Specification**:++| Input | Type | Description |+| :------------- | :-------------------- | :----------------------------------- |+| `documents` | `List[Document]` | Documents from ingest module |+| `ocr_enabled` | `bool` | Enable OCR for images |++| Output | Type | Description |+| :------------- | :-------------------- | :----------------------------------- |+| `parsed_docs` | `List[ParsedDocument]`| Documents with extracted text and metadata |+| `tables` | `List[Table]` | Extracted tables (if any) |++**Components**:+- `DocumentParser`: Main parser orchestrator+- `PDFParser`: Extract text, tables, images from PDFs+- `DOCXParser`: Parse Word documents+- `HTMLParser`: Extract content from HTML+- `JSONParser`: Parse structured JSON data+- `ExcelParser`: Process spreadsheets+- `ImageParser`: OCR and image analysis+- `CodeParser`: Parse source code files++**Complete Code Example**:```pythonfrom semantica.parse import DocumentParser-parser = DocumentParser()-parsed_docs = parser.parse(documents) # (1)+parser = DocumentParser(ocr_enabled=True)+parsed_docs = parser.parse(documents) # (1)++# Access parsed content+for doc in parsed_docs:+ print(f"Content: {doc.content[:100]}...")+ print(f"Metadata: {doc.metadata}")+ if doc.tables:+ print(f"Found {len(doc.tables)} tables")```-1. Automatically detects the file type of each document and routes it to the appropriate specialized parser (e.g., PDFParser for .pdf).+1. Automatically detects the file type of each document and routes it to the appropriate specialized parser (e.g., PDFParser for .pdf).++**Configuration Options**:++| Option | Type | Default | Description |+| :-------------- | :----- | :------ | :------------------------------- |+| `ocr_enabled` | `bool` | `False` | Enable OCR for images |+| `extract_tables`| `bool` | `True` | Extract tables from documents |+| `extract_images`| `bool` | `False` | Extract and process images |++**Common Use Cases**:+- Extracting text from PDFs+- Parsing spreadsheets+- OCR from scanned documents+- Extracting web content+- Parsing code repositories++**API Reference**: [Parse Module](reference/parse.md)### 3. Normalize Module-**Purpose**: Clean and normalize text for processing.-Raw text is often noisy. The `normalize` module cleans, standardizes, and prepares text for semantic extraction.+!!! abstract "Purpose"+ Raw text is often noisy. The `normalize` module cleans, standardizes, and prepares text for semantic extraction.++**Key Features**:+- Text cleaning and noise removal+- Encoding normalization+- Entity name standardization+- Date and number formatting+- Language detection+- Unicode normalization-- **Components**:- - `TextNormalizer`: Main normalization orchestrator- - `TextCleaner`: Remove noise, fix encoding- - `DataCleaner`: Clean structured data- - `EntityNormalizer`: Normalize entity names- - `DateNormalizer`: Standardize date formats- - `NumberNormalizer`: Normalize numeric values- - `LanguageDetector`: Detect document language- - `EncodingHandler`: Handle character encoding+**Input/Output Specification**:++| Input | Type | Description |+| :----------------- | :---------------------- | :----------------------------------- |+| `documents` | `List[ParsedDocument]` | Parsed documents |+| `normalize_entities`| `bool` | Normalize entity names |++| Output | Type | Description |+| :------------- | :---------------------- | :----------------------------------- |+| `normalized_docs`| `List[NormalizedDocument]`| Cleaned and normalized documents |++**Components**:+- `TextNormalizer`: Main normalization orchestrator+- `TextCleaner`: Remove noise, fix encoding+- `DataCleaner`: Clean structured data+- `EntityNormalizer`: Normalize entity names+- `DateNormalizer`: Standardize date formats+- `NumberNormalizer`: Normalize numeric values+- `LanguageDetector`: Detect document language+- `EncodingHandler`: Handle character encoding++**Complete Code Example**:```pythonfrom semantica.normalize import TextNormalizer-normalizer = TextNormalizer()+normalizer = TextNormalizer(+ normalize_entities=True,+ normalize_dates=True,+ detect_language=True+)normalized = normalizer.normalize(parsed_docs)++# Check normalization results+for doc in normalized:+ print(f"Language: {doc.language}")+ print(f"Normalized text: {doc.content[:100]}...")```+**Configuration Options**:++| Option | Type | Default | Description |+| :----------------- | :----- | :------ | :--------------------------- |+| `normalize_entities` | `bool` | `True` | Normalize entity names |+| `normalize_dates` | `bool` | `True` | Standardize date formats |+| `normalize_numbers` | `bool` | `True` | Normalize numeric values |+| `detect_language` | `bool` | `False` | Detect document language |++**Common Use Cases**:+- Cleaning noisy text data+- Standardizing date formats+- Normalizing entity names+- Multi-language support+- Number format standardization++**API Reference**: [Normalize Module](reference/normalize.md)+### 4. Semantic Extract Module-**Purpose**: Extract entities, relationships, and semantic information.-This is the brain of the operation. It uses LLMs and NLP techniques to understand the text and extract structured knowledge.+!!! abstract "Purpose"+ This is the brain of the operation. It uses LLMs and NLP techniques to understand the text and extract structured knowledge.++**Key Features**:+- Multiple NER methods (rule-based, ML, LLM)+- Relationship extraction+- Semantic analysis+- Custom entity types+- Confidence scoring+- Multi-language support++**Input/Output Specification**:++| Input | Type | Description |+| :------------- | :------------------------ | :----------------------------------- |+| `documents` | `List[NormalizedDocument]`| Normalized documents |+| `entity_types` | `List[str]` | Custom entity types to extract |+| `method` | `str` | Extraction method (rule/ml/llm) |++| Output | Type | Description |+| :------------- | :------------------ | :----------------------------------- |+| `entities` | `List[Entity]` | Extracted entities with types and confidence |+| `relationships`| `List[Relationship]`| Extracted relationships |++**Components**:+- `NERExtractor`: Named Entity Recognition+- `RelationExtractor`: Extract relationships between entities+- `SemanticAnalyzer`: Deep semantic analysis+- `SemanticNetworkExtractor`: Extract semantic networks-- **Components**:- - `NERExtractor`: Named Entity Recognition- - `RelationExtractor`: Extract relationships between entities- - `SemanticAnalyzer`: Deep semantic analysis- - `SemanticNetworkExtractor`: Extract semantic networks+**Complete Code Example**:```pythonfrom semantica.semantic_extract import NERExtractor, RelationExtractor# Extract entities-extractor = NERExtractor()+extractor = NERExtractor(method="llm", model="gpt-4")entities = extractor.extract(normalized_docs)+print(f"Extracted {len(entities)} entities")+for entity in entities[:5]:+ print(f" - {entity.text} ({entity.label}) - Confidence: {entity.confidence:.2f}")+# Extract relationshipsrelation_extractor = RelationExtractor()-relationships = relation_extractor.extract(normalized_docs, entities)+relationships = relation_extractor.extract(normalized_docs, entities=entities)++print(f"\nExtracted {len(relationships)} relationships")+for rel in relationships[:5]:+ print(f" {rel.subject.text} --[{rel.predicate}]--> {rel.object.text}")```+**Configuration Options**:++| Option | Type | Default | Description |+| :-------------------- | :---------- | :------ | :------------------------------- |+| `method` | `str` | `"ml"` | Extraction method (rule/ml/llm) |+| `model` | `str` | `None` | Model name for ML/LLM methods |+| `confidence_threshold`| `float` | `0.5` | Minimum confidence score |+| `custom_entity_types`| `List[str]` | `[]` | Custom entity types |++**Common Use Cases**:+- Named entity recognition+- Relationship extraction+- Semantic analysis+- Knowledge extraction+- Information extraction++**API Reference**: [Semantic Extract Module](reference/semantic_extract.md)+### 5. Knowledge Graph (KG) Module-**Purpose**: Build and manage knowledge graphs.--The `kg` module constructs the graph from extracted entities and relationships, handling complex tasks like resolution and analysis.--- **Components**:- - `GraphBuilder`: Construct knowledge graphs from entities/relationships- - `GraphAnalyzer`: Analyze graph structure and properties- - `GraphValidator`: Validate graph quality and consistency- - `EntityResolver`: Resolve entity conflicts and duplicates- - `ConflictDetector`: Detect conflicting information- - `CentralityCalculator`: Calculate node importance metrics- - `CommunityDetector`: Detect communities in graphs- - `ConnectivityAnalyzer`: Analyze graph connectivity- - `TemporalQuery`: Query temporal knowledge graphs- - `Deduplicator`: Remove duplicate entities/relationships-```mermaid-classDiagram- class GraphBuilder {- +build(entities, relations)- +merge_nodes()- }- class GraphAnalyzer {- +compute_centrality()- +detect_communities()- }- class KnowledgeGraph {- +nodes: List- +edges: List- +query(cypher)- }- GraphBuilder ..> KnowledgeGraph : Creates- GraphAnalyzer ..> KnowledgeGraph : Analyzes-```+!!! abstract "Purpose"+ The `kg` module constructs the graph from extracted entities and relationships, handling complex tasks like resolution and analysis.++**Key Features**:+- Graph construction from entities/relationships+- Multiple backend support (NetworkX, Neo4j, KuzuDB)+- Temporal graph support+- Graph analytics and metrics+- Conflict detection and resolution+- Entity deduplication+- Community detection+- Centrality calculations++**Input/Output Specification**:++| Input | Type | Description |+| :------------- | :------------------ | :----------------------------------- |+| `entities` | `List[Entity]` | Extracted entities |+| `relationships`| `List[Relationship]`| Extracted relationships |+| `backend` | `str` | Graph backend (networkx/neo4j/kuzu) |++| Output | Type | Description |+| :------------- | :---------------- | :----------------------------------- |+| `knowledge_graph`| `KnowledgeGraph`| Constructed knowledge graph |+| `metrics` | `Dict` | Graph metrics (density, centrality, etc.) |++**Components**:+- `GraphBuilder`: Construct knowledge graphs from entities/relationships+- `GraphAnalyzer`: Analyze graph structure and properties+- `GraphValidator`: Validate graph quality and consistency+- `EntityResolver`: Resolve entity conflicts and duplicates+- `ConflictDetector`: Detect conflicting information+- `CentralityCalculator`: Calculate node importance metrics+- `CommunityDetector`: Detect communities in graphs+- `ConnectivityAnalyzer`: Analyze graph connectivity+- `TemporalQuery`: Query temporal knowledge graphs+- `Deduplicator`: Remove duplicate entities/relationships++**Complete Code Example**:```pythonfrom semantica.kg import GraphBuilder, GraphAnalyzer# Build graph-builder = GraphBuilder()-kg = builder.build(entities, relationships) # (1)+builder = GraphBuilder(backend="networkx", temporal=True)+kg = builder.build(entities, relationships) # (1)# Analyze graphanalyzer = GraphAnalyzer()-metrics = analyzer.analyze(kg) # (2)+metrics = analyzer.analyze(kg) # (2)++print(f"Nodes: {metrics['nodes']}")+print(f"Edges: {metrics['edges']}")+print(f"Density: {metrics['density']:.3f}")+print(f"Communities: {metrics['communities']}")```-1. Constructs a NetworkX or Neo4j graph from the extracted entities and relationships, handling node merging and edge attributes.-2. Computes graph-theoretic metrics like density, diameter, and centrality to assess the quality and structure of the knowledge graph.+1. Constructs a NetworkX or Neo4j graph from the extracted entities and relationships, handling node merging and edge attributes.+2. Computes graph-theoretic metrics like density, diameter, and centrality to assess the quality and structure of the knowledge graph.-### 6. Embeddings Module-**Purpose**: Generate vector embeddings for various data types.+**Configuration Options**:++| Option | Type | Default | Description |+| :---------------- | :----- | :------------ | :----------------------------------- |+| `backend` | `str` | `"networkx"` | Graph backend (networkx/neo4j/kuzu) |+| `temporal` | `bool` | `False` | Enable temporal graph support |+| `merge_duplicates`| `bool` | `True` | Automatically merge duplicate entities|-Embeddings are crucial for semantic search. This module generates vectors for text, images, and graph nodes.+**Common Use Cases**:+- Building knowledge graphs+- Graph analytics+- Community detection+- Temporal analysis+- Relationship modeling-- **Components**:- - `EmbeddingGenerator`: Main embedding orchestrator- - `TextEmbedder`: Generate text embeddings- - `ImageEmbedder`: Generate image embeddings- - `AudioEmbedder`: Generate audio embeddings- - `MultimodalEmbedder`: Combine multiple modalities- - `EmbeddingOptimizer`: Optimize embedding quality- - `ProviderAdapters`: Support for OpenAI, Cohere, etc.+**API Reference**: [Knowledge Graph Module](reference/kg.md)++### 6. Embeddings Module++!!! abstract "Purpose"+ Embeddings are crucial for semantic search. This module generates vectors for text, images, and graph nodes.++**Key Features**:+- Multiple provider support (OpenAI, Cohere, HuggingFace)+- Text, image, and audio embeddings+- Multimodal embeddings+- Batch processing+- Caching support+- Custom models++**Input/Output Specification**:++| Input | Type | Description |+| :-------- | :------------ | :----------------------------------- |+| `texts` | `List[str]` | Text to embed |+| `provider`| `str` | Embedding provider (openai/cohere/hf)|+| `model` | `str` | Model name |++| Output | Type | Description |+| :--------- | :------------ | :----------------------------------- |+| `embeddings`| `np.ndarray` | Array of embedding vectors |+| `metadata` | `Dict` | Embedding metadata |++**Components**:+- `EmbeddingGenerator`: Main embedding orchestrator+- `TextEmbedder`: Generate text embeddings+- `ImageEmbedder`: Generate image embeddings+- `AudioEmbedder`: Generate audio embeddings+- `MultimodalEmbedder`: Combine multiple modalities+- `EmbeddingOptimizer`: Optimize embedding quality+- `ProviderAdapters`: Support for OpenAI, Cohere, etc.++**Complete Code Example**:```pythonfrom semantica.embeddings import EmbeddingGenerator-generator = EmbeddingGenerator()+generator = EmbeddingGenerator(+ provider="openai",+ model="text-embedding-3-small"+)embeddings = generator.generate(documents)++# Calculate similarity+similarity = generator.similarity(embeddings[0], embeddings[1])+print(f"Similarity: {similarity:.3f}")```+**Configuration Options**:++| Option | Type | Default | Description |+| :---------- | :----- | :---------- | :--------------------------- |+| `provider` | `str` | `"openai"` | Embedding provider |+| `model` | `str` | `None` | Model name |+| `batch_size`| `int` | `100` | Batch size for processing |+| `cache` | `bool` | `True` | Enable caching |++**Common Use Cases**:+- Semantic search+- Similarity calculation+- RAG applications+- Clustering and classification++**API Reference**: [Embeddings Module](reference/embeddings.md)+### 7. Vector Store Module-**Purpose**: Store and search vector embeddings.-Manages the storage and retrieval of high-dimensional vectors, supporting hybrid search strategies.+!!! abstract "Purpose"+ Manages the storage and retrieval of high-dimensional vectors, supporting hybrid search strategies.++**Key Features**:+- Multiple backend support (FAISS, Pinecone, Weaviate)+- Hybrid search (vector + keyword)+- Metadata filtering+- Batch operations+- Similarity search+- Index management++**Input/Output Specification**:++| Input | Type | Description |+| :--------- | :---------------- | :----------------------------------- |+| `embeddings`| `np.ndarray` | Vector embeddings |+| `documents` | `List[Document]` | Associated documents |+| `metadata` | `Dict` | Metadata for filtering |-- **Components**:- - `VectorStore`: Main vector store interface- - `FAISSAdapter`: FAISS integration- - `HybridSearch`: Combine vector and keyword search- - `VectorRetriever`: Retrieve relevant vectors+| Output | Type | Description |+| :------- | :------------------ | :----------------------------------- |+| `results`| `List[SearchResult]`| Search results with scores |++**Components**:+- `VectorStore`: Main vector store interface+- `FAISSAdapter`: FAISS integration+- `HybridSearch`: Combine vector and keyword search+- `VectorRetriever`: Retrieve relevant vectors++**Complete Code Example**:```pythonfrom semantica.vector_store import VectorStore, HybridSearch-vector_store = VectorStore()+vector_store = VectorStore(backend="faiss")vector_store.store(embeddings, documents, metadata)+# Hybrid searchhybrid_search = HybridSearch(vector_store)-results = hybrid_search.search(query, top_k=10)+results = hybrid_search.search(+ query="machine learning",+ top_k=10,+ filters={"category": "AI"}+)++for result in results:+ print(f"Score: {result.score:.3f} - {result.document.content[:50]}...")```-### 8. Graph Store Module-**Purpose**: Store and query property graphs with multiple backend support.+**Configuration Options**:-The `graph_store` module provides integration with property graph databases like Neo4j, KuzuDB, and FalkorDB for storing and querying knowledge graphs.+| Option | Type | Default | Description |+| :------------- | :----- | :-------- | :--------------------------- |+| `backend` | `str` | `"faiss"` | Vector store backend |+| `index_type` | `str` | `"flat"` | FAISS index type |+| `hybrid_search`| `bool` | `True` | Enable hybrid search |-- **Components**:- - `GraphStore`: Main graph store interface- - `Neo4jAdapter`: Neo4j database integration- - `KuzuAdapter`: KuzuDB embedded database integration- - `FalkorDBAdapter`: FalkorDB (Redis-based) integration- - `NodeManager`: Node CRUD operations- - `RelationshipManager`: Relationship CRUD operations- - `QueryEngine`: Cypher query execution- - `GraphAnalytics`: Graph algorithms and analytics+**Common Use Cases**:+- Semantic search+- Document retrieval+- RAG applications+- Similarity matching-```mermaid-classDiagram- class GraphStore {- +create_node(labels, properties)- +create_relationship(start, end, type)- +execute_query(cypher)- +shortest_path(start, end)- }- class Neo4jAdapter {- +connect()- +execute_query()- +create_index()- }- class FalkorDBAdapter {- +select_graph()- +query()- }- GraphStore *-- Neo4jAdapter- GraphStore *-- FalkorDBAdapter-```+**API Reference**: [Vector Store Module](reference/vector_store.md)++### 8. Graph Store Module++!!! abstract "Purpose"+ The `graph_store` module provides integration with property graph databases like Neo4j, KuzuDB, and FalkorDB for storing and querying knowledge graphs.++**Key Features**:+- Multiple backend support (Neo4j, KuzuDB, FalkorDB)+- Cypher query language+- Graph algorithms and analytics+- Transaction support+- Index management+- High-performance queries++**Input/Output Specification**:++| Input | Type | Description |+| :------------- | :----- | :----------------------------------- |+| `backend` | `str` | Backend (neo4j/kuzu/falkordb) |+| `connection_uri`| `str` | Database connection URI |+| `cypher_query` | `str` | Cypher query string |++| Output | Type | Description |+| :------- | :----- | :----------------------------------- |+| `result` | `Dict` | Query results |+| `node_id`| `str` | Created node ID |++**Components**:+- `GraphStore`: Main graph store interface+- `Neo4jAdapter`: Neo4j database integration+- `KuzuAdapter`: KuzuDB embedded database integration+- `FalkorDBAdapter`: FalkorDB (Redis-based) integration+- `NodeManager`: Node CRUD operations+- `RelationshipManager`: Relationship CRUD operations+- `QueryEngine`: Cypher query execution+- `GraphAnalytics`: Graph algorithms and analytics++**Complete Code Example**:```pythonfrom semantica.graph_store import GraphStore, create_node, create_relationship@@ -321,109 +696,548 @@ bob = store.create_node(["Person"], {"name": "Bob", "age": 25})# Create relationshipstore.create_relationship(alice["id"], bob["id"], "KNOWS", {"since": 2020})-# Query+# Query with Cypherresults = store.execute_query("MATCH (p:Person) RETURN p.name")+print(f"Found {len(results)} people")++# Graph analytics+path = store.shortest_path(alice["id"], bob["id"])+print(f"Shortest path: {path}")# Or use convenience functionsnode = create_node(labels=["Entity"], properties={"name": "Test"})```+**Configuration Options**:++| Option | Type | Default | Description |+| :--------- | :----- | :-------- | :--------------------------- |+| `backend` | `str` | `"neo4j"` | Graph database backend |+| `uri` | `str` | `None` | Database connection URI |+| `database` | `str` | `"neo4j"` | Database name |++**Common Use Cases**:+- Persistent graph storage+- Complex graph queries+- Graph analytics+- Production deployments+- High-performance applications++**API Reference**: [Graph Store Module](reference/graph_store.md)+### 9. Reasoning Module-**Purpose**: Perform logical inference and reasoning.-Goes beyond simple retrieval to infer new facts and validate existing knowledge using logical rules.+!!! abstract "Purpose"+ Goes beyond simple retrieval to infer new facts and validate existing knowledge using logical rules.++**Key Features**:+- Forward and backward chaining+- Rule-based inference+- Deductive and abductive reasoning+- Explanation generation+- RETE algorithm support+- Custom rule definition++**Input/Output Specification**:++| Input | Type | Description |+| :-------------- | :------------------ | :----------------------------------- |+| `knowledge_graph`| `KnowledgeGraph` | Input knowledge graph |+| `rules` | `List[Rule]` | Inference rules |+| `method` | `str` | Reasoning method |-- **Components**:- - `InferenceEngine`: Main inference orchestrator- - `RuleManager`: Manage inference rules- - `DeductiveReasoner`: Deductive reasoning- - `AbductiveReasoner`: Abductive reasoning- - `ExplanationGenerator`: Generate explanations for inferences- - `RETEEngine`: RETE algorithm for rule matching+| Output | Type | Description |+| :------------ | :------------------ | :----------------------------------- |+| `new_facts` | `List[Fact]` | Inferred facts |+| `explanations`| `List[Explanation]` | Reasoning explanations |++**Components**:+- `InferenceEngine`: Main inference orchestrator+- `RuleManager`: Manage inference rules+- `DeductiveReasoner`: Deductive reasoning+- `AbductiveReasoner`: Abductive reasoning+- `ExplanationGenerator`: Generate explanations for inferences+- `RETEEngine`: RETE algorithm for rule matching++**Complete Code Example**:```pythonfrom semantica.reasoning import InferenceEngine, RuleManagerinference_engine = InferenceEngine()rule_manager = RuleManager()++# Define rules+rules = [+ "IF Person worksFor Company AND Company locatedIn City THEN Person livesIn City",+ "IF Person hasFriend Person2 AND Person2 hasFriend Person3 THEN Person knows Person3"+]++rule_manager.add_rules(rules)++# Perform inferencenew_facts = inference_engine.forward_chain(kg, rule_manager)+print(f"Inferred {len(new_facts)} new facts")++# Get explanations+for fact in new_facts:+ explanation = inference_engine.explain(fact)+ print(f"{fact}: {explanation}")```+**Configuration Options**:++| Option | Type | Default | Description |+| :-------------- | :----- | :---------------- | :--------------------------- |+| `method` | `str` | `"forward_chain"` | Reasoning method |+| `max_iterations`| `int` | `100` | Maximum inference iterations |++**Common Use Cases**:+- Logical inference+- Fact discovery+- Knowledge validation+- Rule-based systems++**API Reference**: [Reasoning Module](reference/reasoning.md)+### 10. Ontology Module-**Purpose**: Generate and manage ontologies.-Defines the schema and structure of your knowledge domain, ensuring consistency and enabling interoperability.+!!! abstract "Purpose"+ Defines the schema and structure of your knowledge domain, ensuring consistency and enabling interoperability.++**Key Features**:+- Automatic ontology generation (6-stage pipeline)+- OWL/RDF export+- Class and property inference+- Ontology validation+- Symbolic reasoning (HermiT, Pellet)+- Version management++**Input/Output Specification**:++| Input | Type | Description |+| :-------------- | :---------------- | :----------------------------------- |+| `knowledge_graph`| `KnowledgeGraph` | Input knowledge graph |+| `base_uri` | `str` | Base URI for ontology |++| Output | Type | Description |+| :---------- | :---------- | :----------------------------------- |+| `ontology` | `Ontology` | Generated ontology |+| `owl_content`| `str` | OWL/Turtle format |++**Components**:+- `OntologyGenerator`: Generate ontologies from knowledge graphs+- `OntologyValidator`: Validate ontology structure+- `OWLGenerator`: Generate OWL format ontologies+- `PropertyGenerator`: Generate ontology properties+- `ClassInferrer`: Infer ontology classes-- **Components**:- - `OntologyGenerator`: Generate ontologies from knowledge graphs- - `OntologyValidator`: Validate ontology structure- - `OWLGenerator`: Generate OWL format ontologies- - `PropertyGenerator`: Generate ontology properties- - `ClassInferrer`: Infer ontology classes+**Complete Code Example**:```pythonfrom semantica.ontology import OntologyGenerator-generator = OntologyGenerator()+generator = OntologyGenerator(base_uri="https://example.org/ontology/")ontology = generator.generate_from_graph(kg)++# Validate ontology+validator = generator.validate(ontology)+print(f"Valid: {validator.is_valid}")++# Export to OWL+owl_content = generator.export_owl(ontology, format="turtle")+print(f"Generated {len(owl_content)} lines of OWL")```+**Configuration Options**:++| Option | Type | Default | Description |+| :-------- | :----- | :--------- | :--------------------------- |+| `base_uri`| `str` | `None` | Base URI for ontology |+| `reasoner`| `str` | `"hermit"` | Reasoner (hermit/pellet) |++**Common Use Cases**:+- Schema definition+- Data integration+- Consistency validation+- Semantic web applications++**API Reference**: [Ontology Module](reference/ontology.md)+### 11. Export Module-**Purpose**: Export data in various formats.-Allows you to take your knowledge graph and data out of Semantica for use in other tools.+!!! abstract "Purpose"+ Allows you to take your knowledge graph and data out of Semantica for use in other tools.++**Key Features**:+- Multiple export formats (JSON, RDF, CSV, OWL, GraphML)+- Custom export formats+- Batch export+- Metadata preservation+- Streaming export for large graphs-- **Components**:- - `JSONExporter`: Export to JSON- - `RDFExporter`: Export to RDF/XML- - `CSVExporter`: Export to CSV- - `GraphExporter`: Export to graph formats (GraphML, GEXF)- - `OWLExporter`: Export to OWL- - `VectorExporter`: Export vectors+**Input/Output Specification**:++| Input | Type | Description |+| :----------- | :---------------- | :----------------------------------- |+| `knowledge_graph`| `KnowledgeGraph`| Graph to export |+| `format` | `str` | Export format |+| `output_path`| `str` | Output file path |++| Output | Type | Description |+| :------------ | :----- | :----------------------------------- |+| `exported_file`| `str` | Path to exported file |+| `metadata` | `Dict` | Export metadata |++**Components**:+- `JSONExporter`: Export to JSON+- `RDFExporter`: Export to RDF/XML+- `CSVExporter`: Export to CSV+- `GraphExporter`: Export to graph formats (GraphML, GEXF)+- `OWLExporter`: Export to OWL+- `VectorExporter`: Export vectors++**Complete Code Example**:```python-from semantica.export import JSONExporter, RDFExporter+from semantica.export import JSONExporter, RDFExporter, CSVExporter+# Export to JSONjson_exporter = JSONExporter()json_exporter.export(kg, "output.json")++# Export to RDF+rdf_exporter = RDFExporter()+rdf_exporter.export(kg, "output.rdf")++# Export to CSV+csv_exporter = CSVExporter()+csv_exporter.export(kg, "output.csv")```+**Configuration Options**:++| Option | Type | Default | Description |+| :--------------- | :----- | :--------- | :--------------------------- |+| `format` | `str` | `"json"` | Export format |+| `include_metadata`| `bool`| `True` | Include metadata |+| `pretty_print` | `bool` | `False` | Pretty print JSON |++**Common Use Cases**:+- Data portability+- Integration with other tools+- Backup and archival+- Data analysis++**API Reference**: [Export Module](reference/export.md)+### 12. Visualization Module-**Purpose**: Visualize knowledge graphs and analytics.-Provides tools to visually explore your data, making it easier to understand complex relationships.+!!! abstract "Purpose"+ Provides tools to visually explore your data, making it easier to understand complex relationships.-- **Components**:- - `KGVisualizer`: Visualize knowledge graphs- - `EmbeddingVisualizer`: Visualize embeddings (t-SNE, PCA, UMAP)- - `QualityVisualizer`: Visualize quality metrics- - `AnalyticsVisualizer`: Visualize graph analytics- - `TemporalVisualizer`: Visualize temporal data+**Key Features**:+- Interactive graph visualization+- Embedding visualization (t-SNE, PCA, UMAP)+- Quality metrics visualization+- Temporal data visualization+- Multiple output formats (HTML, PNG, SVG)+- Custom styling-```python-from semantica.visualization import KGVisualizer+**Input/Output Specification**:++| Input | Type | Description |+| :-------------- | :---------------- | :----------------------------------- |+| `knowledge_graph`| `KnowledgeGraph` | Graph to visualize |+| `output_format` | `str` | Output format (html/png/svg) |+| `output_path` | `str` | Output file path |++| Output | Type | Description |+| :----------------- | :----- | :----------------------------------- |+| `visualization_file`| `str` | Path to visualization file |++**Components**:+- `KGVisualizer`: Visualize knowledge graphs+- `EmbeddingVisualizer`: Visualize embeddings (t-SNE, PCA, UMAP)+- `QualityVisualizer`: Visualize quality metrics+- `AnalyticsVisualizer`: Visualize graph analytics+- `TemporalVisualizer`: Visualize temporal data-visualizer = KGVisualizer()-visualizer.visualize(kg)+**Complete Code Example**:++```python+from semantica.visualization import KGVisualizer, EmbeddingVisualizer++# Visualize knowledge graph+kg_visualizer = KGVisualizer()+kg_visualizer.visualize(+ kg,+ output_format="html",+ output_path="graph.html"+)++# Visualize embeddings+embed_visualizer = EmbeddingVisualizer()+embed_visualizer.visualize(+ embeddings,+ method="tsne",+ output_path="embeddings.png"+)```+**Configuration Options**:++| Option | Type | Default | Description |+| :------------- | :----- | :--------- | :--------------------------- |+| `output_format`| `str` | `"html"` | Output format |+| `layout` | `str` | `"force"` | Graph layout algorithm |+| `max_nodes` | `int` | `1000` | Maximum nodes to visualize |++**Common Use Cases**:+- Graph exploration+- Data analysis+- Quality assessment+- Presentation and reporting++**API Reference**: [Visualization Module](reference/visualization.md)+### 13. Pipeline Module-**Purpose**: Build and execute processing pipelines.-Orchestrates the entire flow, connecting modules together into robust, executable workflows.+!!! abstract "Purpose"+ Orchestrates the entire flow, connecting modules together into robust, executable workflows.++**Key Features**:+- Pipeline construction DSL+- Parallel execution+- Error handling and recovery+- Resource scheduling+- Pipeline validation+- Monitoring and logging-- **Components**:- - `PipelineBuilder`: Build complex pipelines- - `ExecutionEngine`: Execute pipelines- - `FailureHandler`: Handle pipeline failures- - `ParallelismManager`: Enable parallel processing- - `ResourceScheduler`: Schedule resources+**Input/Output Specification**:++| Input | Type | Description |+| :-------- | :------------------ | :----------------------------------- |+| `steps` | `List[PipelineStep]`| Pipeline steps |+| `parallel`| `bool` | Enable parallel execution |++| Output | Type | Description |+| :------- | :---------------- | :----------------------------------- |+| `result` | `PipelineResult` | Execution result |+| `metrics`| `Dict` | Performance metrics |++**Components**:+- `PipelineBuilder`: Build complex pipelines+- `ExecutionEngine`: Execute pipelines+- `FailureHandler`: Handle pipeline failures+- `ParallelismManager`: Enable parallel processing+- `ResourceScheduler`: Schedule resources++**Complete Code Example**:```pythonfrom semantica.pipeline import PipelineBuilder+from semantica.ingest import FileIngestor+from semantica.parse import DocumentParser+from semantica.semantic_extract import NERExtractorbuilder = PipelineBuilder()-pipeline = builder.add_step("ingest", FileIngestor()) \- .add_step("parse", DocumentParser()) \- .build()+pipeline = builder \+ .add_step("ingest", FileIngestor()) \+ .add_step("parse", DocumentParser()) \+ .add_step("extract", NERExtractor()) \+ .build()++# Execute pipeline+result = pipeline.execute(sources=["data/"], parallel=True)+print(f"Processed {len(result.documents)} documents")+```++**Configuration Options**:++| Option | Type | Default | Description |+| :--------------- | :----- | :------ | :--------------------------- |+| `parallel` | `bool` | `False` | Enable parallel execution |+| `max_workers` | `int` | `4` | Maximum parallel workers |+| `retry_on_failure`| `bool`| `True` | Retry failed steps |++**Common Use Cases**:+- End-to-end workflows+- Performance optimization+- Error handling+- Batch processing++**API Reference**: [Pipeline Module](reference/pipeline.md)++---++## Integration Patterns++This section shows common patterns for integrating multiple modules together.++### Pattern 1: Complete Knowledge Graph Pipeline++```python+from semantica import Semantica++# High-level API - all modules integrated+semantica = Semantica()+result = semantica.build_knowledge_base(+ sources=["documents/"],+ embeddings=True,+ graph=True,+ normalize=True+)```++### Pattern 2: Custom Pipeline with Module Selection++```python+from semantica.ingest import FileIngestor+from semantica.parse import DocumentParser+from semantica.normalize import TextNormalizer+from semantica.semantic_extract import NERExtractor, RelationExtractor+from semantica.kg import GraphBuilder+from semantica.embeddings import EmbeddingGenerator+from semantica.vector_store import VectorStore++# Step-by-step pipeline+ingestor = FileIngestor()+documents = ingestor.ingest("data/")++parser = DocumentParser()+parsed = parser.parse(documents)++normalizer = TextNormalizer()+normalized = normalizer.normalize(parsed)++extractor = NERExtractor()+entities = extractor.extract(normalized)++rel_extractor = RelationExtractor()+relationships = rel_extractor.extract(normalized, entities)++builder = GraphBuilder()+kg = builder.build(entities, relationships)++generator = EmbeddingGenerator()+embeddings = generator.generate(normalized)++vector_store = VectorStore()+vector_store.store(embeddings, normalized)+```++### Pattern 3: GraphRAG Integration++```python+from semantica import Semantica+from semantica.kg import GraphBuilder+from semantica.vector_store import VectorStore, HybridSearch++# Build knowledge base+semantica = Semantica()+result = semantica.build_knowledge_base(["documents/"])++# Set up GraphRAG+kg = result["knowledge_graph"]+embeddings = result["embeddings"]+vector_store = VectorStore()+vector_store.store(embeddings, result["documents"])++# Query with GraphRAG+hybrid_search = HybridSearch(vector_store)+results = hybrid_search.search(+ query="What is the relationship between X and Y?",+ graph=kg,+ top_k=10+)+```++### Pattern 4: Temporal Graph with Reasoning++```python+from semantica.kg import GraphBuilder+from semantica.reasoning import InferenceEngine, RuleManager++# Build temporal graph+builder = GraphBuilder(temporal=True)+kg = builder.build(entities, relationships)++# Add reasoning+inference_engine = InferenceEngine()+rule_manager = RuleManager()+rules = ["IF A THEN B"]+rule_manager.add_rules(rules)++new_facts = inference_engine.forward_chain(kg, rule_manager)+```++---++## Performance Considerations++### Module Performance Characteristics++| Module | Typical Speed | Memory Usage | Scalability | Optimization Tips |+| :--- | :--- | :--- | :--- | :--- |+| **Ingest** | Fast | Low | High | Batch processing, parallel I/O |+| **Parse** | Medium | Medium | Medium | OCR only when needed, cache results |+| **Normalize** | Fast | Low | High | Batch processing |+| **Semantic Extract** | Slow (LLM) | Medium | Medium | Use faster models, batch processing |+| **KG** | Fast | High (large graphs) | Medium | Use graph stores for large graphs |+| **Embeddings** | Slow (API) | Low | High | Batch processing, caching |+| **Vector Store** | Fast | Medium | High | Use FAISS for large datasets |+| **Graph Store** | Fast | Low | High | Index optimization, query tuning |+| **Reasoning** | Slow | Medium | Low | Limit iterations, optimize rules |+| **Ontology** | Medium | Medium | Medium | Cache validation results |+| **Export** | Fast | Low | High | Streaming for large graphs |+| **Visualization** | Slow | High | Low | Limit nodes, use sampling |+| **Pipeline** | Varies | Varies | High | Parallel execution, resource limits |++### Optimization Strategies++1. **Batch Processing**: Process multiple documents together+ ```python+ # Good: Batch processing+ documents = ingestor.ingest("data/", batch_size=100)+ ```++2. **Caching**: Cache expensive operations+ ```python+ # Cache embeddings+ generator = EmbeddingGenerator(cache=True)+ ```++3. **Parallel Execution**: Use pipeline parallelism+ ```python+ pipeline = builder.build()+ result = pipeline.execute(sources=sources, parallel=True, max_workers=8)+ ```++4. **Backend Selection**: Choose appropriate backends+ ```python+ # For large graphs, use Neo4j instead of NetworkX+ builder = GraphBuilder(backend="neo4j")+ ```++5. **Resource Limits**: Set appropriate limits+ ```python+ # Limit memory usage+ parser = DocumentParser(max_file_size=10_000_000) # 10MB+ ```++---++## Next Steps++- **[Core Concepts](concepts.md)** - Understand the fundamental concepts+- **[Use Cases](use-cases.md)** - See real-world applications+- **[Examples](examples.md)** - Practical code examples+- **[API Reference](reference/core.md)** - Detailed API documentation++---++!!! info "Contribute"+ Found an issue or want to improve this guide? [Contribute on GitHub](https://github.com/Hawksight-AI/semantica)++**Last Updated**: 2024diff --git a/docs/use-cases.md b/docs/use-cases.mdindex da92a4dd..72933c26 100644--- a/docs/use-cases.md+++ b/docs/use-cases.md@@ -2,31 +2,265 @@Semantica is designed to solve complex data challenges across various domains. This guide explores common use cases and how to implement them.-## π¬ Research & Science+!!! info "About This Guide"+ This guide provides detailed implementation guides for real-world use cases, complete with code examples, prerequisites, and step-by-step instructions.-<div class="grid cards" markdown>+----- :material-microscope: **Research Paper Analysis**- ---- Extract structured knowledge from academic papers to discover trends, relationships, and key concepts.+## Table of Contents++- [Choosing the Right Use Case](#choosing-the-right-use-case)+- [Use Case Comparison](#use-case-comparison)+- [Research & Science](#research--science)+- [Finance & Trading](#finance--trading)+- [Healthcare & Life Sciences](#healthcare--life-sciences)+- [Security & Intelligence](#security--intelligence)+- [Industry & Operations](#industry--operations)+- [Advanced AI Patterns](#advanced-ai-patterns)+- [New Use Cases](#new-use-cases)++---++## Choosing the Right Use Case++Use this decision tree to find the use case that best fits your needs:++```mermaid+flowchart TD+ Start[What is your domain?] --> Q1{Research/Academic?}+ Q1 -->|Yes| Research[Research Paper Analysis<br/>Biomedical Knowledge Graphs]+ Q1 -->|No| Q2{Finance/Trading?}- **Goal**: Ingest PDFs, extract entities (Authors, Concepts, Methods), and build a citation network.+ Q2 -->|Yes| Finance[Financial Market Intelligence<br/>Algorithmic Trading<br/>Blockchain Analytics]+ Q2 -->|No| Q3{Healthcare?}- [:material-arrow-right: View Cookbook](cookbook/use_cases/biomedical/index.ipynb)--- :material-dna: **Biomedical Knowledge Graphs**- ---- Accelerate drug discovery and understand disease pathways.+ Q3 -->|Yes| Healthcare[Medical Record Analysis<br/>Patient Journey Mapping]+ Q3 -->|No| Q4{Security/Intelligence?}++ Q4 -->|Yes| Security[Cybersecurity Threat Intelligence<br/>OSINT<br/>Fraud Detection]+ Q4 -->|No| Q5{Industry/Operations?}++ Q5 -->|Yes| Industry[Supply Chain Optimization<br/>Renewable Energy Management]+ Q5 -->|No| Q6{AI/ML Applications?}- **Goal**: Connect genes, proteins, drugs, and diseases from scientific literature and databases.+ Q6 -->|Yes| AI[GraphRAG<br/>Corporate Intelligence<br/>Legal Document Review]+ Q6 -->|No| Q7{Other?}- **Key Entities**: Gene, Protein, Drug, Disease, Pathway.+ Q7 -->|Legal| Legal[Legal Document Analysis]+ Q7 -->|Social Media| Social[Social Media Analysis]+ Q7 -->|Support| Support[Customer Support Knowledge Base]++ style Research fill:#e1f5fe,stroke:#01579b+ style Finance fill:#fff3e0,stroke:#ef6c00+ style Healthcare fill:#e8f5e9,stroke:#2e7d32+ style Security fill:#ffebee,stroke:#c62828+ style Industry fill:#f3e5f5,stroke:#7b1fa2+ style AI fill:#e0f2f1,stroke:#00695c+```-</div>+---++## Use Case Comparison++| Use Case | Difficulty | Time | Domain | Key Features |+| :-------------------------------- | :------------ | :---------- | :---------- | :---------------------------------------------- |+| **Research Paper Analysis** | Beginner | 30 min | Research | Citation networks, concept extraction |+| **Biomedical Knowledge Graphs** | Intermediate | 1-2 hours | Healthcare | Gene-protein-disease relationships |+| **Financial Market Intelligence** | Intermediate | 1 hour | Finance | Sentiment analysis, trend detection |+| **Algorithmic Trading** | Advanced | 2-3 hours | Finance | Multi-source integration, signal generation |+| **Blockchain Analytics** | Intermediate | 1-2 hours | Finance | Transaction tracing, fraud detection |+| **Medical Record Analysis** | Intermediate | 1 hour | Healthcare | Patient history, temporal tracking |+| **Cybersecurity Threat Intelligence**| Advanced | 2-3 hours | Security | Threat mapping, pattern detection |+| **OSINT** | Intermediate | 1-2 hours | Security | Multi-source intelligence |+| **Supply Chain Optimization** | Intermediate | 1-2 hours | Industry | Route optimization, risk management |+| **GraphRAG** | Intermediate | 1 hour | AI | Enhanced RAG with knowledge graphs |+| **Legal Document Analysis** | Intermediate | 1-2 hours | Legal | Contract analysis, clause extraction |+| **Social Media Analysis** | Beginner | 30 min | Social | Sentiment, trend analysis |+| **Customer Support KB** | Beginner | 30 min | Support | FAQ generation, knowledge base |++**Difficulty Levels**:+- **Beginner**: Basic Semantica knowledge required+- **Intermediate**: Some domain knowledge helpful+- **Advanced**: Requires domain expertise and advanced Semantica features++## Research & Science++### Research Paper Analysis++!!! abstract "Use Case"+ Extract structured knowledge from academic papers to discover trends, relationships, and key concepts.++**Difficulty**: Beginner+**Time**: 30 minutes+**Domain**: Research++**Prerequisites**:+- Semantica installed+- Python 3.8++- Sample research papers (PDF format)+- OpenAI API key (optional, for LLM-based extraction)++**Goal**: Ingest PDFs, extract entities (Authors, Concepts, Methods), and build a citation network.++**Step-by-Step Implementation**:++1. **Install and Import**+ ```python+ from semantica import Semantica+ ```++2. **Initialize Semantica**+ ```python+ semantica = Semantica()+ ```++3. **Build Knowledge Base**+ ```python+ result = semantica.build_knowledge_base(+ sources=["papers/paper1.pdf", "papers/paper2.pdf"],+ embeddings=True,+ graph=True+ )+ ```++4. **Analyze Results**+ ```python+ kg = result["knowledge_graph"]+ print(f"Extracted {len(kg['entities'])} entities")+ print(f"Created {len(kg['relationships'])} relationships")+ ```++**Complete Code Example**:++```python+from semantica import Semantica+from semantica.visualization import KGVisualizer++# Initialize+semantica = Semantica()++# Build knowledge graph from research papers+result = semantica.build_knowledge_base(+ sources=[+ "papers/machine_learning_survey.pdf",+ "papers/deep_learning_review.pdf",+ "papers/nlp_advances.pdf"+ ],+ embeddings=True,+ graph=True,+ normalize=True+)++# Access results+kg = result["knowledge_graph"]+embeddings = result["embeddings"]++# Filter entities by type+authors = [e for e in kg['entities'] if e.get('type') == 'PERSON']+concepts = [e for e in kg['entities'] if e.get('type') == 'CONCEPT']+methods = [e for e in kg['entities'] if e.get('type') == 'METHOD']++print(f"Authors: {len(authors)}")+print(f"Concepts: {len(concepts)}")+print(f"Methods: {len(methods)}")++# Visualize citation network+visualizer = KGVisualizer()+visualizer.visualize(+ kg,+ output_format="html",+ output_path="citation_network.html"+)++# Export for analysis+semantica.export.to_json(kg, "research_kg.json")+```++**Expected Output**:+```+Authors: 45+Concepts: 120+Methods: 30+Relationships: 200+```++**Next Steps**:+- [:material-arrow-right: View Cookbook](cookbook/use_cases/biomedical/index.ipynb)+- [Explore Graph Analytics](reference/kg.md#graph-analytics)+- [Learn about Visualization](reference/visualization.md)----## πΌ Finance & Trading+### Biomedical Knowledge Graphs++!!! abstract "Use Case"+ Accelerate drug discovery and understand disease pathways by connecting genes, proteins, drugs, and diseases.++**Difficulty**: Intermediate+**Time**: 1-2 hours+**Domain**: Healthcare/Research++**Prerequisites**:+- Domain knowledge of biomedical concepts+- Access to biomedical literature/databases+- LLM API access (recommended for accuracy)++**Goal**: Connect genes, proteins, drugs, and diseases from scientific literature and databases.++**Key Entities**: Gene, Protein, Drug, Disease, Pathway++**Complete Code Example**:++```python+from semantica import Semantica+from semantica.ontology import OntologyGenerator++# Initialize with biomedical focus+semantica = Semantica()++# Define custom entity types for biomedical domain+custom_entities = ["Gene", "Protein", "Drug", "Disease", "Pathway", "Mutation"]++# Build knowledge graph+result = semantica.build_knowledge_base(+ sources=[+ "literature/cancer_research.pdf",+ "databases/gene_protein_interactions.json"+ ],+ embeddings=True,+ graph=True,+ custom_entity_types=custom_entities+)++kg = result["knowledge_graph"]++# Generate ontology+ontology_gen = OntologyGenerator(base_uri="https://biomed.example.org/ontology/")+ontology = ontology_gen.generate_from_graph(kg)++# Query disease pathways+pathways = [r for r in kg['relationships']+ if r.get('predicate') == 'in_pathway']++print(f"Found {len(pathways)} pathway relationships")++# Export for further analysis+semantica.export.to_owl(ontology, "biomedical_ontology.owl")+```++**Expected Output**:+```+Found 150 pathway relationships+Generated ontology with 25 classes and 40 properties+```++**Next Steps**:+- [Ontology Module](reference/ontology.md)+- [Temporal Graphs](concepts.md#5-temporal-graphs)++---++## Finance & Trading<div class="grid cards" markdown>@@ -56,41 +290,9 @@ Semantica is designed to solve complex data challenges across various domains. T</div>-### π Financial Data Pipeline Architecture--```mermaid-graph LR- subgraph Sources- N[News Feeds]- M[Market Data]- R[Reports]- end-- subgraph Processing- NER[Entity Extraction]- SA[Sentiment Analysis]- TC[Trend Correlation]- end-- subgraph Knowledge- KG[Financial KG]- Signals[Alpha Signals]- end-- Sources --> NER- Sources --> SA- NER --> KG- SA --> KG- KG --> TC- TC --> Signals-- style KG fill:#e8f5e9,stroke:#2e7d32- style Signals fill:#fff3e0,stroke:#ef6c00-```-----## π₯ Healthcare & Life Sciences+## Healthcare & Life Sciences<div class="grid cards" markdown>@@ -112,7 +314,7 @@ graph LR----## π‘οΈ Security & Intelligence+## Security & Intelligence<div class="grid cards" markdown>@@ -156,37 +358,9 @@ graph LR</div>-### π‘οΈ Threat Intelligence Architecture--```mermaid-graph TD- subgraph Ingest- F[Threat Feeds]- L[System Logs]- end-- subgraph Analysis- P[Pattern Match]- A[Anomaly Detect]- end-- subgraph Response- G[Threat Graph]- Alert[Alert System]- end-- F --> P- L --> A- P --> G- A --> G- G --> Alert-- style G fill:#ffebee,stroke:#c62828-```-----## π Industry & Operations+## Industry & Operations<div class="grid cards" markdown>@@ -210,7 +384,7 @@ graph TD----## π€ Advanced AI Patterns+## Advanced AI Patterns<div class="grid cards" markdown>@@ -238,24 +412,208 @@ graph TD----## π§© Implementation Example+## New Use Cases-Here is a general pattern for implementing these use cases:+### Legal Document Analysis-```mermaid-graph LR- Input[π Data Sources] --> Ingest- Ingest --> Extract[π§ Semantic Extraction]- Extract --> KG[πΈοΈ Knowledge Graph]- KG --> App[π Application]-- subgraph Application Layer- App --> Search[Semantic Search]- App --> RAG[GraphRAG]- App --> Analytics[Graph Analytics]- end+!!! abstract "Use Case"+ Analyze contracts and legal texts to extract clauses, identify relationships, and understand document structure.++**Difficulty**: Intermediate+**Time**: 1-2 hours+**Domain**: Legal++**Prerequisites**:+- Legal document samples (contracts, agreements)+- Understanding of legal terminology+- LLM API access (recommended)++**Goal**: Parse contracts, extract clauses, and identify relationships like "supersedes", "amends", "references".++**Complete Code Example**:++```python+from semantica import Semantica+from semantica.semantic_extract import NERExtractor, RelationExtractor++semantica = Semantica()++# Define legal entity types+legal_entities = [+ "Party", "Clause", "Section", "Contract", "Agreement",+ "Term", "Condition", "Obligation", "Right"+]++# Build knowledge graph from contracts+result = semantica.build_knowledge_base(+ sources=[+ "contracts/agreement1.pdf",+ "contracts/amendment1.pdf"+ ],+ custom_entity_types=legal_entities,+ graph=True,+ temporal=True # Track contract versions+)++kg = result["knowledge_graph"]++# Extract clause relationships+clause_rels = [r for r in kg['relationships']+ if r.get('predicate') in ['supersedes', 'amends', 'references']]++print(f"Found {len(clause_rels)} clause relationships")++# Query contract structure+parties = [e for e in kg['entities'] if e.get('type') == 'Party']+print(f"Parties: {[p.get('text') for p in parties]}")++# Export for legal review+semantica.export.to_json(kg, "contract_analysis.json")+```++**Expected Output**:+```+Found 15 clause relationships+Parties: ['Company A', 'Company B']+```++---++### Social Media Analysis++!!! abstract "Use Case"+ Analyze social media content to extract sentiment, trends, and relationships between users and topics.++**Difficulty**: Beginner+**Time**: 30 minutes+**Domain**: Social Media++**Prerequisites**:+- Social media data (JSON, CSV, or API access)+- Basic understanding of sentiment analysis++**Goal**: Extract entities, relationships, and sentiment from social media posts to understand trends and user connections.++**Complete Code Example**:++```python+from semantica import Semantica+from semantica.ingest import FileIngestor++semantica = Semantica()++# Ingest social media data+ingestor = FileIngestor()+posts = ingestor.ingest("social_media/posts.json")++# Build knowledge graph+result = semantica.build_knowledge_base(+ sources=posts,+ embeddings=True,+ graph=True+)++kg = result["knowledge_graph"]++# Analyze trends+hashtags = [e for e in kg['entities'] if e.get('text', '').startswith('#')]+mentions = [e for e in kg['entities'] if e.get('text', '').startswith('@')]++print(f"Hashtags: {len(hashtags)}")+print(f"Mentions: {len(mentions)}")++# Find popular topics+from collections import Counter+topic_counts = Counter([e.get('text') for e in hashtags])+print(f"Top topics: {topic_counts.most_common(10)}")++# Visualize social network+semantica.visualization.visualize_network(+ kg,+ output="social_network.html"+)```+**Expected Output**:+```+Hashtags: 150+Mentions: 200+Top topics: [('AI', 45), ('MachineLearning', 30), ('Python', 25)]+```++---++### Customer Support Knowledge Base++!!! abstract "Use Case"+ Build a knowledge base from support tickets, documentation, and FAQs to improve customer service.++**Difficulty**: Beginner+**Time**: 30 minutes+**Domain**: Customer Support++**Prerequisites**:+- Support tickets or documentation+- FAQ documents+- Basic text data++**Goal**: Create a searchable knowledge base that connects support issues, solutions, and related topics.++**Complete Code Example**:++```python+from semantica import Semantica+from semantica.vector_store import VectorStore, HybridSearch++semantica = Semantica()++# Build knowledge base from support docs+result = semantica.build_knowledge_base(+ sources=[+ "support/tickets/",+ "support/faqs/",+ "support/documentation/"+ ],+ embeddings=True,+ graph=True+)++kg = result["knowledge_graph"]+embeddings = result["embeddings"]++# Set up semantic search+vector_store = VectorStore()+vector_store.store(embeddings, result["documents"])++# Search for similar issues+hybrid_search = HybridSearch(vector_store)+results = hybrid_search.search(+ query="How do I reset my password?",+ top_k=5+)++print("Similar support articles:")+for result in results:+ print(f" - {result.document.metadata.get('title', 'N/A')} (Score: {result.score:.3f})")++# Export knowledge base+semantica.export.to_json(kg, "support_kb.json")+```++**Expected Output**:+```+Similar support articles:+ - Password Reset Guide (Score: 0.892)+ - Account Recovery (Score: 0.856)+ - Login Issues FAQ (Score: 0.823)+```++---++## Implementation Example++Here is a general pattern for implementing these use cases:+```pythonfrom semantica import Semantica@@ -271,3 +629,40 @@ kg = semantica.kg.build_graph(docs)# 4. Analyze or Queryinsights = semantica.kg.query("MATCH (c:Company)-[:HAS_RISK]->(r:Risk) RETURN c, r")```++---++## Summary++This guide covered use cases across multiple domains:++- **Research & Science**: Academic paper analysis, biomedical knowledge graphs+- **Finance & Trading**: Market intelligence, trading signals, blockchain analytics+- **Healthcare**: Medical records, patient journey mapping+- **Security**: Threat intelligence, OSINT, fraud detection+- **Industry**: Supply chain, energy management+- **AI Applications**: GraphRAG, corporate intelligence+- **New Use Cases**: Legal analysis, social media, customer support++Each use case follows a similar pattern:+1. **Ingest** data from various sources+2. **Extract** entities and relationships+3. **Build** knowledge graph+4. **Analyze** and query+5. **Export** or visualize results++---++## Next Steps++- **[Examples](examples.md)** - More detailed code examples+- **[Modules Guide](modules.md)** - Learn about available modules+- **[Cookbook](cookbook.md)** - Interactive Jupyter notebooks+- **[API Reference](reference/core.md)** - Complete API documentation++---++!!! info "Contribute"+ Have a use case to add? [Contribute on GitHub](https://github.com/Hawksight-AI/semantica)++**Last Updated**: 2024