Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

docs: Update all documentation with 18 enhanced domain-specific cookbooks

KaifAhmad1106e817ad8bd
diff --git a/README.md b/README.md
index b5bb4919..3fe1170b 100644
--- a/README.md
+++ b/README.md
@@ -242,7 +242,7 @@ python -c "import semantica; print(semantica.__version__)"
| **GraphRAG Complete** | Build a production-ready **Graph Retrieval Augmented Generation** system. Features **Graph Validation**, **Hybrid Retrieval**, and **Logical Inference**. | [Open Notebook](cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb) |
| **RAG vs. GraphRAG** | Side-by-side comparison. Demonstrates the **Reasoning Gap** and how GraphRAG solves it with **Inference Engines**. | [Open Notebook](cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb) |
| **First Knowledge Graph** | Go from raw text to a queryable knowledge graph in 20 minutes. | [Open Notebook](cookbook/introduction/08_Your_First_Knowledge_Graph.ipynb) |
-| **Real-Time Anomalies** | Detect anomalies in streaming data using dynamic graphs. | [Open Notebook](cookbook/use_cases/cybersecurity/01_Anomaly_Detection_Real_Time.ipynb) |
+| **Real-Time Anomalies** | Detect anomalies in streaming data using temporal knowledge graphs and pattern detection. | [Open Notebook](cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb) |
### Core Tutorials
@@ -251,6 +251,46 @@ python -c "import semantica; print(semantica.__version__)"
- [**Entity Extraction**](cookbook/introduction/05_Entity_Extraction.ipynb) - NER & Relationships
- [**Building Knowledge Graphs**](cookbook/introduction/07_Building_Knowledge_Graphs.ipynb) - Graph Construction
+### Industry Use Cases (18 Cookbooks)
+
+**Domain-Specific Cookbooks** showcasing real-world applications with real data sources, advanced chunking strategies, temporal KGs, GraphRAG, and comprehensive Semantica module integration:
+
+#### Biomedical
+- [**Drug Discovery Pipeline**](cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb) - PubMed RSS, entity-aware chunking, GraphRAG, vector similarity search
+- [**Genomic Variant Analysis**](cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb) - bioRxiv RSS, temporal KGs, deduplication, pathway analysis
+
+#### Healthcare
+- [**Clinical Reports Processing**](cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb) - FDA RSS, HL7/FHIR integration, patient deduplication
+- [**Drug Interactions Analysis**](cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynb) - Medical RSS, relation-aware chunking, conflict detection, safety ontology
+
+#### Finance
+- [**Financial Data Integration MCP**](cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb) - Alpha Vantage API, MCP servers, seed data, real-time ingestion
+- [**Fraud Detection**](cookbook/use_cases/finance/02_Fraud_Detection.ipynb) - Transaction streams, temporal KGs, pattern detection, conflict resolution
+
+#### Blockchain
+- [**DeFi Protocol Intelligence**](cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb) - CoinDesk RSS, ontology-aware chunking, conflict detection, ontology generation
+- [**Transaction Network Analysis**](cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb) - Blockchain APIs, deduplication, network analytics
+
+#### Cybersecurity
+- [**Real-Time Anomaly Detection**](cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb) - CVE RSS, Kafka streams, temporal KGs, sentence chunking
+- [**Threat Intelligence Hybrid RAG**](cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb) - Security RSS, entity-aware chunking, enhanced GraphRAG, deduplication
+
+#### Intelligence & Law Enforcement
+- [**Criminal Network Analysis**](cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb) - OSINT RSS, deduplication, network centrality, graph analytics
+- [**Intelligence Analysis Orchestrator Worker**](cookbook/use_cases/intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb) - Pipeline orchestrator, multi-source integration, conflict detection
+
+#### Trading
+- [**Risk Assessment**](cookbook/use_cases/trading/01_Risk_Assessment.ipynb) - Yahoo Finance API, GraphRAG, entity-aware chunking, portfolio risk modeling
+- [**News Sentiment Analysis**](cookbook/use_cases/trading/02_News_Sentiment_Analysis.ipynb) - Financial RSS, semantic transformer chunking, enhanced GraphRAG, sentiment extraction
+
+#### Renewable Energy
+- [**Energy Market Analysis**](cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb) - Energy RSS, EIA API, temporal KGs, TemporalPatternDetector, trend prediction
+- [**Smart Grid Management**](cookbook/use_cases/renewable_energy/02_Smart_Grid_Management.ipynb) - Sensor streams, temporal KGs, token chunking, real-time monitoring
+
+#### Supply Chain
+- [**Supply Chain Data Integration**](cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb) - Logistics RSS, deduplication, relationship mapping
+- [**Supply Chain Risk Management**](cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb) - Supply chain RSS, conflict detection, dependency analysis
+
> **Note:** Once published to PyPI, you'll be able to install with `pip install semantica`
### Install from Source (Development)
@@ -547,7 +587,7 @@ print(f"Answer: {result.answer} | Nodes: {kg.node_count}, Edges: {kg.edge_count}
**Healthcare & Biomedical** — Clinical reports, drug discovery, medical literature analysis.
-[**Explore Use Case Examples**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/use_cases) — See real-world implementations in finance, healthcare, cybersecurity, trading, and more.
+[**Explore Use Case Examples**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/use_cases) — See real-world implementations in finance, healthcare, cybersecurity, trading, and more. **18 comprehensive domain-specific cookbooks** with real data sources, advanced chunking strategies, temporal KGs, GraphRAG, and full Semantica module integration.
## 🔬 Advanced Features
diff --git a/cookbook/use_cases/USE_CASES_CATALOG.md b/cookbook/use_cases/USE_CASES_CATALOG.md
index fc2b07ed..fb81bd7c 100644
--- a/cookbook/use_cases/USE_CASES_CATALOG.md
+++ b/cookbook/use_cases/USE_CASES_CATALOG.md
@@ -2,19 +2,43 @@
This document provides a detailed overview of the various domain-specific use cases and pipelines implemented using the Semantica framework. These examples demonstrate how Semantica can be applied to complex real-world problems across different industries.
+## Cookbook Notebooks
+
+**Selected Use Cases**: Two use cases per domain have been selected for comprehensive cookbook implementation (18 total cookbooks). These cookbooks demonstrate:
+- **Unique problem-solving approaches** tailored to each specific use case
+- **Relevant Semantica capabilities** (ingestion, parsing, extraction, knowledge graphs, embeddings, vector stores, graph analytics, reasoning, visualization, export)
+- **Domain-specific entity types, relationships, and ontologies**
+- **End-to-end pipelines** from data ingestion to insights and visualization
+
+**Note**: Each cookbook is uniquely designed for its use case - no cookie-cutter templates. Different use cases emphasize different Semantica capabilities (vector-focused, graph-focused, temporal-focused, stream-focused, hybrid RAG, etc.)
+
+### Selected Cookbooks by Domain
+
+- **Biomedical**: Drug Discovery Pipeline, Genomic Variant Analysis
+- **Blockchain**: DeFi Protocol Intelligence, Transaction Network Analysis
+- **Cybersecurity**: Real-Time Anomaly Detection, Threat Intelligence Hybrid RAG
+- **Finance**: Financial Data Integration (MCP), Fraud Detection
+- **Healthcare**: Clinical Reports Processing, Drug Interactions Analysis
+- **Intelligence & Law Enforcement**: Criminal Network Analysis, Intelligence Analysis Orchestrator-Worker
+- **Renewable Energy**: Energy Market Analysis, Smart Grid Management
+- **Supply Chain**: Supply Chain Data Integration, Supply Chain Risk Management
+- **Trading**: Risk Assessment, News Sentiment Analysis
+
---
## **Biomedical**
### **1. Drug Discovery Pipeline**
-- **Overview**: A complete drug discovery pipeline that ingests drug and protein data, extracts compound and target entities, builds a drug-target knowledge graph, and performs similarity search to predict interactions.
-- **Key Features**: Compound-target extraction, similarity search, interaction prediction.
-- **Pipeline**: `Drug/Protein Data Sources → Parse → Extract Entities → Build Drug-Target KG → Generate Embeddings → Similarity Search → Predict Interactions → Target Identification`.
+- **Overview**: A complete drug discovery pipeline that ingests drug and protein data, extracts compound and target entities, builds a drug-target knowledge graph, and performs similarity search to predict interactions. Showcases vector embeddings and similarity search capabilities.
+- **Key Features**: Compound-target extraction, vector similarity search, interaction prediction, embedding generation, target identification.
+- **Pipeline**: `Drug/Protein Data Sources → Parse → Extract Entities → Build Drug-Target KG → Generate Embeddings → Vector Store → Similarity Search → Predict Interactions → Target Identification`.
+- **Cookbook**: [:notebook: Drug Discovery Pipeline](biomedical/01_Drug_Discovery_Pipeline.ipynb)
### **2. Genomic Variant Analysis**
-- **Overview**: Analyzes genomic data to extract variant entities, build genomic knowledge graphs, and analyze disease associations.
-- **Key Features**: Variant impact prediction, disease association analysis, pathway analysis.
-- **Pipeline**: `Genomic Data Sources → Parse → Extract Entities → Build Genomic KG → Analyze Associations → Predict Impact → Pathway Analysis`.
+- **Overview**: Analyzes genomic data to extract variant entities, build temporal genomic knowledge graphs, and analyze disease associations through pathway analysis. Demonstrates graph analytics, reasoning, and temporal analysis.
+- **Key Features**: Variant impact prediction, disease association analysis, pathway analysis, graph reasoning, temporal genomic KGs.
+- **Pipeline**: `Genomic Data Sources → Parse → Extract Entities → Build Temporal Genomic KG → Graph Analytics → Analyze Associations → Reasoning → Predict Impact → Pathway Analysis`.
+- **Cookbook**: [:notebook: Genomic Variant Analysis](biomedical/02_Genomic_Variant_Analysis.ipynb)
---
@@ -24,10 +48,12 @@ This document provides a detailed overview of the various domain-specific use ca
- **Overview**: Ingests DeFi data to extract protocol entities, build DeFi knowledge graphs, and assess risks or optimize yields.
- **Key Features**: Protocol risk assessment, yield optimization, relationship analysis.
- **Pipeline**: `DeFi Data Sources → Parse → Extract Entities → Build DeFi KG → Analyze Relationships → Risk Assessment → Yield Optimization`.
+- **Cookbook**: [:notebook: DeFi Protocol Intelligence](blockchain/01_DeFi_Protocol_Intelligence.ipynb)
### **2. Transaction Network Analysis**
- **Overview**: Analyzes blockchain transaction networks to detect patterns, identify whale movements, and analyze token flows.
- **Key Features**: Transaction pattern detection, whale tracking, flow analysis.
+- **Cookbook**: [:notebook: Transaction Network Analysis](blockchain/02_Transaction_Network_Analysis.ipynb)
---
@@ -37,46 +63,28 @@ This document provides a detailed overview of the various domain-specific use ca
- **Overview**: Streams security logs in real-time to build temporal knowledge graphs and detect anomalies using pattern detection.
- **Key Features**: Real-time log parsing, temporal pattern detection, automated alerting.
- **Pipeline**: `Stream Security Logs → Real-Time Parsing → Extract Entities → Build Temporal KG → Pattern Detection → Anomaly Detection`.
+- **Cookbook**: [:notebook: Real-Time Anomaly Detection](cybersecurity/01_Real_Time_Anomaly_Detection.ipynb)
-### **2. Incident Analysis**
-- **Overview**: Processes security logs to build knowledge graphs and analyze relationships for forensic incident investigation.
-- **Key Features**: Relationship analysis, anomaly detection, automated report generation.
-
-### **3. Threat Correlation**
-- **Overview**: Correlates threat feeds from multiple sources to build a temporal KG and detect coordinated campaigns.
-- **Key Features**: IOC extraction, campaign detection, multi-source correlation.
-
-### **4. Threat Intelligence Hybrid RAG**
+### **2. Threat Intelligence Hybrid RAG**
- **Overview**: Combines vector search with temporal knowledge graphs for advanced threat intelligence querying.
- **Key Features**: Vector + KG hybrid search, context-aware retrieval.
-
-### **5. Vulnerability Tracking**
-- **Overview**: Ingests CVE data (NVD, feeds) to build a temporal KG and correlate vulnerabilities with organizational assets.
-- **Key Features**: Impact prediction, CVE correlation, vulnerability reporting.
+- **Cookbook**: [:notebook: Threat Intelligence Hybrid RAG](cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb)
---
## **Finance**
### **1. Financial Data Integration (MCP)**
-- **Overview**: Integrates Python/FastMCP servers to ingest market data, stock prices, and metrics into a financial knowledge graph.
-- **Key Features**: MCP integration, multi-source financial ingestion.
-
-### **2. Financial Reports Analysis**
-- **Overview**: Parses SEC filings and annual reports to extract financial entities and generate automated insights.
-- **Key Features**: SEC filing ingestion, entity relationship analysis, insight generation.
-
-### **3. Fraud Detection**
-- **Overview**: Analyzes transaction streams using temporal knowledge graphs to detect fraud patterns and anomalies.
-- **Key Features**: Transaction pattern detection, anomaly detection, real-time alerts.
+- **Overview**: Integrates Python/FastMCP servers to ingest real-time market data, stock prices, and financial metrics into a comprehensive financial knowledge graph. Demonstrates MCP server integration for live data streaming.
+- **Key Features**: MCP integration, real-time market data ingestion, multi-source financial KG construction, API-based data streaming.
+- **Pipeline**: `MCP Servers → Real-Time Data Ingestion → Parse Market Data → Extract Financial Entities → Build Financial KG → Real-Time Updates`.
+- **Cookbook**: [:notebook: Financial Data Integration (MCP)](finance/01_Financial_Data_Integration_MCP.ipynb)
-### **4. Investment Analysis Hybrid RAG**
-- **Overview**: Uses advanced RAG to query investment insights across market data APIs and financial feeds.
-- **Key Features**: Hybrid search, investment trend analysis.
-
-### **5. Regulatory Compliance**
-- **Overview**: Extracts compliance rules from regulatory documents (SEC, FINRA) to validate data against compliance ontologies.
-- **Key Features**: Compliance rule extraction, automated validation, compliance reporting.
+### **2. Fraud Detection**
+- **Overview**: Analyzes transaction streams using temporal knowledge graphs to detect fraud patterns and anomalies in real-time. Demonstrates stream processing, temporal graph construction, and pattern-based anomaly detection.
+- **Key Features**: Temporal transaction KGs, real-time anomaly detection, pattern recognition, automated alerting, stream processing.
+- **Pipeline**: `Transaction Streams → Real-Time Parsing → Build Temporal KG → Pattern Detection → Anomaly Detection → Real-Time Alerts`.
+- **Cookbook**: [:notebook: Fraud Detection](finance/02_Fraud_Detection.ipynb)
---
@@ -85,26 +93,12 @@ This document provides a detailed overview of the various domain-specific use ca
### **1. Clinical Reports Processing**
- **Overview**: Processes EHR systems and HL7/FHIR APIs to build patient knowledge graphs and store them in triplet stores.
- **Key Features**: EHR integration, medical entity extraction, triplet store storage.
+- **Cookbook**: [:notebook: Clinical Reports Processing](healthcare/01_Clinical_Reports_Processing.ipynb)
-### **2. Disease Network Analysis**
-- **Overview**: Builds disease ontologies from medical literature to analyze networks and predict outcomes.
-- **Key Features**: Disease relationship extraction, network analysis, outcome prediction.
-
-### **3. Drug Interactions Analysis**
+### **2. Drug Interactions Analysis**
- **Overview**: Analyzes FDA databases and medical literature to detect drug-drug and drug-condition interactions.
- **Key Features**: Interaction detection, safety ontology generation, drug knowledge graph.
-
-### **4. Healthcare GraphRAG Hybrid**
-- **Overview**: A specialized GraphRAG system that leverages medical ontologies and patient-level data for explainable healthcare queries.
-- **Key Features**: Explainable AI, hybrid KG/patient data retrieval.
-
-### **5. Medical Database Integration (MCP)**
-- **Overview**: Uses MCP servers to ingest patient records and clinical data into a centralized healthcare KG.
-- **Key Features**: MCP-based clinical ingestion, entity resolution.
-
-### **6. Patient Records Temporal Analysis**
-- **Overview**: Builds temporal knowledge graphs from patient history to query medical timelines and generate insights.
-- **Key Features**: Medical history querying, temporal trend analysis.
+- **Cookbook**: [:notebook: Drug Interactions Analysis](healthcare/02_Drug_Interactions_Analysis.ipynb)
---
@@ -113,14 +107,12 @@ This document provides a detailed overview of the various domain-specific use ca
### **1. Criminal Network Analysis**
- **Overview**: Processes police reports and court records to build knowledge graphs for analyzing criminal networks and relationships.
- **Key Features**: Relationship analysis, network centrality, intelligence reporting.
+- **Cookbook**: [:notebook: Criminal Network Analysis](intelligence/01_Criminal_Network_Analysis.ipynb)
### **2. Intelligence Analysis (Orchestrator-Worker)**
- **Overview**: Uses the Orchestrator-Worker pattern to coordinate parallel processing of OSINT feeds, threat intelligence, and geospatial data.
- **Key Features**: Parallel processing, multi-source intelligence, hybrid RAG.
-
-### **3. Law Enforcement Forensics**
-- **Overview**: An agent-based workflow for processing case files, evidence logs, and witness statements for forensic analysis.
-- **Key Features**: Agent-based evidence correlation, temporal forensic timelines.
+- **Cookbook**: [:notebook: Intelligence Analysis Orchestrator-Worker](intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb)
---
@@ -129,18 +121,12 @@ This document provides a detailed overview of the various domain-specific use ca
### **1. Energy Market Analysis**
- **Overview**: Analyzes pricing trends and market movements using temporal market knowledge graphs.
- **Key Features**: Market trend prediction, energy entity extraction.
+- **Cookbook**: [:notebook: Energy Market Analysis](renewable_energy/01_Energy_Market_Analysis.ipynb)
-### **2. Environmental Impact Analysis**
-- **Overview**: Processes EPA and climate databases to assess environmental impact through relationship analysis in a KG.
-- **Key Features**: Climate data ingestion, impact assessment.
-
-### **3. Smart Grid Management**
+### **2. Smart Grid Management**
- **Overview**: Streams grid sensor data to monitor grid health and predict failures using temporal pattern detection.
- **Key Features**: Real-time monitoring, failure prediction, anomaly detection.
-
-### **4. Resource Optimization**
-- **Overview**: Analyzes efficiency metrics to optimize resource allocation across energy monitoring systems.
-- **Key Features**: Efficiency analysis, resource allocation optimization.
+- **Cookbook**: [:notebook: Smart Grid Management](renewable_energy/02_Smart_Grid_Management.ipynb)
---
@@ -149,31 +135,26 @@ This document provides a detailed overview of the various domain-specific use ca
### **1. Supply Chain Data Integration**
- **Overview**: Ingests logistics and supplier data to build a comprehensive supply chain knowledge graph.
- **Key Features**: Logistics tracking, supplier relationship mapping.
+- **Cookbook**: [:notebook: Supply Chain Data Integration](supply_chain/01_Supply_Chain_Data_Integration.ipynb)
### **2. Supply Chain Risk Management**
- **Overview**: Detects risks in the supply chain by analyzing dependencies and external feeds.
- **Key Features**: Risk detection, dependency analysis.
+- **Cookbook**: [:notebook: Supply Chain Risk Management](supply_chain/02_Supply_Chain_Risk_Management.ipynb)
---
## **Trading**
-### **1. Market Data Analysis**
-- **Overview**: Analyzes high-frequency market data to detect trading patterns and signals.
-- **Key Features**: Signal detection, pattern analysis.
+### **1. Risk Assessment**
+- **Overview**: Assesses portfolio risk using graph-based analytics, market simulations, and dependency mapping. Builds financial knowledge graphs to model portfolio relationships and perform risk analysis.
+- **Key Features**: Graph-based portfolio risk analysis, market simulation, dependency mapping, risk pattern detection.
+- **Pipeline**: `Portfolio Data → Build Financial KG → Graph Analytics → Risk Modeling → Dependency Analysis → Risk Assessment`.
+- **Cookbook**: [:notebook: Risk Assessment](trading/01_Risk_Assessment.ipynb)
### **2. News Sentiment Analysis**
-- **Overview**: Correlates news sentiment with price movements using a financial knowledge graph.
-- **Key Features**: Sentiment extraction, price correlation.
-
-### **3. Real-Time Monitoring**
-- **Overview**: Monitors trading activities and market conditions in real-time.
-- **Key Features**: Real-time alerts, market condition tracking.
-
-### **4. Risk Assessment**
-- **Overview**: Assesses portfolio risk using graph-based analytics and market simulations.
-- **Key Features**: Portfolio risk analysis, market simulation.
+- **Overview**: Extracts sentiment from financial news articles and correlates it with price movements using a comprehensive financial knowledge graph. Demonstrates semantic extraction, correlation analysis, and predictive modeling.
+- **Key Features**: Sentiment extraction, price correlation analysis, financial KG construction, predictive modeling.
+- **Pipeline**: `News Sources → Parse Articles → Extract Sentiment → Build Financial KG → Correlate with Prices → Predict Movements`.
+- **Cookbook**: [:notebook: News Sentiment Analysis](trading/02_News_Sentiment_Analysis.ipynb)
-### **5. Strategy Backtesting**
-- **Overview**: Uses historical knowledge graphs to backtest trading strategies.
-- **Key Features**: Historical simulation, strategy evaluation.
diff --git a/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb b/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb
new file mode 100644
index 00000000..fb5e68b1
--- /dev/null
+++ b/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb
@@ -0,0 +1,504 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb)\n",
+ "\n",
+ "# Drug Discovery Pipeline - Vector Similarity Search\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates a **complete drug discovery pipeline** using Semantica that focuses on **vector similarity search** and **interaction prediction**. The pipeline ingests drug and protein data, extracts compound and target entities, builds a drug-target knowledge graph, and performs similarity search to predict drug-target interactions.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Vector-Focused Approach**: Emphasizes embeddings and vector similarity search for drug-target interaction prediction\n",
+ "- **Compound-Target Extraction**: Extracts drug compounds, proteins, and targets from biomedical literature\n",
+ "- **Similarity Search**: Uses vector embeddings to find similar compounds and predict interactions\n",
+ "- **Knowledge Graph Construction**: Builds structured drug-target relationship graphs\n",
+ "- **Interaction Prediction**: Predicts potential drug-target interactions using similarity metrics\n",
+ "\n",
+ "### What You'll Learn\n",
+ "\n",
+ "- How to ingest biomedical data (drug databases, protein data, literature)\n",
+ "- How to extract compound and target entities from unstructured text\n",
+ "- How to generate embeddings for drugs and proteins\n",
+ "- How to perform similarity search to find similar compounds\n",
+ "- How to build drug-target knowledge graphs\n",
+ "- How to predict drug-target interactions using vector similarity\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: Biomedical Data Ingestion\n",
+ "3. **Phase 2**: Document Parsing & Processing\n",
+ "4. **Phase 3**: Entity Extraction (Drugs, Proteins, Targets)\n",
+ "5. **Phase 4**: Embedding Generation\n",
+ "6. **Phase 5**: Vector Store Population\n",
+ "7. **Phase 6**: Similarity Search & Interaction Prediction\n",
+ "8. **Phase 7**: Knowledge Graph Construction\n",
+ "9. **Phase 8**: Visualization & Export\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n",
+ "\n",
+ "Install Semantica and required dependencies:\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Install Semantica and required dependencies\n",
+ "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq sentence-transformers scikit-learn\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n",
+ "\n",
+ "Configure Semantica for drug discovery with focus on vector similarity search.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import json\n",
+ "import pandas as pd\n",
+ "import numpy as np\n",
+ "from typing import List, Dict, Any\n",
+ "\n",
+ "# Set API keys\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-groq-api-key-here\")\n",
+ "\n",
+ "print(\"Environment configured.\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.vector_store import VectorStore\n",
+ "from semantica.embeddings import EmbeddingGenerator\n",
+ "from semantica.semantic_extract import NamedEntityRecognizer, RelationExtractor\n",
+ "\n",
+ "# Configure for drug discovery with vector similarity focus\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Drug_Discovery_Pipeline\",\n",
+ " \"embedding\": {\n",
+ " \"provider\": \"sentence_transformers\",\n",
+ " \"model\": \"all-MiniLM-L6-v2\" # 384-dimensional embeddings\n",
+ " },\n",
+ " \"extraction\": {\n",
+ " \"provider\": \"groq\",\n",
+ " \"model\": \"llama-3.1-8b-instant\",\n",
+ " \"temperature\": 0.0\n",
+ " },\n",
+ " \"vector_store\": {\n",
+ " \"provider\": \"faiss\",\n",
+ " \"dimension\": 384\n",
+ " },\n",
+ " \"knowledge_graph\": {\n",
+ " \"backend\": \"networkx\",\n",
+ " \"merge_entities\": True\n",
+ " }\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=384)\n",
+ "\n",
+ "print(\"Semantica configured for drug discovery pipeline.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (PubMed RSS Feed)\n",
+ "\n",
+ "Ingest biomedical data from PubMed RSS feeds using FeedIngestor.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, FileIngestor\n",
+ "import os\n",
+ "\n",
+ "# Create data directory if it doesn't exist\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "# Option 1: Ingest from PubMed RSS feed (real data source)\n",
+ "# PubMed RSS feed for drug discovery research\n",
+ "pubmed_rss_url = \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+discovery&limit=10&sort=pub_date&fc=article_type\"\n",
+ "\n",
+ "try:\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " # Ingest from PubMed RSS feed\n",
+ " feed_documents = feed_ingestor.ingest(pubmed_rss_url, method=\"rss\")\n",
+ " print(f\"Ingested {len(feed_documents)} documents from PubMed RSS feed\")\n",
+ " documents = feed_documents\n",
+ "except Exception as e:\n",
+ " print(f\"RSS feed ingestion failed (using sample data): {e}\")\n",
+ " # Fallback: Sample drug and protein data\n",
+ " sample_drug_data = \"\"\"\n",
+ " Aspirin (acetylsalicylic acid) is a medication used to reduce pain, fever, or inflammation. \n",
+ " It targets cyclooxygenase enzymes COX-1 and COX-2. Aspirin is commonly used for cardiovascular protection.\n",
+ " Ibuprofen is a nonsteroidal anti-inflammatory drug (NSAID) that targets COX-1 and COX-2 enzymes.\n",
+ " Metformin is an antidiabetic medication that targets AMP-activated protein kinase (AMPK).\n",
+ " Insulin targets the insulin receptor (INSR) to regulate glucose metabolism.\n",
+ " Warfarin is an anticoagulant that targets vitamin K epoxide reductase complex subunit 1 (VKORC1).\n",
+ " Atorvastatin is a statin medication that targets HMG-CoA reductase.\n",
+ " \"\"\"\n",
+ " \n",
+ " # Save sample data\n",
+ " with open(\"data/sample_drugs.txt\", \"w\") as f:\n",
+ " f.write(sample_drug_data)\n",
+ " \n",
+ " # Ingest from file\n",
+ " file_ingestor = FileIngestor()\n",
+ " documents = file_ingestor.ingest(\"data/sample_drugs.txt\")\n",
+ " print(f\"Ingested {len(documents)} documents from sample data\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 2: Text Normalization & Cleaning\n",
+ "\n",
+ "Normalize and clean ingested text data using the normalize module.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "\n",
+ "# Normalize and clean text data\n",
+ "normalizer = TextNormalizer()\n",
+ "\n",
+ "# Normalize all documents\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True,\n",
+ " lowercase=False # Preserve drug names (case-sensitive)\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "print(f\"Sample normalized text (first 200 chars): {normalized_documents[0][:200] if normalized_documents else 'N/A'}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 3: Advanced Chunking (Entity-Aware)\n",
+ "\n",
+ "Use entity-aware chunking to preserve drug/protein entity boundaries for GraphRAG.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.split import TextSplitter, EntityAwareChunker\n",
+ "\n",
+ "# Use entity-aware chunking to preserve drug/protein entity boundaries\n",
+ "# This is crucial for GraphRAG workflows to maintain entity context\n",
+ "splitter = TextSplitter(\n",
+ " method=\"entity_aware\",\n",
+ " ner_method=\"llm\", # Use LLM for better entity recognition\n",
+ " chunk_size=1000,\n",
+ " chunk_overlap=200\n",
+ ")\n",
+ "\n",
+ "# Alternative: Use EntityAwareChunker directly\n",
+ "entity_chunker = EntityAwareChunker(\n",
+ " chunk_size=1000,\n",
+ " chunk_overlap=200,\n",
+ " ner_method=\"llm\",\n",
+ " preserve_entities=True\n",
+ ")\n",
+ "\n",
+ "# Chunk normalized documents\n",
+ "chunked_documents = []\n",
+ "for doc_text in normalized_documents:\n",
+ " chunks = splitter.split(doc_text)\n",
+ " chunked_documents.extend(chunks)\n",
+ "\n",
+ "print(f\"Created {len(chunked_documents)} chunks using entity-aware chunking\")\n",
+ "print(f\"Sample chunk (first 300 chars): {chunked_documents[0].content[:300] if chunked_documents else 'N/A'}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 4: Entity Extraction & Knowledge Graph Construction\n",
+ "\n",
+ "Extract drug and protein entities, then build knowledge graph.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Convert chunks to document format for entity extraction\n",
+ "# Chunks from TextSplitter have content attribute\n",
+ "chunk_docs = []\n",
+ "for chunk in chunked_documents:\n",
+ " # Create a simple document-like object\n",
+ " doc_content = chunk.content if hasattr(chunk, 'content') else str(chunk)\n",
+ " chunk_docs.append(doc_content)\n",
+ "\n",
+ "# Build knowledge base with entity extraction\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=chunk_docs,\n",
+ " custom_entity_types=[\"Drug\", \"Protein\", \"Target\", \"Compound\", \"Enzyme\", \"Receptor\"],\n",
+ " embeddings=True,\n",
+ " graph=True\n",
+ ")\n",
+ "\n",
+ "# Extract entities\n",
+ "entities = result[\"entities\"]\n",
+ "drugs = [e for e in entities if e.get(\"type\") == \"Drug\" or \"drug\" in e.get(\"type\", \"\").lower()]\n",
+ "proteins = [e for e in entities if e.get(\"type\") == \"Protein\" or \"protein\" in e.get(\"type\", \"\").lower()]\n",
+ "\n",
+ "print(f\"Extracted {len(drugs)} drugs and {len(proteins)} proteins\")\n",
+ "print(f\"Sample drugs: {[d.get('text', '')[:30] for d in drugs[:3]]}\")\n",
+ "print(f\"Sample proteins: {[p.get('text', '')[:30] for p in proteins[:3]]}\")\n",
+ "\n",
+ "# Get knowledge graph\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "print(f\"Knowledge graph contains {len(kg.get('entities', []))} entities and {len(kg.get('relationships', []))} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 5: Vector Store Population & Embedding Generation\n",
+ "\n",
+ "Generate embeddings and populate vector store for similarity search.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 4-5: Vector Store & Similarity Search\n",
+ "\n",
+ "Generate embeddings and populate vector store for similarity search.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 6: GraphRAG - Hybrid Vector + Graph Retrieval\n",
+ "\n",
+ "Use AgentContext for GraphRAG to combine vector similarity search with knowledge graph traversal.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.context import AgentContext\n",
+ "\n",
+ "# Initialize GraphRAG context with vector store and knowledge graph\n",
+ "context = AgentContext(vector_store=vector_store, knowledge_graph=kg)\n",
+ "\n",
+ "# Example GraphRAG query: Find drugs and their targets\n",
+ "query = \"What drugs target COX enzymes?\"\n",
+ "print(f\"Query: {query}\\n\")\n",
+ "\n",
+ "# Retrieve using GraphRAG (hybrid vector + graph retrieval)\n",
+ "results = context.retrieve(\n",
+ " query,\n",
+ " max_results=10,\n",
+ " use_graph=True, # Enable graph traversal\n",
+ " expand_graph=True, # Expand graph relationships\n",
+ " include_entities=True, # Include related entities\n",
+ " include_relationships=True # Include relationships\n",
+ ")\n",
+ "\n",
+ "print(f\"GraphRAG retrieved {len(results)} results:\\n\")\n",
+ "for i, result in enumerate(results[:5], 1):\n",
+ " print(f\"{i}. Score: {result.get('score', 0):.3f}\")\n",
+ " print(f\" Content: {result.get('content', '')[:200]}...\")\n",
+ " if result.get('related_entities'):\n",
+ " print(f\" Related entities: {len(result['related_entities'])}\")\n",
+ " print()\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 7: Similarity Search & Interaction Prediction\n",
+ "\n",
+ "Use vector similarity to find similar drugs and predict interactions.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.embeddings import EmbeddingGenerator\n",
+ "\n",
+ "# Generate embeddings for drugs and proteins\n",
+ "embedding_gen = EmbeddingGenerator(provider=\"sentence_transformers\", model=\"all-MiniLM-L6-v2\")\n",
+ "\n",
+ "# Create drug embeddings\n",
+ "drug_texts = [f\"{d.get('text', '')} {d.get('description', '')}\" for d in drugs]\n",
+ "drug_embeddings = embedding_gen.generate_embeddings(drug_texts)\n",
+ "\n",
+ "# Store in vector store\n",
+ "drug_ids = vector_store.store_vectors(\n",
+ " vectors=drug_embeddings,\n",
+ " metadata=[{\"type\": \"drug\", \"name\": d.get(\"text\", \"\")} for d in drugs]\n",
+ ")\n",
+ "\n",
+ "print(f\"Stored {len(drug_ids)} drug embeddings in vector store\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 8: Knowledge Graph Visualization\n",
+ "\n",
+ "Visualize drug-target knowledge graph and relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 6: Similarity Search & Interaction Prediction\n",
+ "\n",
+ "Use vector similarity to find similar drugs and predict interactions.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Example: Find drugs similar to Aspirin\n",
+ "query_drug = \"Aspirin\"\n",
+ "query_embedding = embedding_gen.generate_embeddings([query_drug])[0]\n",
+ "\n",
+ "# Search for similar drugs\n",
+ "similar_drugs = vector_store.search_vectors(query_embedding, k=5)\n",
+ "\n",
+ "print(f\"Drugs similar to '{query_drug}':\")\n",
+ "for i, result in enumerate(similar_drugs, 1):\n",
+ " print(f\"{i}. {result['metadata'].get('name', 'Unknown')} (similarity: {result['score']:.3f})\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 7-8: Knowledge Graph & Visualization\n",
+ "\n",
+ "Build drug-target knowledge graph and visualize relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "# Get knowledge graph from result\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "\n",
+ "# Visualize drug-target relationships\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(\n",
+ " kg,\n",
+ " output_path=\"drug_target_kg.html\",\n",
+ " layout=\"spring\",\n",
+ " node_size=20\n",
+ ")\n",
+ "\n",
+ "print(\"Knowledge graph visualization saved to drug_target_kg.html\")\n",
+ "print(f\"Graph contains {len(kg.get('entities', []))} entities and {len(kg.get('relationships', []))} relationships\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb b/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb
new file mode 100644
index 00000000..86fded2e
--- /dev/null
+++ b/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb
@@ -0,0 +1,311 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb)\n",
+ "\n",
+ "# Genomic Variant Analysis - Graph Analytics & Pathway Analysis\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **genomic variant analysis** using Semantica with focus on **graph analytics**, **pathway analysis**, and **temporal knowledge graphs**. The pipeline analyzes genomic data to extract variant entities, build temporal genomic knowledge graphs, and analyze disease associations through reasoning.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Graph Analytics Focus**: Emphasizes graph reasoning, centrality measures, and pathway analysis\n",
+ "- **Temporal Analysis**: Builds temporal genomic knowledge graphs to track variant evolution\n",
+ "- **Disease Association**: Analyzes relationships between variants, genes, and diseases\n",
+ "- **Pathway Analysis**: Uses graph traversal to identify biological pathways\n",
+ "- **Impact Prediction**: Predicts variant impact using graph-based reasoning\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: Genomic Data Ingestion\n",
+ "3. **Phase 2**: Variant Entity Extraction\n",
+ "4. **Phase 3**: Temporal Knowledge Graph Construction\n",
+ "5. **Phase 4**: Graph Analytics (Centrality, Communities)\n",
+ "6. **Phase 5**: Pathway Analysis & Reasoning\n",
+ "7. **Phase 6**: Disease Association Analysis\n",
+ "8. **Phase 7**: Visualization & Export\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.kg import KnowledgeGraphBuilder\n",
+ "from semantica.reasoning import GraphReasoner\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Genomic_Variant_Analysis\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\", \"temporal\": True}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "print(\"Configured for genomic variant analysis with graph analytics focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (bioRxiv RSS Feed)\n",
+ "\n",
+ "Ingest genomic variant data from bioRxiv RSS feeds using FeedIngestor.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, FileIngestor\n",
+ "import os\n",
+ "\n",
+ "# Create data directory if it doesn't exist\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "# Option 1: Ingest from bioRxiv RSS feed (real data source)\n",
+ "# bioRxiv RSS feed for genomic variant research\n",
+ "biorxiv_rss_url = \"https://connect.biorxiv.org/biorxiv_xml.php?subject=genetics\"\n",
+ "\n",
+ "try:\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " # Ingest from bioRxiv RSS feed\n",
+ " feed_documents = feed_ingestor.ingest(biorxiv_rss_url, method=\"rss\")\n",
+ " print(f\"Ingested {len(feed_documents)} documents from bioRxiv RSS feed\")\n",
+ " documents = feed_documents\n",
+ "except Exception as e:\n",
+ " print(f\"RSS feed ingestion failed (using sample data): {e}\")\n",
+ " # Fallback: Sample genomic variant data\n",
+ " variant_data = \"\"\"\n",
+ " Variant rs699 is located in the AGT gene and associated with hypertension.\n",
+ " Variant rs7412 in APOE gene is linked to Alzheimer's disease risk.\n",
+ " BRCA1 variant c.5266dupC increases breast cancer susceptibility.\n",
+ " CFTR variant F508del causes cystic fibrosis.\n",
+ " Variant rs1800566 in NAT2 gene affects drug metabolism.\n",
+ " \"\"\"\n",
+ " \n",
+ " with open(\"data/variants.txt\", \"w\") as f:\n",
+ " f.write(variant_data)\n",
+ " \n",
+ " documents = FileIngestor().ingest(\"data/variants.txt\")\n",
+ " print(f\"Ingested {len(documents)} documents from sample data\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 2: Text Normalization & Deduplication\n",
+ "\n",
+ "Normalize genomic data and detect duplicate variants.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.deduplication import DuplicateDetector\n",
+ "\n",
+ "# Normalize genomic data\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Build knowledge base first to get entities for deduplication\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=normalized_documents,\n",
+ " custom_entity_types=[\"Variant\", \"Gene\", \"Disease\", \"Pathway\"],\n",
+ " graph=True,\n",
+ " temporal=True\n",
+ ")\n",
+ "\n",
+ "# Detect duplicate variants\n",
+ "entities = result[\"entities\"]\n",
+ "variants = [e for e in entities if e.get(\"type\") == \"Variant\" or \"variant\" in e.get(\"type\", \"\").lower()]\n",
+ "\n",
+ "detector = DuplicateDetector()\n",
+ "duplicates = detector.detect_duplicates(variants, threshold=0.9)\n",
+ "deduplicated_variants = detector.resolve_duplicates(variants, duplicates)\n",
+ "\n",
+ "print(f\"Detected {len(duplicates)} duplicate variant groups\")\n",
+ "print(f\"Deduplicated: {len(variants)} -> {len(deduplicated_variants)} unique variants\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 3: Temporal Knowledge Graph Construction\n",
+ "\n",
+ "Build temporal knowledge graph with temporal query capabilities.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphBuilder, TemporalGraphQuery\n",
+ "\n",
+ "# Get knowledge graph from result\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "\n",
+ "# Initialize temporal graph query engine\n",
+ "temporal_query = TemporalGraphQuery(\n",
+ " enable_temporal_reasoning=True,\n",
+ " temporal_granularity=\"day\"\n",
+ ")\n",
+ "\n",
+ "# Query graph at specific time point\n",
+ "# Example: Query variants active on a specific date\n",
+ "query_results = temporal_query.query_at_time(\n",
+ " kg,\n",
+ " query={\"type\": \"Variant\"},\n",
+ " at_time=\"2024-01-01\"\n",
+ ")\n",
+ "\n",
+ "# Analyze temporal evolution\n",
+ "evolution = temporal_query.analyze_evolution(kg)\n",
+ "\n",
+ "print(f\"Built temporal KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"Temporal queries: {len(query_results)} variants at query time\")\n",
+ "print(f\"Graph emphasizes: graph analytics, pathway analysis, temporal reasoning\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphAnalytics\n",
+ "\n",
+ "# Perform graph analytics (centrality, communities)\n",
+ "analytics = GraphAnalytics(kg)\n",
+ "centrality = analytics.calculate_centrality(method=\"betweenness\")\n",
+ "communities = analytics.detect_communities()\n",
+ "\n",
+ "# Use reasoning for pathway analysis\n",
+ "reasoner = GraphReasoner(kg)\n",
+ "pathways = reasoner.find_paths(\n",
+ " source_type=\"Variant\",\n",
+ " target_type=\"Disease\",\n",
+ " max_hops=3\n",
+ ")\n",
+ "\n",
+ "# Temporal pattern detection\n",
+ "temporal_patterns = temporal_query.detect_temporal_patterns(kg, pattern_type=\"sequence\")\n",
+ "\n",
+ "print(f\"Graph analytics: {len(communities)} communities detected\")\n",
+ "print(f\"Pathway analysis: {len(pathways)} variant-disease pathways found\")\n",
+ "print(f\"Temporal patterns: {len(temporal_patterns)} temporal patterns detected\")\n",
+ "print(\"This cookbook emphasizes graph analytics, temporal reasoning, and pathway analysis\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 6-7: Visualization & Export\n",
+ "\n",
+ "Visualize temporal knowledge graph and export results.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "from semantica.export import GraphExporter\n",
+ "\n",
+ "# Visualize temporal knowledge graph\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"genomic_variant_kg.html\", layout=\"hierarchical\")\n",
+ "\n",
+ "# Export graph\n",
+ "exporter = GraphExporter()\n",
+ "exporter.export(kg, format=\"graphml\", output_path=\"genomic_variant_kg.graphml\")\n",
+ "\n",
+ "print(\"Visualization and export complete\")\n",
+ "print(\"\\n=== Pipeline Summary ===\")\n",
+ "print(f\"✓ Ingested {len(documents)} documents from bioRxiv RSS feed\")\n",
+ "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
+ "print(f\"✓ Deduplicated {len(variants)} variants to {len(deduplicated_variants)} unique variants\")\n",
+ "print(f\"✓ Built temporal KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"✓ Detected {len(communities)} communities and {len(pathways)} pathways\")\n",
+ "print(f\"✓ This cookbook demonstrates graph analytics, temporal reasoning, and pathway analysis\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb b/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb
new file mode 100644
index 00000000..2dee6a96
--- /dev/null
+++ b/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb
@@ -0,0 +1,298 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb)\n",
+ "\n",
+ "# DeFi Protocol Intelligence - Risk Assessment & Ontology Reasoning\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **DeFi protocol intelligence** using Semantica with focus on **risk assessment**, **ontology-based reasoning**, and **relationship analysis**. The pipeline ingests DeFi data, extracts protocol entities, builds DeFi knowledge graphs, and assesses risks using graph reasoning.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Risk Assessment Focus**: Emphasizes KG construction and reasoning for risk evaluation\n",
+ "- **Ontology-Based Reasoning**: Uses domain ontologies for DeFi protocol analysis\n",
+ "- **Relationship Analysis**: Analyzes protocol relationships and dependencies\n",
+ "- **Yield Optimization**: Identifies optimization opportunities through graph analysis\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: DeFi Data Ingestion\n",
+ "3. **Phase 2**: Protocol Entity Extraction\n",
+ "4. **Phase 3**: DeFi Knowledge Graph Construction\n",
+ "5. **Phase 4**: Ontology Generation & Reasoning\n",
+ "6. **Phase 5**: Risk Assessment Analysis\n",
+ "7. **Phase 6**: Relationship Analysis\n",
+ "8. **Phase 7**: Visualization & Export\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.ontology import OntologyGenerator\n",
+ "from semantica.reasoning import GraphReasoner\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"DeFi_Protocol_Intelligence\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\"},\n",
+ " \"ontology\": {\"base_uri\": \"https://defi.example.org/ontology/\"}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "print(\"Configured for DeFi protocol intelligence with ontology reasoning focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (CoinDesk RSS Feed)\n",
+ "\n",
+ "Ingest DeFi protocol data from CoinDesk RSS feeds using FeedIngestor.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, FileIngestor\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "# Option 1: Ingest from CoinDesk RSS feed (real data source)\n",
+ "coindesk_rss_url = \"https://www.coindesk.com/arc/outboundfeeds/rss/\"\n",
+ "\n",
+ "try:\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " feed_documents = feed_ingestor.ingest(coindesk_rss_url, method=\"rss\")\n",
+ " print(f\"Ingested {len(feed_documents)} documents from CoinDesk RSS feed\")\n",
+ " documents = feed_documents\n",
+ "except Exception as e:\n",
+ " print(f\"RSS feed ingestion failed (using sample data): {e}\")\n",
+ " defi_data = \"\"\"\n",
+ " Uniswap is a decentralized exchange protocol with high liquidity pools.\n",
+ " Aave is a lending protocol that offers variable interest rates.\n",
+ " Compound is a money market protocol for lending and borrowing.\n",
+ " MakerDAO uses collateralized debt positions (CDPs) for stablecoin generation.\n",
+ " \"\"\"\n",
+ " with open(\"data/defi_protocols.txt\", \"w\") as f:\n",
+ " f.write(defi_data)\n",
+ " documents = FileIngestor().ingest(\"data/defi_protocols.txt\")\n",
+ " print(f\"Ingested {len(documents)} documents from sample data\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 2: Text Normalization & Advanced Chunking\n",
+ "\n",
+ "Normalize protocol names and use ontology-aware chunking to preserve protocol concepts.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.split import TextSplitter\n",
+ "\n",
+ "# Normalize protocol names and text\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Use ontology-aware chunking to preserve protocol ontology concepts\n",
+ "# This will be applied after ontology generation\n",
+ "splitter = TextSplitter(method=\"recursive\", chunk_size=1000, chunk_overlap=200)\n",
+ "chunked_docs = []\n",
+ "for doc_text in normalized_documents:\n",
+ " chunks = splitter.split(doc_text)\n",
+ " chunked_docs.extend([chunk.content if hasattr(chunk, 'content') else str(chunk) for chunk in chunks])\n",
+ "\n",
+ "print(f\"Created {len(chunked_docs)} chunks\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 3: Knowledge Graph Construction & Conflict Detection\n",
+ "\n",
+ "Build DeFi knowledge graph and detect conflicts from multiple sources.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.conflicts import ConflictDetector\n",
+ "\n",
+ "# Build DeFi knowledge graph\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=chunked_docs,\n",
+ " custom_entity_types=[\"Protocol\", \"Token\", \"Pool\", \"Transaction\", \"Risk\"],\n",
+ " graph=True\n",
+ ")\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "entities = result[\"entities\"]\n",
+ "\n",
+ "# Detect conflicts from multiple sources\n",
+ "detector = ConflictDetector()\n",
+ "conflicts = detector.detect_conflicts(entities, kg.get(\"relationships\", []))\n",
+ "\n",
+ "print(f\"Built DeFi KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"Detected {len(conflicts)} conflicts from multiple sources\")\n",
+ "\n",
+ "# Resolve conflicts using highest confidence strategy\n",
+ "if conflicts:\n",
+ " resolved = detector.resolve_conflicts(conflicts, strategy=\"highest_confidence\")\n",
+ " print(f\"Resolved {len(resolved)} conflicts\")\n",
+ "print(\"Focus: Risk assessment, ontology reasoning, relationship analysis\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Generate DeFi ontology\n",
+ "ontology_gen = OntologyGenerator(base_uri=\"https://defi.example.org/ontology/\")\n",
+ "ontology = ontology_gen.generate_from_graph(kg)\n",
+ "\n",
+ "# Apply ontology-aware chunking using the generated ontology\n",
+ "ontology_splitter = TextSplitter(\n",
+ " method=\"ontology_aware\",\n",
+ " ontology=ontology,\n",
+ " chunk_size=1000,\n",
+ " chunk_overlap=200\n",
+ ")\n",
+ "\n",
+ "# Re-chunk with ontology awareness\n",
+ "ontology_chunks = []\n",
+ "for doc_text in normalized_documents[:3]: # Apply to subset for demonstration\n",
+ " chunks = ontology_splitter.split(doc_text)\n",
+ " ontology_chunks.extend([chunk.content if hasattr(chunk, 'content') else str(chunk) for chunk in chunks])\n",
+ "\n",
+ "print(f\"Generated DeFi ontology with {len(ontology.get('classes', []))} classes\")\n",
+ "print(f\"Created {len(ontology_chunks)} ontology-aware chunks\")\n",
+ "\n",
+ "# Use reasoning for risk assessment\n",
+ "reasoner = GraphReasoner(kg)\n",
+ "risk_patterns = reasoner.find_patterns(pattern_type=\"risk\")\n",
+ "\n",
+ "print(f\"Identified {len(risk_patterns)} risk patterns\")\n",
+ "print(\"This cookbook emphasizes ontology reasoning, ontology-aware chunking, and risk assessment\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 5-6: Visualization & Export\n",
+ "\n",
+ "Visualize DeFi protocol knowledge graph and export ontology.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "from semantica.export import GraphExporter\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"defi_protocol_kg.html\")\n",
+ "\n",
+ "exporter = GraphExporter()\n",
+ "exporter.export(kg, format=\"rdf\", output_path=\"defi_ontology.ttl\")\n",
+ "\n",
+ "print(\"DeFi protocol intelligence analysis complete\")\n",
+ "print(\"\\n=== Pipeline Summary ===\")\n",
+ "print(f\"✓ Ingested {len(documents)} documents from CoinDesk RSS feed\")\n",
+ "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
+ "print(f\"✓ Detected and resolved {len(conflicts)} conflicts\")\n",
+ "print(f\"✓ Generated ontology with {len(ontology.get('classes', []))} classes\")\n",
+ "print(f\"✓ Created {len(ontology_chunks)} ontology-aware chunks\")\n",
+ "print(f\"✓ Identified {len(risk_patterns)} risk patterns\")\n",
+ "print(f\"✓ Emphasizes: KG construction, ontology reasoning, ontology-aware chunking, risk assessment\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb b/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb
new file mode 100644
index 00000000..7d79b7ea
--- /dev/null
+++ b/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb
@@ -0,0 +1,248 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb)\n",
+ "\n",
+ "# Transaction Network Analysis - Pattern Detection & Graph Analytics\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **blockchain transaction network analysis** using Semantica with focus on **pattern detection**, **network analytics**, and **real-time processing**. The pipeline analyzes blockchain transaction networks to detect patterns, identify whale movements, and analyze token flows.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Pattern Detection**: Emphasizes graph analytics for transaction pattern recognition\n",
+ "- **Network Analytics**: Uses centrality measures and community detection\n",
+ "- **Real-Time Processing**: Demonstrates stream processing capabilities\n",
+ "- **Whale Tracking**: Identifies large transaction movements\n",
+ "- **Flow Analysis**: Analyzes token flows through the network\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: Blockchain Data Ingestion (Stream/File)\n",
+ "3. **Phase 2**: Transaction Entity Extraction\n",
+ "4. **Phase 3**: Transaction Network Graph Construction\n",
+ "5. **Phase 4**: Graph Analytics (Centrality, Communities)\n",
+ "6. **Phase 5**: Pattern Detection & Whale Tracking\n",
+ "7. **Phase 6**: Flow Analysis\n",
+ "8. **Phase 7**: Visualization & Export\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.kg import GraphAnalytics\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Transaction_Network_Analysis\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\"}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "print(\"Configured for transaction network analysis with graph analytics focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (Blockchain API Structure)\n",
+ "\n",
+ "Ingest blockchain transaction data using WebIngestor for API structure.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import WebIngestor, FileIngestor\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "# Option 1: Ingest from blockchain API (simulated structure)\n",
+ "# In production, use actual blockchain.com or Etherscan API\n",
+ "blockchain_api_url = \"https://api.blockchain.info/stats\" # Example API endpoint\n",
+ "\n",
+ "try:\n",
+ " web_ingestor = WebIngestor()\n",
+ " # Ingest from blockchain API\n",
+ " api_documents = web_ingestor.ingest(blockchain_api_url, method=\"url\")\n",
+ " print(f\"Ingested {len(api_documents)} documents from blockchain API\")\n",
+ " documents = api_documents\n",
+ "except Exception as e:\n",
+ " print(f\"API ingestion failed (using sample data): {e}\")\n",
+ " # Fallback: Sample blockchain transaction data\n",
+ " tx_data = \"\"\"\n",
+ " Transaction 0x123 transfers 1000 ETH from wallet A to wallet B.\n",
+ " Transaction 0x456 transfers 500 BTC from wallet C to wallet D.\n",
+ " Large transaction 0x789 moves 10000 ETH (whale movement) from wallet E to wallet F.\n",
+ " Transaction 0xabc transfers 200 USDT from wallet G to wallet H.\n",
+ " Transaction 0xdef transfers 5000 ETH from wallet I to wallet J.\n",
+ " \"\"\"\n",
+ " with open(\"data/transactions.txt\", \"w\") as f:\n",
+ " f.write(tx_data)\n",
+ " documents = FileIngestor().ingest(\"data/transactions.txt\")\n",
+ " print(f\"Ingested {len(documents)} documents from sample data\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 2: Text Normalization & Deduplication\n",
+ "\n",
+ "Normalize addresses and detect duplicate transactions.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.deduplication import DuplicateDetector\n",
+ "\n",
+ "# Normalize addresses and transaction data\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Build transaction network graph\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=normalized_documents,\n",
+ " custom_entity_types=[\"Transaction\", \"Wallet\", \"Address\", \"Block\", \"Flow\"],\n",
+ " graph=True\n",
+ ")\n",
+ "\n",
+ "# Detect duplicate transactions\n",
+ "entities = result[\"entities\"]\n",
+ "transactions = [e for e in entities if e.get(\"type\") == \"Transaction\" or \"transaction\" in e.get(\"type\", \"\").lower()]\n",
+ "\n",
+ "detector = DuplicateDetector()\n",
+ "duplicates = detector.detect_duplicates(transactions, threshold=0.9)\n",
+ "deduplicated_transactions = detector.resolve_duplicates(transactions, duplicates)\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "print(f\"Built transaction network with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"Deduplicated: {len(transactions)} -> {len(deduplicated_transactions)} unique transactions\")\n",
+ "print(\"Focus: Pattern detection, network analytics, real-time processing\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Perform network analytics\n",
+ "analytics = GraphAnalytics(kg)\n",
+ "centrality = analytics.calculate_centrality(method=\"degree\")\n",
+ "communities = analytics.detect_communities()\n",
+ "\n",
+ "# Detect whale movements (large transactions)\n",
+ "whale_wallets = [e for e in kg.get(\"entities\", []) \n",
+ " if e.get(\"type\") == \"Wallet\" and \n",
+ " any(\"large\" in str(r.get(\"predicate\", \"\")).lower() \n",
+ " for r in kg.get(\"relationships\", []) \n",
+ " if r.get(\"source\") == e.get(\"id\"))]\n",
+ "\n",
+ "print(f\"Network analytics: {len(communities)} communities, {len(centrality)} central nodes\")\n",
+ "print(f\"Whale tracking: {len(whale_wallets)} large transaction wallets identified\")\n",
+ "print(\"\\n=== Pipeline Summary ===\")\n",
+ "print(f\"✓ Ingested {len(documents)} documents from blockchain API\")\n",
+ "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
+ "print(f\"✓ Deduplicated {len(transactions)} transactions to {len(deduplicated_transactions)} unique\")\n",
+ "print(f\"✓ Detected {len(communities)} communities and {len(whale_wallets)} whale wallets\")\n",
+ "print(f\"✓ This cookbook emphasizes graph analytics and pattern detection\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 6-7: Visualization & Export\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"transaction_network.html\", layout=\"force-directed\")\n",
+ "\n",
+ "print(\"Transaction network analysis complete\")\n",
+ "print(\"Emphasizes: Graph analytics, pattern detection, network analysis\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb b/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb
new file mode 100644
index 00000000..ed81abd3
--- /dev/null
+++ b/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb
@@ -0,0 +1,307 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb)\n",
+ "\n",
+ "# Real-Time Anomaly Detection - Stream Processing & Temporal KGs\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **real-time anomaly detection** using Semantica with focus on **stream ingestion**, **temporal knowledge graphs**, and **pattern detection**. The pipeline streams security logs in real-time, builds temporal knowledge graphs, and detects anomalies using pattern detection.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Stream Processing**: Emphasizes real-time log streaming and processing\n",
+ "- **Temporal Knowledge Graphs**: Builds temporal KGs to track events over time\n",
+ "- **Pattern Detection**: Uses graph patterns to identify anomalies\n",
+ "- **Automated Alerting**: Generates alerts for detected anomalies\n",
+ "- **Real-Time Processing**: Demonstrates stream ingestion capabilities\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: Stream Security Log Ingestion\n",
+ "3. **Phase 2**: Real-Time Log Parsing\n",
+ "4. **Phase 3**: Entity Extraction (Log, Event, IP, User, Alert)\n",
+ "5. **Phase 4**: Temporal Knowledge Graph Construction\n",
+ "6. **Phase 5**: Pattern Detection\n",
+ "7. **Phase 6**: Anomaly Detection\n",
+ "8. **Phase 7**: Alert Generation & Visualization\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.ingest import StreamIngestor\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Real_Time_Anomaly_Detection\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\", \"temporal\": True}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "print(\"Configured for real-time anomaly detection with stream processing focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (CVE RSS Feed & Kafka Stream)\n",
+ "\n",
+ "Ingest security data from CVE RSS feeds and simulated Kafka streams.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, StreamIngestor, FileIngestor\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "# Option 1: Ingest from CVE RSS feed (real data source)\n",
+ "cve_rss_url = \"https://cve.mitre.org/data/downloads/allitems.xml\" # CVE feed\n",
+ "\n",
+ "documents = []\n",
+ "try:\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " feed_documents = feed_ingestor.ingest(cve_rss_url, method=\"rss\")\n",
+ " print(f\"Ingested {len(feed_documents)} documents from CVE RSS feed\")\n",
+ " documents.extend(feed_documents)\n",
+ "except Exception as e:\n",
+ " print(f\"CVE RSS feed ingestion failed: {e}\")\n",
+ "\n",
+ "# Option 2: Simulate Kafka stream (in production, use actual Kafka)\n",
+ "# stream_ingestor = StreamIngestor()\n",
+ "# stream_documents = stream_ingestor.ingest(\"kafka://localhost:9092/security-logs\", method=\"kafka\")\n",
+ "\n",
+ "# Fallback: Sample security log stream data\n",
+ "security_logs = \"\"\"\n",
+ "2024-01-01 10:00:00 - Login attempt from IP 192.168.1.100 user admin\n",
+ "2024-01-01 10:01:00 - Failed login from IP 192.168.1.100 user admin\n",
+ "2024-01-01 10:02:00 - Multiple failed logins from IP 192.168.1.100 user admin\n",
+ "2024-01-01 10:03:00 - Unusual activity detected from IP 192.168.1.100\n",
+ "2024-01-01 10:04:00 - Alert: Potential brute force attack from IP 192.168.1.100\n",
+ "2024-01-01 10:05:00 - Login attempt from IP 192.168.1.101 user test\n",
+ "\"\"\"\n",
+ "\n",
+ "with open(\"data/security_logs.txt\", \"w\") as f:\n",
+ " f.write(security_logs)\n",
+ "\n",
+ "stream_documents = FileIngestor().ingest(\"data/security_logs.txt\")\n",
+ "documents.extend(stream_documents)\n",
+ "print(f\"Added {len(stream_documents)} documents from simulated stream\")\n",
+ "print(f\"Total documents: {len(documents)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 2: Text Normalization & Advanced Chunking\n",
+ "\n",
+ "Normalize log data and use sentence/recursive chunking for structured logs.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.split import TextSplitter\n",
+ "\n",
+ "# Normalize log data\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Use sentence chunking for log line boundaries (structured logs)\n",
+ "splitter = TextSplitter(method=\"sentence\", chunk_size=500, chunk_overlap=50)\n",
+ "# Alternative: recursive for hierarchical log structures\n",
+ "# splitter = TextSplitter(method=\"recursive\", chunk_size=500, chunk_overlap=50)\n",
+ "\n",
+ "chunked_docs = []\n",
+ "for doc_text in normalized_documents:\n",
+ " chunks = splitter.split(doc_text)\n",
+ " chunked_docs.extend([chunk.content if hasattr(chunk, 'content') else str(chunk) for chunk in chunks])\n",
+ "\n",
+ "print(f\"Created {len(chunked_docs)} chunks using sentence chunking\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 3-4: Temporal Knowledge Graph Construction\n",
+ "\n",
+ "Build full temporal KG with TemporalGraphQuery capabilities.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphBuilder, TemporalGraphQuery\n",
+ "\n",
+ "# Build temporal knowledge graph\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=chunked_docs,\n",
+ " custom_entity_types=[\"Log\", \"Event\", \"IP\", \"User\", \"Alert\", \"Attack\"],\n",
+ " graph=True,\n",
+ " temporal=True\n",
+ ")\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "\n",
+ "# Initialize temporal graph query engine\n",
+ "temporal_query = TemporalGraphQuery(\n",
+ " enable_temporal_reasoning=True,\n",
+ " temporal_granularity=\"minute\" # Fine-grained for real-time logs\n",
+ ")\n",
+ "\n",
+ "# Query graph at specific time point\n",
+ "query_results = temporal_query.query_at_time(\n",
+ " kg,\n",
+ " query={\"type\": \"Alert\"},\n",
+ " at_time=\"2024-01-01 10:04:00\"\n",
+ ")\n",
+ "\n",
+ "# Analyze temporal evolution\n",
+ "evolution = temporal_query.analyze_evolution(kg)\n",
+ "\n",
+ "print(f\"Built temporal KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"Temporal queries: {len(query_results)} alerts at query time\")\n",
+ "print(\"Focus: Stream processing, temporal KGs, pattern detection\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.reasoning import GraphReasoner\n",
+ "\n",
+ "# Detect anomaly patterns (e.g., multiple failed logins)\n",
+ "reasoner = GraphReasoner(kg)\n",
+ "anomaly_patterns = reasoner.find_patterns(pattern_type=\"anomaly\")\n",
+ "\n",
+ "# Temporal pattern detection\n",
+ "temporal_patterns = temporal_query.detect_temporal_patterns(kg, pattern_type=\"sequence\")\n",
+ "\n",
+ "# Identify suspicious IPs\n",
+ "suspicious_ips = [e for e in kg.get(\"entities\", []) \n",
+ " if e.get(\"type\") == \"IP\" and \n",
+ " any(\"alert\" in str(r.get(\"predicate\", \"\")).lower() \n",
+ " for r in kg.get(\"relationships\", []) \n",
+ " if r.get(\"target\") == e.get(\"id\"))]\n",
+ "\n",
+ "print(f\"Pattern detection: {len(anomaly_patterns)} anomaly patterns found\")\n",
+ "print(f\"Temporal patterns: {len(temporal_patterns)} temporal patterns detected\")\n",
+ "print(f\"Anomaly detection: {len(suspicious_ips)} suspicious IPs identified\")\n",
+ "print(\"This cookbook emphasizes stream processing, temporal KGs, and pattern detection\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 7: Visualization & Alert Generation\n",
+ "\n",
+ "Visualize temporal knowledge graph with anomaly alerts.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"anomaly_detection_kg.html\", layout=\"temporal\")\n",
+ "\n",
+ "print(\"Real-time anomaly detection analysis complete\")\n",
+ "print(\"\\n=== Pipeline Summary ===\")\n",
+ "print(f\"✓ Ingested {len(documents)} documents from CVE RSS feed and stream\")\n",
+ "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
+ "print(f\"✓ Created {len(chunked_docs)} chunks using sentence chunking\")\n",
+ "print(f\"✓ Built temporal KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"✓ Detected {len(anomaly_patterns)} anomaly patterns and {len(suspicious_ips)} suspicious IPs\")\n",
+ "print(f\"✓ Emphasizes: Stream processing, temporal KGs, pattern detection\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb b/cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb
new file mode 100644
index 00000000..6addff70
--- /dev/null
+++ b/cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb
@@ -0,0 +1,361 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb)\n",
+ "\n",
+ "# Threat Intelligence Hybrid RAG - Vector + Graph Retrieval\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **threat intelligence hybrid RAG** using Semantica with focus on **hybrid search**, **vector + graph retrieval**, and **context-aware queries**. The pipeline combines vector search with temporal knowledge graphs for advanced threat intelligence querying.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Hybrid RAG**: Combines vector similarity search with knowledge graph traversal\n",
+ "- **Vector + Graph Retrieval**: Uses both vector embeddings and graph relationships\n",
+ "- **Context-Aware Queries**: Provides context-aware retrieval for threat intelligence\n",
+ "- **Temporal Knowledge Graphs**: Builds temporal KGs for threat timeline analysis\n",
+ "- **Multi-hop Reasoning**: Follows relationships across the graph for deeper context\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: Threat Intelligence Data Ingestion\n",
+ "3. **Phase 2**: Entity Extraction (IOC, Campaign, Threat, Actor, TTP)\n",
+ "4. **Phase 3**: Temporal Knowledge Graph Construction\n",
+ "5. **Phase 4**: Embedding Generation & Vector Store\n",
+ "6. **Phase 5**: Hybrid Search Setup (Vector + Graph)\n",
+ "7. **Phase 6**: Context-Aware Query System\n",
+ "8. **Phase 7**: Visualization & Export\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu groq sentence-transformers\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.vector_store import VectorStore\n",
+ "from semantica.context import AgentContext\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Threat_Intelligence_Hybrid_RAG\",\n",
+ " \"embedding\": {\"provider\": \"sentence_transformers\", \"model\": \"all-MiniLM-L6-v2\"},\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"vector_store\": {\"provider\": \"faiss\", \"dimension\": 384},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\", \"temporal\": True}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=384)\n",
+ "print(\"Configured for threat intelligence hybrid RAG\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (Security RSS Feeds)\n",
+ "\n",
+ "Ingest threat intelligence data from multiple security RSS feeds.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, FileIngestor\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "# Ingest from multiple security RSS feeds (real data sources)\n",
+ "security_feeds = [\n",
+ " \"https://www.us-cert.gov/ncas/alerts.xml\", # US-CERT alerts\n",
+ " # Add more security feeds as needed\n",
+ "]\n",
+ "\n",
+ "documents = []\n",
+ "for feed_url in security_feeds:\n",
+ " try:\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " feed_documents = feed_ingestor.ingest(feed_url, method=\"rss\")\n",
+ " print(f\"Ingested {len(feed_documents)} documents from {feed_url}\")\n",
+ " documents.extend(feed_documents)\n",
+ " except Exception as e:\n",
+ " print(f\"Feed ingestion failed for {feed_url}: {e}\")\n",
+ "\n",
+ "# Fallback: Sample threat intelligence data\n",
+ "if not documents:\n",
+ " threat_data = \"\"\"\n",
+ " IOC: IP address 192.168.1.50 associated with APT28 campaign.\n",
+ " Threat actor APT28 uses TTP: Spear phishing and credential harvesting.\n",
+ " Campaign Operation GhostShell targets financial institutions.\n",
+ " Malware sample hash: abc123def456 linked to APT28 infrastructure.\n",
+ " IOC: Domain example-malicious.com linked to APT29 operations.\n",
+ " \"\"\"\n",
+ " with open(\"data/threat_intel.txt\", \"w\") as f:\n",
+ " f.write(threat_data)\n",
+ " documents = FileIngestor().ingest(\"data/threat_intel.txt\")\n",
+ " print(f\"Ingested {len(documents)} documents from sample data\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 2: Text Normalization & Advanced Chunking\n",
+ "\n",
+ "Normalize IOC data and use entity-aware/relation-aware chunking for threat relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.split import TextSplitter, EntityAwareChunker, RelationAwareChunker\n",
+ "from semantica.deduplication import DuplicateDetector\n",
+ "\n",
+ "# Normalize IOC data and threat intelligence\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Use entity-aware chunking to preserve threat entity boundaries for GraphRAG\n",
+ "entity_splitter = TextSplitter(\n",
+ " method=\"entity_aware\",\n",
+ " ner_method=\"llm\",\n",
+ " chunk_size=1000,\n",
+ " chunk_overlap=200\n",
+ ")\n",
+ "\n",
+ "# Alternative: relation-aware chunking to preserve threat relationship triplets\n",
+ "relation_splitter = TextSplitter(\n",
+ " method=\"relation_aware\",\n",
+ " chunk_size=1000,\n",
+ " chunk_overlap=200\n",
+ ")\n",
+ "\n",
+ "# Chunk with entity-aware (preserves IOC, Actor, Campaign boundaries)\n",
+ "chunked_docs = []\n",
+ "for doc_text in normalized_documents:\n",
+ " chunks = entity_splitter.split(doc_text)\n",
+ " chunked_docs.extend([chunk.content if hasattr(chunk, 'content') else str(chunk) for chunk in chunks])\n",
+ "\n",
+ "print(f\"Created {len(chunked_docs)} entity-aware chunks\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 3: Knowledge Graph Construction & Deduplication\n",
+ "\n",
+ "Build temporal knowledge graph and deduplicate threat entities.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Build knowledge base with both vectors and graph\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=chunked_docs,\n",
+ " custom_entity_types=[\"IOC\", \"Campaign\", \"Threat\", \"Actor\", \"TTP\", \"Malware\"],\n",
+ " embeddings=True,\n",
+ " graph=True,\n",
+ " temporal=True\n",
+ ")\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "entities = result[\"entities\"]\n",
+ "embeddings_data = result[\"embeddings\"]\n",
+ "\n",
+ "# Deduplicate threat entities (IOCs, actors, campaigns)\n",
+ "iocs = [e for e in entities if e.get(\"type\") == \"IOC\" or \"ioc\" in e.get(\"type\", \"\").lower()]\n",
+ "actors = [e for e in entities if e.get(\"type\") == \"Actor\" or \"actor\" in e.get(\"type\", \"\").lower()]\n",
+ "\n",
+ "detector = DuplicateDetector()\n",
+ "ioc_duplicates = detector.detect_duplicates(iocs, threshold=0.9)\n",
+ "actor_duplicates = detector.detect_duplicates(actors, threshold=0.9)\n",
+ "\n",
+ "deduplicated_iocs = detector.resolve_duplicates(iocs, ioc_duplicates)\n",
+ "deduplicated_actors = detector.resolve_duplicates(actors, actor_duplicates)\n",
+ "\n",
+ "print(f\"Built hybrid system: {len(kg.get('entities', []))} entities, {len(embeddings_data['vectors'])} vectors\")\n",
+ "print(f\"Deduplicated: {len(iocs)} -> {len(deduplicated_iocs)} unique IOCs\")\n",
+ "print(f\"Deduplicated: {len(actors)} -> {len(deduplicated_actors)} unique actors\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 4: Vector Store Population\n",
+ "\n",
+ "Store embeddings in vector store for hybrid retrieval.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Store embeddings in vector store\n",
+ "vector_store.store_vectors(\n",
+ " vectors=embeddings_data[\"vectors\"],\n",
+ " metadata=embeddings_data[\"metadata\"]\n",
+ ")\n",
+ "\n",
+ "print(f\"Stored {len(embeddings_data['vectors'])} embeddings in vector store\")\n",
+ "print(\"Focus: Hybrid RAG, vector + graph retrieval, context-aware queries\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.context import AgentContext\n",
+ "from semantica.embeddings import EmbeddingGenerator\n",
+ "\n",
+ "# Initialize enhanced GraphRAG context\n",
+ "context = AgentContext(vector_store=vector_store, knowledge_graph=kg)\n",
+ "\n",
+ "# Example hybrid query\n",
+ "query = \"What threats are associated with APT28?\"\n",
+ "print(f\"Query: {query}\\n\")\n",
+ "\n",
+ "# Generate query embedding\n",
+ "embedding_gen = EmbeddingGenerator(provider=\"sentence_transformers\", model=\"all-MiniLM-L6-v2\")\n",
+ "query_embedding = embedding_gen.generate_embeddings([query])[0]\n",
+ "\n",
+ "# Vector search\n",
+ "vector_results = vector_store.search_vectors(query_embedding, k=5)\n",
+ "\n",
+ "# Enhanced GraphRAG retrieval with graph expansion\n",
+ "graph_context = context.retrieve(\n",
+ " query,\n",
+ " max_results=10,\n",
+ " use_graph=True, # Enable graph traversal\n",
+ " expand_graph=True, # Expand graph relationships\n",
+ " include_entities=True, # Include related entities\n",
+ " include_relationships=True # Include relationships\n",
+ ")\n",
+ "\n",
+ "print(f\"Hybrid RAG results:\")\n",
+ "print(f\" - Vector search: {len(vector_results)} matches\")\n",
+ "print(f\" - GraphRAG retrieval: {len(graph_context)} context items with graph expansion\")\n",
+ "print(f\"\\nTop GraphRAG results:\")\n",
+ "for i, result in enumerate(graph_context[:3], 1):\n",
+ " print(f\"{i}. Score: {result.get('score', 0):.3f}\")\n",
+ " print(f\" Content: {result.get('content', '')[:150]}...\")\n",
+ " if result.get('related_entities'):\n",
+ " print(f\" Related entities: {len(result['related_entities'])}\")\n",
+ "print(\"\\nThis cookbook emphasizes enhanced GraphRAG with entity-aware chunking and deduplication\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 7: Visualization & Summary\n",
+ "\n",
+ "Visualize threat intelligence knowledge graph.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"threat_intelligence_kg.html\")\n",
+ "\n",
+ "print(\"Threat intelligence hybrid RAG analysis complete\")\n",
+ "print(\"\\n=== Pipeline Summary ===\")\n",
+ "print(f\"✓ Ingested {len(documents)} documents from security RSS feeds\")\n",
+ "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
+ "print(f\"✓ Created {len(chunked_docs)} entity-aware chunks\")\n",
+ "print(f\"✓ Deduplicated IOCs and actors\")\n",
+ "print(f\"✓ Built temporal KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"✓ Stored {len(embeddings_data['vectors'])} embeddings\")\n",
+ "print(f\"✓ Enhanced GraphRAG with graph expansion enabled\")\n",
+ "print(f\"✓ Emphasizes: Hybrid RAG, entity-aware chunking, vector + graph retrieval, context-aware queries\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb b/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb
new file mode 100644
index 00000000..a8ff3f0f
--- /dev/null
+++ b/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb
@@ -0,0 +1,224 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb)\n",
+ "\n",
+ "# Financial Data Integration (MCP) - Real-Time Market Data\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **financial data integration using MCP servers** with focus on **MCP server integration**, **real-time data ingestion**, and **multi-source financial KG construction**. The pipeline integrates Python/FastMCP servers to ingest market data, stock prices, and metrics into a financial knowledge graph.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **MCP Integration**: Showcases MCP (Model Context Protocol) server integration capability\n",
+ "- **Real-Time Data Ingestion**: Ingests live market data from MCP servers\n",
+ "- **Multi-Source Financial KG**: Builds comprehensive financial knowledge graphs from APIs\n",
+ "- **Real-Time Updates**: Demonstrates real-time data streaming and KG updates\n",
+ "- **API-Based Integration**: Connects to financial data APIs via MCP\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: MCP Server Setup & Connection\n",
+ "3. **Phase 2**: Real-Time Market Data Ingestion\n",
+ "4. **Phase 3**: Financial Entity Extraction\n",
+ "5. **Phase 4**: Financial Knowledge Graph Construction\n",
+ "6. **Phase 5**: Real-Time KG Updates\n",
+ "7. **Phase 6**: Visualization & Export\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.ingest import MCPIngestor\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Financial_Data_Integration_MCP\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\"}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "print(\"Configured for financial data integration with MCP focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (Alpha Vantage API & MCP Server)\n",
+ "\n",
+ "Ingest financial data from Alpha Vantage API and MCP servers.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import MCPIngestor, WebIngestor, FileIngestor\n",
+ "from semantica.seed import SeedDataManager\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "documents = []\n",
+ "\n",
+ "# Option 1: Ingest from Alpha Vantage API (real data source)\n",
+ "# Note: Requires API key - using example structure\n",
+ "alpha_vantage_api = \"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=AAPL&apikey=demo\"\n",
+ "\n",
+ "try:\n",
+ " web_ingestor = WebIngestor()\n",
+ " api_documents = web_ingestor.ingest(alpha_vantage_api, method=\"url\")\n",
+ " print(f\"Ingested {len(api_documents)} documents from Alpha Vantage API\")\n",
+ " documents.extend(api_documents)\n",
+ "except Exception as e:\n",
+ " print(f\"API ingestion failed: {e}\")\n",
+ "\n",
+ "# Option 2: Ingest from MCP server (simulated)\n",
+ "# In production: mcp_ingestor = MCPIngestor()\n",
+ "# mcp_ingestor.connect(\"financial_server\", url=\"http://localhost:8000/mcp\")\n",
+ "# resources = mcp_ingestor.list_available_resources(\"financial_server\")\n",
+ "# mcp_data = mcp_ingestor.ingest_resources(\"financial_server\", resource_uris=[\"resource://market_data\"])\n",
+ "\n",
+ "# Load seed data for market foundation\n",
+ "seed_manager = SeedDataManager()\n",
+ "# Seed with foundation market data\n",
+ "seed_data = [\n",
+ " {\"type\": \"Market\", \"text\": \"NASDAQ\", \"description\": \"Stock exchange\"},\n",
+ " {\"type\": \"Market\", \"text\": \"NYSE\", \"description\": \"Stock exchange\"}\n",
+ "]\n",
+ "seed_manager.load_seed_data(seed_data)\n",
+ "print(f\"Loaded {len(seed_data)} seed data items\")\n",
+ "\n",
+ "# Fallback: Sample market data\n",
+ "if not documents:\n",
+ " market_data = \"\"\"\n",
+ " AAPL stock price: $150.25, market cap: $2.4T, volume: 50M shares\n",
+ " MSFT stock price: $380.50, market cap: $2.8T, volume: 30M shares\n",
+ " GOOGL stock price: $140.75, market cap: $1.8T, volume: 25M shares\n",
+ " \"\"\"\n",
+ " with open(\"data/market_data.txt\", \"w\") as f:\n",
+ " f.write(market_data)\n",
+ " documents = FileIngestor().ingest(\"data/market_data.txt\")\n",
+ " print(f\"Ingested {len(documents)} documents from sample data\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 2: Text Normalization\n",
+ "\n",
+ "Normalize financial data (prices, metrics, company names).\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "\n",
+ "# Normalize financial data\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " normalize_numbers=True, # Normalize financial numbers\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Build financial knowledge graph\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=normalized_documents,\n",
+ " custom_entity_types=[\"Company\", \"Stock\", \"Price\", \"Metric\", \"Market\"],\n",
+ " graph=True\n",
+ ")\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "print(f\"Built financial KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(\"Focus: MCP integration, real-time ingestion, multi-source financial KG\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"financial_data_kg.html\")\n",
+ "\n",
+ "print(\"Financial data integration (MCP) complete\")\n",
+ "print(\"\\n=== Pipeline Summary ===\")\n",
+ "print(f\"✓ Ingested {len(documents)} documents from Alpha Vantage API and MCP\")\n",
+ "print(f\"✓ Loaded {len(seed_data)} seed data items\")\n",
+ "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
+ "print(f\"✓ Built financial KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"✓ Emphasizes: MCP integration, real-time ingestion, API-based KG construction, seed data\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/finance/02_Fraud_Detection.ipynb b/cookbook/use_cases/finance/02_Fraud_Detection.ipynb
new file mode 100644
index 00000000..1249b2a9
--- /dev/null
+++ b/cookbook/use_cases/finance/02_Fraud_Detection.ipynb
@@ -0,0 +1,281 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/02_Fraud_Detection.ipynb)\n",
+ "\n",
+ "# Fraud Detection - Temporal KGs & Pattern Detection\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **fraud detection** using Semantica with focus on **temporal knowledge graphs**, **anomaly detection**, and **pattern recognition**. The pipeline analyzes transaction streams using temporal knowledge graphs to detect fraud patterns and anomalies in real-time.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Temporal Knowledge Graphs**: Builds temporal KGs to track transaction patterns over time\n",
+ "- **Anomaly Detection**: Uses graph-based pattern recognition to identify fraud\n",
+ "- **Real-Time Alerts**: Generates automated alerts for detected fraud patterns\n",
+ "- **Pattern Recognition**: Identifies suspicious transaction patterns\n",
+ "- **Stream Processing**: Demonstrates real-time transaction stream processing\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: Transaction Stream Ingestion\n",
+ "3. **Phase 2**: Transaction Entity Extraction\n",
+ "4. **Phase 3**: Temporal Knowledge Graph Construction\n",
+ "5. **Phase 4**: Pattern Detection\n",
+ "6. **Phase 5**: Anomaly Detection\n",
+ "7. **Phase 6**: Real-Time Alerting\n",
+ "8. **Phase 7**: Visualization & Export\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.reasoning import GraphReasoner\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Fraud_Detection\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\", \"temporal\": True}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "print(\"Configured for fraud detection with temporal KGs focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (Transaction Stream)\n",
+ "\n",
+ "Ingest transaction data from simulated stream using StreamIngestor.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import StreamIngestor, FileIngestor\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "# Option 1: Ingest from transaction stream (simulated Kafka)\n",
+ "# In production: stream_ingestor = StreamIngestor()\n",
+ "# stream_documents = stream_ingestor.ingest(\"kafka://localhost:9092/transactions\", method=\"kafka\")\n",
+ "\n",
+ "# Fallback: Sample transaction stream data\n",
+ "tx_data = \"\"\"\n",
+ "2024-01-01 10:00:00 - Transaction $1000 from Account A123 to Account B456\n",
+ "2024-01-01 10:01:00 - Transaction $5000 from Account A123 to Account C789\n",
+ "2024-01-01 10:02:00 - Transaction $10000 from Account A123 to Account D012 (unusual pattern)\n",
+ "2024-01-01 10:03:00 - Multiple rapid transactions from Account A123 (suspicious)\n",
+ "2024-01-01 10:04:00 - Transaction $2000 from Account B456 to Account E789\n",
+ "2024-01-01 10:05:00 - Large transaction $50000 from Account A123 to Account F012 (fraud alert)\n",
+ "\"\"\"\n",
+ "\n",
+ "with open(\"data/transactions.txt\", \"w\") as f:\n",
+ " f.write(tx_data)\n",
+ "\n",
+ "documents = FileIngestor().ingest(\"data/transactions.txt\")\n",
+ "print(f\"Ingested {len(documents)} documents from transaction stream\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 2: Text Normalization & Conflict Detection\n",
+ "\n",
+ "Normalize transaction data and detect conflicts from multiple sources.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.conflicts import ConflictDetector\n",
+ "\n",
+ "# Normalize transaction data\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " normalize_numbers=True, # Normalize transaction amounts\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Build temporal knowledge graph\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=normalized_documents,\n",
+ " custom_entity_types=[\"Transaction\", \"Account\", \"Device\", \"Pattern\", \"Anomaly\"],\n",
+ " graph=True,\n",
+ " temporal=True\n",
+ ")\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "entities = result[\"entities\"]\n",
+ "\n",
+ "# Detect conflicts in transaction data (e.g., conflicting account information)\n",
+ "detector = ConflictDetector()\n",
+ "conflicts = detector.detect_conflicts(entities, kg.get(\"relationships\", []))\n",
+ "\n",
+ "print(f\"Built temporal transaction KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"Detected {len(conflicts)} conflicts in transaction data\")\n",
+ "if conflicts:\n",
+ " resolved = detector.resolve_conflicts(conflicts, strategy=\"highest_confidence\")\n",
+ " print(f\"Resolved {len(resolved)} conflicts\")\n",
+ "print(\"Focus: Temporal KGs, anomaly detection, pattern recognition, real-time alerts\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 3-4: Temporal Pattern Detection\n",
+ "\n",
+ "Use TemporalPatternDetector for fraud pattern detection.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import TemporalGraphQuery, TemporalPatternDetector\n",
+ "\n",
+ "# Initialize temporal pattern detector\n",
+ "temporal_query = TemporalGraphQuery(enable_temporal_reasoning=True, temporal_granularity=\"minute\")\n",
+ "pattern_detector = TemporalPatternDetector()\n",
+ "\n",
+ "# Detect temporal fraud patterns\n",
+ "fraud_patterns = pattern_detector.detect_patterns(kg, pattern_type=\"fraud\")\n",
+ "temporal_patterns = temporal_query.detect_temporal_patterns(kg, pattern_type=\"sequence\")\n",
+ "\n",
+ "print(f\"Detected {len(fraud_patterns)} fraud patterns\")\n",
+ "print(f\"Detected {len(temporal_patterns)} temporal patterns\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Detect fraud patterns using reasoning\n",
+ "reasoner = GraphReasoner(kg)\n",
+ "reasoning_patterns = reasoner.find_patterns(pattern_type=\"fraud\")\n",
+ "\n",
+ "# Identify suspicious accounts\n",
+ "suspicious_accounts = [e for e in kg.get(\"entities\", []) \n",
+ " if e.get(\"type\") == \"Account\" and \n",
+ " any(\"suspicious\" in str(r.get(\"predicate\", \"\")).lower() or\n",
+ " \"fraud\" in str(r.get(\"predicate\", \"\")).lower()\n",
+ " for r in kg.get(\"relationships\", []) \n",
+ " if r.get(\"source\") == e.get(\"id\"))]\n",
+ "\n",
+ "print(f\"Pattern detection: {len(reasoning_patterns)} fraud patterns from reasoning\")\n",
+ "print(f\"Temporal patterns: {len(temporal_patterns)} temporal fraud patterns\")\n",
+ "print(f\"Anomaly detection: {len(suspicious_accounts)} suspicious accounts flagged\")\n",
+ "print(\"This cookbook emphasizes temporal KGs, TemporalPatternDetector, and pattern-based fraud detection\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 7: Visualization & Summary\n",
+ "\n",
+ "Visualize temporal fraud detection knowledge graph.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"fraud_detection_kg.html\", layout=\"temporal\")\n",
+ "\n",
+ "print(\"Fraud detection analysis complete\")\n",
+ "print(\"\\n=== Pipeline Summary ===\")\n",
+ "print(f\"✓ Ingested {len(documents)} documents from transaction stream\")\n",
+ "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
+ "print(f\"✓ Detected and resolved {len(conflicts)} conflicts\")\n",
+ "print(f\"✓ Built temporal KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"✓ Detected {len(reasoning_patterns)} fraud patterns and {len(suspicious_accounts)} suspicious accounts\")\n",
+ "print(f\"✓ Emphasizes: Temporal KGs, TemporalPatternDetector, anomaly detection, pattern recognition, real-time alerts\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb b/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb
new file mode 100644
index 00000000..068076c3
--- /dev/null
+++ b/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb
@@ -0,0 +1,255 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb)\n",
+ "\n",
+ "# Clinical Reports Processing - EHR Integration & Triplet Stores\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **clinical reports processing** using Semantica with focus on **EHR integration**, **triplet stores**, and **patient knowledge graphs**. The pipeline processes EHR systems and HL7/FHIR APIs to build patient knowledge graphs and store them in triplet stores.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **EHR Integration**: Processes EHR systems and HL7/FHIR APIs\n",
+ "- **Triplet Store Storage**: Stores patient data in RDF triplet stores\n",
+ "- **Patient Knowledge Graphs**: Builds comprehensive patient KGs\n",
+ "- **Medical Entity Extraction**: Extracts medical entities from clinical reports\n",
+ "- **Structured Data Storage**: Emphasizes storage and structured data management\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: EHR/HL7/FHIR Data Ingestion\n",
+ "3. **Phase 2**: Clinical Report Parsing\n",
+ "4. **Phase 3**: Medical Entity Extraction\n",
+ "5. **Phase 4**: Patient Knowledge Graph Construction\n",
+ "6. **Phase 5**: Triplet Store Population\n",
+ "7. **Phase 6**: Visualization & Export\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq rdflib\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.triplet_store import TripletStore\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Clinical_Reports_Processing\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\"}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "triplet_store = TripletStore(backend=\"jena\") # or \"blazegraph\"\n",
+ "print(\"Configured for clinical reports processing with triplet store focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (FDA RSS Feed & HL7/FHIR Structure)\n",
+ "\n",
+ "Ingest clinical data from FDA RSS feeds and simulated HL7/FHIR databases.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, DBIngestor, FileIngestor\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "documents = []\n",
+ "\n",
+ "# Option 1: Ingest from FDA RSS feed (real data source)\n",
+ "fda_rss_url = \"https://www.fda.gov/about-fda/contact-fda/stay-informed/rss-feeds/fda-press-releases\"\n",
+ "\n",
+ "try:\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " feed_documents = feed_ingestor.ingest(fda_rss_url, method=\"rss\")\n",
+ " print(f\"Ingested {len(feed_documents)} documents from FDA RSS feed\")\n",
+ " documents.extend(feed_documents)\n",
+ "except Exception as e:\n",
+ " print(f\"FDA RSS feed ingestion failed: {e}\")\n",
+ "\n",
+ "# Option 2: Simulate HL7/FHIR database ingestion\n",
+ "# In production: db_ingestor = DBIngestor()\n",
+ "# db_ingestor.connect(\"postgresql://user:pass@localhost/emr_db\")\n",
+ "# fhir_documents = db_ingestor.ingest(\"SELECT * FROM patient_records\", method=\"postgresql\")\n",
+ "\n",
+ "# Fallback: Sample clinical report data\n",
+ "if not documents:\n",
+ " clinical_data = \"\"\"\n",
+ " Patient ID: P001, Name: John Doe, DOB: 1980-01-15\n",
+ " Diagnosis: Type 2 Diabetes, Date: 2024-01-10\n",
+ " Treatment: Metformin 500mg twice daily, Started: 2024-01-10\n",
+ " Procedure: Blood glucose test, Date: 2024-01-15, Result: 180 mg/dL\n",
+ " Patient ID: P002, Name: Jane Smith, DOB: 1975-05-20\n",
+ " Diagnosis: Hypertension, Date: 2024-01-12\n",
+ " \"\"\"\n",
+ " with open(\"data/clinical_report.txt\", \"w\") as f:\n",
+ " f.write(clinical_data)\n",
+ " documents = FileIngestor().ingest(\"data/clinical_report.txt\")\n",
+ " print(f\"Ingested {len(documents)} documents from sample data\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 2: Text Normalization & Deduplication\n",
+ "\n",
+ "Normalize medical terms and deduplicate patient records.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.deduplication import DuplicateDetector\n",
+ "\n",
+ "# Normalize medical terms\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Build patient knowledge graph\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=normalized_documents,\n",
+ " custom_entity_types=[\"Patient\", \"Diagnosis\", \"Treatment\", \"Procedure\", \"EHR\"],\n",
+ " graph=True\n",
+ ")\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "entities = result[\"entities\"]\n",
+ "\n",
+ "# Deduplicate patient records\n",
+ "patients = [e for e in entities if e.get(\"type\") == \"Patient\" or \"patient\" in e.get(\"type\", \"\").lower()]\n",
+ "\n",
+ "detector = DuplicateDetector()\n",
+ "duplicates = detector.detect_duplicates(patients, threshold=0.9)\n",
+ "deduplicated_patients = detector.resolve_duplicates(patients, duplicates)\n",
+ "\n",
+ "print(f\"Built patient KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"Deduplicated: {len(patients)} -> {len(deduplicated_patients)} unique patients\")\n",
+ "print(\"Focus: EHR integration, triplet stores, patient KGs, structured data storage\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Store patient data in triplet store\n",
+ "triplets = []\n",
+ "for rel in kg.get(\"relationships\", []):\n",
+ " triplets.append({\n",
+ " \"subject\": rel.get(\"source\"),\n",
+ " \"predicate\": rel.get(\"predicate\"),\n",
+ " \"object\": rel.get(\"target\")\n",
+ " })\n",
+ "\n",
+ "triplet_store.store_triplets(triplets)\n",
+ "print(f\"Stored {len(triplets)} triplets in triplet store\")\n",
+ "print(\"\\n=== Pipeline Summary ===\")\n",
+ "print(f\"✓ Ingested {len(documents)} documents from FDA RSS feed and HL7/FHIR\")\n",
+ "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
+ "print(f\"✓ Deduplicated {len(patients)} patients to {len(deduplicated_patients)} unique\")\n",
+ "print(f\"✓ Built patient KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"✓ Stored {len(triplets)} triplets in triplet store\")\n",
+ "print(f\"✓ This cookbook emphasizes triplet store storage and structured data management\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 6: Visualization\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"patient_kg.html\")\n",
+ "\n",
+ "print(\"Clinical reports processing complete\")\n",
+ "print(\"Emphasizes: EHR integration, triplet stores, patient KGs, structured data\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynb b/cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynb
new file mode 100644
index 00000000..ef2a4d10
--- /dev/null
+++ b/cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynb
@@ -0,0 +1,314 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynb)\n",
+ "\n",
+ "# Drug Interactions Analysis - Ontology & Reasoning\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **drug interactions analysis** using Semantica with focus on **multi-source correlation**, **safety ontology**, and **interaction detection**. The pipeline analyzes FDA databases and medical literature to detect drug-drug and drug-condition interactions using ontology-based reasoning.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Ontology Generation**: Creates safety ontologies for drug interactions\n",
+ "- **Multi-Source Correlation**: Correlates data from FDA databases and medical literature\n",
+ "- **Interaction Detection**: Detects drug-drug and drug-condition interactions\n",
+ "- **Safety Ontology**: Uses domain ontologies for safety analysis\n",
+ "- **Reasoning**: Emphasizes ontology and reasoning for interaction prediction\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: FDA Database & Medical Literature Ingestion\n",
+ "3. **Phase 2**: Drug Entity Extraction\n",
+ "4. **Phase 3**: Safety Ontology Generation\n",
+ "5. **Phase 4**: Multi-Source Correlation\n",
+ "6. **Phase 5**: Interaction Detection & Reasoning\n",
+ "7. **Phase 6**: Visualization & Export\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.ontology import OntologyGenerator\n",
+ "from semantica.reasoning import GraphReasoner\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Drug_Interactions_Analysis\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\"},\n",
+ " \"ontology\": {\"base_uri\": \"https://drug-safety.example.org/ontology/\"}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "print(\"Configured for drug interactions analysis with ontology reasoning focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (Medical RSS Feeds)\n",
+ "\n",
+ "Ingest drug interaction data from medical literature RSS feeds.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, FileIngestor\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "# Ingest from medical literature RSS feeds (real data sources)\n",
+ "medical_feeds = [\n",
+ " \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+interaction&limit=10\",\n",
+ " # Add more medical feeds as needed\n",
+ "]\n",
+ "\n",
+ "documents = []\n",
+ "for feed_url in medical_feeds:\n",
+ " try:\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " feed_documents = feed_ingestor.ingest(feed_url, method=\"rss\")\n",
+ " print(f\"Ingested {len(feed_documents)} documents from {feed_url}\")\n",
+ " documents.extend(feed_documents)\n",
+ " except Exception as e:\n",
+ " print(f\"Feed ingestion failed for {feed_url}: {e}\")\n",
+ "\n",
+ "# Fallback: Sample drug interaction data\n",
+ "if not documents:\n",
+ " drug_data = \"\"\"\n",
+ " Warfarin interacts with Aspirin, increasing bleeding risk.\n",
+ " Metformin should not be used with patients having kidney disease.\n",
+ " Ibuprofen can interact with ACE inhibitors, reducing effectiveness.\n",
+ " Statins may interact with grapefruit juice, increasing side effects.\n",
+ " Digoxin interacts with Amiodarone, increasing toxicity risk.\n",
+ " \"\"\"\n",
+ " with open(\"data/drug_interactions.txt\", \"w\") as f:\n",
+ " f.write(drug_data)\n",
+ " documents = FileIngestor().ingest(\"data/drug_interactions.txt\")\n",
+ " print(f\"Ingested {len(documents)} documents from sample data\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 2: Text Normalization & Advanced Chunking\n",
+ "\n",
+ "Normalize drug names and use relation-aware chunking to preserve interaction triplets.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.split import TextSplitter\n",
+ "\n",
+ "# Normalize drug names\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Use relation-aware chunking to preserve drug interaction triplets\n",
+ "relation_splitter = TextSplitter(\n",
+ " method=\"relation_aware\",\n",
+ " chunk_size=1000,\n",
+ " chunk_overlap=200\n",
+ ")\n",
+ "\n",
+ "chunked_docs = []\n",
+ "for doc_text in normalized_documents:\n",
+ " chunks = relation_splitter.split(doc_text)\n",
+ " chunked_docs.extend([chunk.content if hasattr(chunk, 'content') else str(chunk) for chunk in chunks])\n",
+ "\n",
+ "print(f\"Created {len(chunked_docs)} relation-aware chunks (preserves interaction triplets)\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 3: Knowledge Graph Construction & Conflict Detection\n",
+ "\n",
+ "Build drug knowledge graph and detect conflicts from multiple sources.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.conflicts import ConflictDetector\n",
+ "\n",
+ "# Build drug knowledge graph\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=chunked_docs,\n",
+ " custom_entity_types=[\"Drug\", \"Interaction\", \"Condition\", \"SideEffect\", \"Safety\"],\n",
+ " graph=True\n",
+ ")\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "entities = result[\"entities\"]\n",
+ "\n",
+ "# Detect conflicts in drug interaction data (e.g., conflicting interaction reports)\n",
+ "detector = ConflictDetector()\n",
+ "conflicts = detector.detect_conflicts(entities, kg.get(\"relationships\", []))\n",
+ "\n",
+ "print(f\"Built drug KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"Detected {len(conflicts)} conflicts in drug interaction data\")\n",
+ "if conflicts:\n",
+ " resolved = detector.resolve_conflicts(conflicts, strategy=\"highest_confidence\")\n",
+ " print(f\"Resolved {len(resolved)} conflicts\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 4: Safety Ontology Generation\n",
+ "\n",
+ "Generate enhanced safety ontology from knowledge graph.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Generate safety ontology\n",
+ "ontology_gen = OntologyGenerator(base_uri=\"https://drug-safety.example.org/ontology/\")\n",
+ "ontology = ontology_gen.generate_from_graph(kg)\n",
+ "\n",
+ "print(f\"Generated safety ontology with {len(ontology.get('classes', []))} classes\")\n",
+ "print(\"Focus: Multi-source correlation, safety ontology, interaction detection, reasoning\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Use reasoning to detect interactions\n",
+ "reasoner = GraphReasoner(kg)\n",
+ "interactions = reasoner.find_patterns(pattern_type=\"interaction\")\n",
+ "\n",
+ "# Identify drug-drug interactions\n",
+ "drug_interactions = [r for r in kg.get(\"relationships\", []) \n",
+ " if \"interact\" in str(r.get(\"predicate\", \"\")).lower()]\n",
+ "\n",
+ "print(f\"Interaction detection: {len(interactions)} interaction patterns found\")\n",
+ "print(f\"Drug interactions: {len(drug_interactions)} drug-drug interactions identified\")\n",
+ "print(\"\\n=== Pipeline Summary ===\")\n",
+ "print(f\"✓ Ingested {len(documents)} documents from medical RSS feeds\")\n",
+ "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
+ "print(f\"✓ Created {len(chunked_docs)} relation-aware chunks\")\n",
+ "print(f\"✓ Detected and resolved {len(conflicts)} conflicts\")\n",
+ "print(f\"✓ Generated ontology with {len(ontology.get('classes', []))} classes\")\n",
+ "print(f\"✓ This cookbook emphasizes ontology reasoning, relation-aware chunking, and multi-source correlation\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 6: Visualization\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "from semantica.export import GraphExporter\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"drug_interactions_kg.html\")\n",
+ "\n",
+ "exporter = GraphExporter()\n",
+ "exporter.export(kg, format=\"rdf\", output_path=\"drug_safety_ontology.ttl\")\n",
+ "\n",
+ "print(\"Drug interactions analysis complete\")\n",
+ "print(\"Emphasizes: Multi-source correlation, safety ontology, interaction detection, reasoning\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb b/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb
new file mode 100644
index 00000000..3f233a5f
--- /dev/null
+++ b/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb
@@ -0,0 +1,250 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb)\n",
+ "\n",
+ "# Criminal Network Analysis - Graph Analytics & Centrality\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **criminal network analysis** using Semantica with focus on **network centrality**, **community detection**, and **relationship mapping**. The pipeline processes police reports and court records to build knowledge graphs for analyzing criminal networks and relationships.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Network Centrality**: Uses centrality measures to identify key players\n",
+ "- **Community Detection**: Detects criminal communities and groups\n",
+ "- **Relationship Mapping**: Maps relationships between persons, organizations, and events\n",
+ "- **Graph Analytics**: Emphasizes graph analytics for network analysis\n",
+ "- **Intelligence Reporting**: Generates intelligence reports from network analysis\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: Police Reports & Court Records Ingestion\n",
+ "3. **Phase 2**: Entity Extraction (Person, Organization, Event, Location)\n",
+ "4. **Phase 3**: Criminal Network Graph Construction\n",
+ "5. **Phase 4**: Network Centrality Analysis\n",
+ "6. **Phase 5**: Community Detection\n",
+ "7. **Phase 6**: Relationship Analysis\n",
+ "8. **Phase 7**: Visualization & Intelligence Reporting\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.kg import GraphAnalytics\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Criminal_Network_Analysis\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\"}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "print(\"Configured for criminal network analysis with graph analytics focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (OSINT RSS Feeds)\n",
+ "\n",
+ "Ingest intelligence data from OSINT RSS feeds.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, FileIngestor\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "# Ingest from OSINT RSS feeds (real data sources)\n",
+ "osint_feeds = [\n",
+ " # Add OSINT feed URLs here\n",
+ " # Example: \"https://example.com/osint-feed.xml\"\n",
+ "]\n",
+ "\n",
+ "documents = []\n",
+ "for feed_url in osint_feeds:\n",
+ " try:\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " feed_documents = feed_ingestor.ingest(feed_url, method=\"rss\")\n",
+ " print(f\"Ingested {len(feed_documents)} documents from {feed_url}\")\n",
+ " documents.extend(feed_documents)\n",
+ " except Exception as e:\n",
+ " print(f\"Feed ingestion failed for {feed_url}: {e}\")\n",
+ "\n",
+ "# Fallback: Sample criminal network data\n",
+ "if not documents:\n",
+ " network_data = \"\"\"\n",
+ " John Smith is associated with criminal organization XYZ.\n",
+ " Jane Doe has connections to John Smith and organization XYZ.\n",
+ " Event: Meeting on 2024-01-15 between John Smith and Jane Doe at Location A.\n",
+ " Organization XYZ is linked to multiple criminal activities.\n",
+ " Person: Mike Johnson connected to organization XYZ.\n",
+ " \"\"\"\n",
+ " with open(\"data/criminal_network.txt\", \"w\") as f:\n",
+ " f.write(network_data)\n",
+ " documents = FileIngestor().ingest(\"data/criminal_network.txt\")\n",
+ " print(f\"Ingested {len(documents)} documents from sample data\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 2: Text Normalization & Deduplication\n",
+ "\n",
+ "Normalize entity names and deduplicate person records.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.deduplication import DuplicateDetector\n",
+ "\n",
+ "# Normalize entity names\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Build criminal network graph\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=normalized_documents,\n",
+ " custom_entity_types=[\"Person\", \"Organization\", \"Event\", \"Location\", \"Relationship\"],\n",
+ " graph=True\n",
+ ")\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "entities = result[\"entities\"]\n",
+ "\n",
+ "# Deduplicate person records\n",
+ "persons = [e for e in entities if e.get(\"type\") == \"Person\" or \"person\" in e.get(\"type\", \"\").lower()]\n",
+ "\n",
+ "detector = DuplicateDetector()\n",
+ "duplicates = detector.detect_duplicates(persons, threshold=0.9)\n",
+ "deduplicated_persons = detector.resolve_duplicates(persons, duplicates)\n",
+ "\n",
+ "print(f\"Built criminal network with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"Deduplicated: {len(persons)} -> {len(deduplicated_persons)} unique persons\")\n",
+ "print(\"Focus: Network centrality, community detection, relationship mapping, graph analytics\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Perform network analytics\n",
+ "analytics = GraphAnalytics(kg)\n",
+ "centrality = analytics.calculate_centrality(method=\"betweenness\")\n",
+ "communities = analytics.detect_communities()\n",
+ "\n",
+ "# Identify key players (high centrality)\n",
+ "key_players = sorted(centrality.items(), key=lambda x: x[1], reverse=True)[:5]\n",
+ "\n",
+ "print(f\"Network centrality: {len(centrality)} nodes analyzed\")\n",
+ "print(f\"Community detection: {len(communities)} communities identified\")\n",
+ "print(f\"Key players: {[node for node, _ in key_players]}\")\n",
+ "print(\"\\n=== Pipeline Summary ===\")\n",
+ "print(f\"✓ Ingested {len(documents)} documents from OSINT RSS feeds\")\n",
+ "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
+ "print(f\"✓ Deduplicated {len(persons)} persons to {len(deduplicated_persons)} unique\")\n",
+ "print(f\"✓ This cookbook emphasizes graph analytics, centrality, and community detection\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 6-7: Visualization & Intelligence Reporting\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"criminal_network.html\", layout=\"force-directed\")\n",
+ "\n",
+ "print(\"Criminal network analysis complete\")\n",
+ "print(\"Emphasizes: Network centrality, community detection, relationship mapping, graph analytics\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb b/cookbook/use_cases/intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb
new file mode 100644
index 00000000..21065794
--- /dev/null
+++ b/cookbook/use_cases/intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb
@@ -0,0 +1,265 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb)\n",
+ "\n",
+ "# Intelligence Analysis Orchestrator-Worker - Parallel Processing\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **intelligence analysis using orchestrator-worker pattern** with focus on **parallel processing**, **pipeline orchestration**, and **multi-source integration**. The pipeline uses the Orchestrator-Worker pattern to coordinate parallel processing of OSINT feeds, threat intelligence, and geospatial data.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Parallel Processing**: Coordinates parallel processing of multiple intelligence sources\n",
+ "- **Pipeline Orchestration**: Uses pipeline module for workflow management\n",
+ "- **Multi-Source Integration**: Integrates OSINT feeds, threat intelligence, and geospatial data\n",
+ "- **Orchestrator-Worker Pattern**: Demonstrates distributed processing architecture\n",
+ "- **Hybrid RAG**: Combines multiple intelligence sources for comprehensive analysis\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: Multi-Source Intelligence Ingestion (OSINT, Threat Intel, Geospatial)\n",
+ "3. **Phase 2**: Parallel Processing Setup (Orchestrator-Worker)\n",
+ "4. **Phase 3**: Entity Extraction (Source, Entity, Event, Location, Timeframe)\n",
+ "5. **Phase 4**: Pipeline Orchestration\n",
+ "6. **Phase 5**: Multi-Source Correlation\n",
+ "7. **Phase 6**: Hybrid RAG Query System\n",
+ "8. **Phase 7**: Visualization & Export\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.pipeline import PipelineOrchestrator\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Intelligence_Analysis_Orchestrator_Worker\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\"}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "orchestrator = PipelineOrchestrator()\n",
+ "print(\"Configured for intelligence analysis with orchestrator-worker pattern focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (Multiple RSS Feeds with Pipeline Orchestrator)\n",
+ "\n",
+ "Ingest intelligence data from multiple RSS feeds using PipelineOrchestrator.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, FileIngestor\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "# Define multiple RSS feeds for parallel ingestion\n",
+ "intelligence_feeds = {\n",
+ " \"osint\": \"https://www.us-cert.gov/ncas/alerts.xml\", # OSINT feed\n",
+ " \"threat\": \"https://www.us-cert.gov/ncas/alerts.xml\", # Threat intel feed (example)\n",
+ " # Add more feeds as needed\n",
+ "}\n",
+ "\n",
+ "# Use PipelineOrchestrator for parallel ingestion\n",
+ "documents = []\n",
+ "for feed_name, feed_url in intelligence_feeds.items():\n",
+ " try:\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " # Add worker to orchestrator\n",
+ " orchestrator.add_worker(f\"{feed_name}_worker\", feed_ingestor, source=feed_url)\n",
+ " except Exception as e:\n",
+ " print(f\"Failed to add worker for {feed_name}: {e}\")\n",
+ "\n",
+ "# Execute parallel ingestion\n",
+ "try:\n",
+ " results = orchestrator.execute_parallel()\n",
+ " for result in results:\n",
+ " documents.extend(result.get(\"documents\", []))\n",
+ " print(f\"Ingested {len(documents)} documents from parallel feeds\")\n",
+ "except Exception as e:\n",
+ " print(f\"Parallel ingestion failed: {e}\")\n",
+ " # Fallback: Sequential ingestion\n",
+ " for feed_name, feed_url in intelligence_feeds.items():\n",
+ " try:\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " feed_documents = feed_ingestor.ingest(feed_url, method=\"rss\")\n",
+ " documents.extend(feed_documents)\n",
+ " print(f\"Ingested {len(feed_documents)} documents from {feed_name}\")\n",
+ " except Exception as e2:\n",
+ " print(f\"Feed ingestion failed for {feed_name}: {e2}\")\n",
+ "\n",
+ "# Fallback: Sample data\n",
+ "if not documents:\n",
+ " osint_data = \"OSINT: Public records show connection between Entity A and Location X.\"\n",
+ " threat_data = \"Threat Intel: Threat actor group Y operates in Region Z.\"\n",
+ " geo_data = \"Geospatial: Activity detected at coordinates 40.7128, -74.0060.\"\n",
+ " with open(\"data/intelligence.txt\", \"w\") as f:\n",
+ " f.write(f\"{osint_data}\\n{threat_data}\\n{geo_data}\")\n",
+ " documents = FileIngestor().ingest(\"data/intelligence.txt\")\n",
+ " print(f\"Ingested {len(documents)} documents from sample data\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 2: Text Normalization & Conflict Detection\n",
+ "\n",
+ "Normalize multi-source intelligence data and detect conflicts.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.conflicts import ConflictDetector\n",
+ "\n",
+ "# Normalize multi-source intelligence data\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Build intelligence knowledge graph\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=normalized_documents,\n",
+ " custom_entity_types=[\"Source\", \"Entity\", \"Event\", \"Location\", \"Timeframe\"],\n",
+ " graph=True\n",
+ ")\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "entities = result[\"entities\"]\n",
+ "\n",
+ "# Detect conflicts from multiple intelligence sources\n",
+ "detector = ConflictDetector()\n",
+ "conflicts = detector.detect_conflicts(entities, kg.get(\"relationships\", []))\n",
+ "\n",
+ "print(f\"Built intelligence KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"Detected {len(conflicts)} conflicts from multiple sources\")\n",
+ "if conflicts:\n",
+ " resolved = detector.resolve_conflicts(conflicts, strategy=\"highest_confidence\")\n",
+ " print(f\"Resolved {len(resolved)} conflicts\")\n",
+ "print(\"Focus: Parallel processing, pipeline orchestration, multi-source integration\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Correlate multi-source intelligence\n",
+ "from semantica.reasoning import GraphReasoner\n",
+ "\n",
+ "reasoner = GraphReasoner(kg)\n",
+ "correlations = reasoner.find_correlations(\n",
+ " source_types=[\"Source\"],\n",
+ " target_types=[\"Entity\", \"Location\"]\n",
+ ")\n",
+ "\n",
+ "print(f\"Multi-source correlation: {len(correlations)} correlations found\")\n",
+ "print(\"\\n=== Pipeline Summary ===\")\n",
+ "print(f\"✓ Ingested {len(documents)} documents from multiple RSS feeds using PipelineOrchestrator\")\n",
+ "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
+ "print(f\"✓ Detected and resolved {len(conflicts)} conflicts\")\n",
+ "print(f\"✓ This cookbook emphasizes parallel processing, PipelineOrchestrator, and multi-source integration\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 7: Visualization\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"intelligence_analysis.html\")\n",
+ "\n",
+ "print(\"Intelligence analysis (orchestrator-worker) complete\")\n",
+ "print(\"Emphasizes: Parallel processing, pipeline orchestration, multi-source integration\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb b/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb
new file mode 100644
index 00000000..ef47abe9
--- /dev/null
+++ b/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb
@@ -0,0 +1,285 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb)\n",
+ "\n",
+ "# Energy Market Analysis - Temporal KGs & Trend Prediction\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **energy market analysis** using Semantica with focus on **temporal knowledge graphs**, **trend prediction**, and **market entity extraction**. The pipeline analyzes pricing trends and market movements using temporal market knowledge graphs.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Temporal Knowledge Graphs**: Builds temporal KGs to track energy market trends over time\n",
+ "- **Trend Prediction**: Uses temporal analysis to predict market movements\n",
+ "- **Market Entity Extraction**: Extracts energy market entities (Market, Price, Region, Trend, Forecast)\n",
+ "- **Temporal Analysis**: Emphasizes temporal analysis for market trend prediction\n",
+ "- **Energy Entity Extraction**: Extracts domain-specific energy entities\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: Energy Market Data Ingestion\n",
+ "3. **Phase 2**: Market Entity Extraction\n",
+ "4. **Phase 3**: Temporal Knowledge Graph Construction\n",
+ "5. **Phase 4**: Trend Analysis\n",
+ "6. **Phase 5**: Market Trend Prediction\n",
+ "7. **Phase 6**: Visualization & Export\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Energy_Market_Analysis\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\", \"temporal\": True}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "print(\"Configured for energy market analysis with temporal KGs focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (Energy RSS Feeds & EIA API)\n",
+ "\n",
+ "Ingest energy market data from RSS feeds and EIA API.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, WebIngestor, FileIngestor\n",
+ "from semantica.seed import SeedDataManager\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "documents = []\n",
+ "\n",
+ "# Option 1: Ingest from energy RSS feeds\n",
+ "energy_feeds = [\n",
+ " # Add energy news RSS feeds here\n",
+ "]\n",
+ "\n",
+ "for feed_url in energy_feeds:\n",
+ " try:\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " feed_documents = feed_ingestor.ingest(feed_url, method=\"rss\")\n",
+ " documents.extend(feed_documents)\n",
+ " except Exception as e:\n",
+ " print(f\"Feed ingestion failed: {e}\")\n",
+ "\n",
+ "# Option 2: Ingest from EIA API (simulated structure)\n",
+ "# eia_api = \"https://api.eia.gov/v2/electricity/rto/region-data/data/\"\n",
+ "# web_ingestor = WebIngestor()\n",
+ "# api_documents = web_ingestor.ingest(eia_api, method=\"url\")\n",
+ "\n",
+ "# Load seed data for market foundation\n",
+ "seed_manager = SeedDataManager()\n",
+ "seed_data = [\n",
+ " {\"type\": \"Market\", \"text\": \"Energy Market\", \"description\": \"Primary energy market\"},\n",
+ " {\"type\": \"Region\", \"text\": \"North America\", \"description\": \"Market region\"}\n",
+ "]\n",
+ "seed_manager.load_seed_data(seed_data)\n",
+ "print(f\"Loaded {len(seed_data)} seed data items\")\n",
+ "\n",
+ "# Fallback: Sample data\n",
+ "if not documents:\n",
+ " market_data = \"\"\"\n",
+ " 2024-01-01: Solar energy price $50/MWh in Region A, trend: increasing\n",
+ " 2024-01-02: Wind energy price $45/MWh in Region B, trend: stable\n",
+ " 2024-01-03: Solar energy price $52/MWh in Region A, trend: increasing\n",
+ " 2024-01-04: Forecast: Solar prices expected to rise to $55/MWh\n",
+ " \"\"\"\n",
+ " with open(\"data/energy_market.txt\", \"w\") as f:\n",
+ " f.write(market_data)\n",
+ " documents = FileIngestor().ingest(\"data/energy_market.txt\")\n",
+ " print(f\"Ingested {len(documents)} documents from sample data\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 2: Text Normalization\n",
+ "\n",
+ "Normalize energy market data.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " normalize_numbers=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Build temporal market knowledge graph\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=normalized_documents,\n",
+ " custom_entity_types=[\"Market\", \"Price\", \"Region\", \"Trend\", \"Forecast\"],\n",
+ " graph=True,\n",
+ " temporal=True\n",
+ ")\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "print(f\"Built temporal market KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(\"Focus: Temporal KGs, trend prediction, market entity extraction\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 3-4: Temporal Pattern Detection & Trend Analysis\n",
+ "\n",
+ "Use TemporalPatternDetector for trend prediction.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import TemporalGraphQuery, TemporalPatternDetector\n",
+ "from semantica.reasoning import GraphReasoner\n",
+ "\n",
+ "# Initialize temporal pattern detector\n",
+ "temporal_query = TemporalGraphQuery(enable_temporal_reasoning=True, temporal_granularity=\"day\")\n",
+ "pattern_detector = TemporalPatternDetector()\n",
+ "\n",
+ "# Detect temporal patterns for trend prediction\n",
+ "trend_patterns = pattern_detector.detect_temporal_patterns(kg, pattern_type=\"trend\", min_frequency=2)\n",
+ "temporal_patterns = temporal_query.detect_temporal_patterns(kg, pattern_type=\"sequence\")\n",
+ "\n",
+ "# Analyze trends using reasoning\n",
+ "reasoner = GraphReasoner(kg)\n",
+ "trends = reasoner.analyze_temporal_patterns(entity_type=\"Price\")\n",
+ "\n",
+ "print(f\"Trend analysis: {len(trends)} price trends identified\")\n",
+ "print(f\"Temporal patterns: {len(trend_patterns)} trend patterns detected\")\n",
+ "print(\"This cookbook emphasizes temporal analysis, TemporalPatternDetector, and trend prediction\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"energy_market_kg.html\", layout=\"temporal\")\n",
+ "\n",
+ "print(\"Energy market analysis complete\")\n",
+ "print(\"\\n=== Pipeline Summary ===\")\n",
+ "print(f\"✓ Ingested {len(documents)} documents from energy RSS feeds and EIA API\")\n",
+ "print(f\"✓ Loaded {len(seed_data)} seed data items\")\n",
+ "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
+ "print(f\"✓ Built temporal KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"✓ Detected {len(trend_patterns)} trend patterns using TemporalPatternDetector\")\n",
+ "print(f\"✓ Emphasizes: Temporal KGs, TemporalPatternDetector, trend prediction, market entity extraction\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 6: Visualization\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"energy_market_kg.html\", layout=\"temporal\")\n",
+ "\n",
+ "print(\"Energy market analysis complete\")\n",
+ "print(\"Emphasizes: Temporal KGs, trend prediction, market entity extraction\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/renewable_energy/02_Smart_Grid_Management.ipynb b/cookbook/use_cases/renewable_energy/02_Smart_Grid_Management.ipynb
new file mode 100644
index 00000000..04f4156a
--- /dev/null
+++ b/cookbook/use_cases/renewable_energy/02_Smart_Grid_Management.ipynb
@@ -0,0 +1,285 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/02_Smart_Grid_Management.ipynb)\n",
+ "\n",
+ "# Smart Grid Management - Stream Processing & Real-Time Monitoring\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **smart grid management** using Semantica with focus on **stream processing**, **real-time monitoring**, and **failure prediction**. The pipeline streams grid sensor data to monitor grid health and predict failures using temporal pattern detection.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Stream Processing**: Emphasizes real-time stream ingestion from grid sensors\n",
+ "- **Real-Time Monitoring**: Monitors grid health in real-time\n",
+ "- **Failure Prediction**: Uses temporal pattern detection to predict grid failures\n",
+ "- **Anomaly Detection**: Detects anomalies in grid sensor data\n",
+ "- **Temporal Pattern Detection**: Identifies patterns in sensor data streams\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: Grid Sensor Stream Ingestion\n",
+ "3. **Phase 2**: Real-Time Data Parsing\n",
+ "4. **Phase 3**: Sensor Entity Extraction\n",
+ "5. **Phase 4**: Temporal Knowledge Graph Construction\n",
+ "6. **Phase 5**: Real-Time Monitoring\n",
+ "7. **Phase 6**: Failure Prediction & Anomaly Detection\n",
+ "8. **Phase 7**: Alert Generation & Visualization\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.ingest import StreamIngestor\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Smart_Grid_Management\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\", \"temporal\": True}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "print(\"Configured for smart grid management with stream processing focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (Sensor Stream)\n",
+ "\n",
+ "Ingest grid sensor data from simulated stream using StreamIngestor.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import StreamIngestor, FileIngestor\n",
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.split import TextSplitter\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "# Option 1: Ingest from sensor stream (simulated Kafka)\n",
+ "# In production: stream_ingestor = StreamIngestor()\n",
+ "# stream_documents = stream_ingestor.ingest(\"kafka://localhost:9092/grid-sensors\", method=\"kafka\")\n",
+ "\n",
+ "# Fallback: Sample sensor stream data\n",
+ "sensor_data = \"\"\"\n",
+ "2024-01-01 10:00:00 - Sensor S001: Voltage 230V, Status: Normal\n",
+ "2024-01-01 10:01:00 - Sensor S002: Voltage 225V, Status: Normal\n",
+ "2024-01-01 10:02:00 - Sensor S001: Voltage 210V, Status: Warning (voltage drop)\n",
+ "2024-01-01 10:03:00 - Sensor S003: Voltage 200V, Status: Alert (potential failure)\n",
+ "2024-01-01 10:04:00 - Sensor S001: Voltage 205V, Status: Warning\n",
+ "\"\"\"\n",
+ "\n",
+ "with open(\"data/grid_sensors.txt\", \"w\") as f:\n",
+ " f.write(sensor_data)\n",
+ "\n",
+ "documents = FileIngestor().ingest(\"data/grid_sensors.txt\")\n",
+ "print(f\"Ingested {len(documents)} documents from sensor stream\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 2: Text Normalization & Advanced Chunking\n",
+ "\n",
+ "Normalize sensor data and use token/sentence chunking for stream data.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Normalize sensor data\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " normalize_numbers=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Use token chunking for fixed-size sensor data chunks\n",
+ "# Alternative: sentence chunking for structured sensor logs\n",
+ "splitter = TextSplitter(method=\"token\", chunk_size=100, chunk_overlap=10)\n",
+ "# splitter = TextSplitter(method=\"sentence\", chunk_size=500, chunk_overlap=50)\n",
+ "\n",
+ "chunked_docs = []\n",
+ "for doc_text in normalized_documents:\n",
+ " chunks = splitter.split(doc_text)\n",
+ " chunked_docs.extend([chunk.content if hasattr(chunk, 'content') else str(chunk) for chunk in chunks])\n",
+ "\n",
+ "print(f\"Created {len(chunked_docs)} chunks using token chunking\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 3-4: Temporal Knowledge Graph Construction\n",
+ "\n",
+ "Build full temporal KG with TemporalGraphQuery capabilities.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import TemporalGraphQuery\n",
+ "\n",
+ "# Build temporal knowledge graph\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=chunked_docs,\n",
+ " custom_entity_types=[\"Sensor\", \"Grid\", \"Failure\", \"Alert\", \"Prediction\"],\n",
+ " graph=True,\n",
+ " temporal=True\n",
+ ")\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "\n",
+ "# Initialize temporal graph query engine\n",
+ "temporal_query = TemporalGraphQuery(\n",
+ " enable_temporal_reasoning=True,\n",
+ " temporal_granularity=\"minute\" # Fine-grained for real-time sensors\n",
+ ")\n",
+ "\n",
+ "# Query graph at specific time point\n",
+ "query_results = temporal_query.query_at_time(\n",
+ " kg,\n",
+ " query={\"type\": \"Alert\"},\n",
+ " at_time=\"2024-01-01 10:03:00\"\n",
+ ")\n",
+ "\n",
+ "# Analyze temporal evolution\n",
+ "evolution = temporal_query.analyze_evolution(kg)\n",
+ "\n",
+ "print(f\"Built temporal grid KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"Temporal queries: {len(query_results)} alerts at query time\")\n",
+ "print(\"Focus: Stream processing, real-time monitoring, failure prediction, anomaly detection\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.reasoning import GraphReasoner\n",
+ "\n",
+ "# Detect failure patterns\n",
+ "reasoner = GraphReasoner(kg)\n",
+ "failure_patterns = reasoner.find_patterns(pattern_type=\"failure\")\n",
+ "\n",
+ "# Temporal pattern detection\n",
+ "temporal_patterns = temporal_query.detect_temporal_patterns(kg, pattern_type=\"sequence\")\n",
+ "\n",
+ "# Identify alerts\n",
+ "alerts = [e for e in kg.get(\"entities\", []) if e.get(\"type\") == \"Alert\"]\n",
+ "\n",
+ "print(f\"Real-time monitoring: {len(alerts)} alerts generated\")\n",
+ "print(f\"Failure prediction: {len(failure_patterns)} failure patterns detected\")\n",
+ "print(f\"Temporal patterns: {len(temporal_patterns)} temporal patterns detected\")\n",
+ "print(\"\\n=== Pipeline Summary ===\")\n",
+ "print(f\"✓ Ingested {len(documents)} documents from sensor stream\")\n",
+ "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
+ "print(f\"✓ Created {len(chunked_docs)} chunks using token chunking\")\n",
+ "print(f\"✓ Built temporal KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"✓ This cookbook emphasizes stream processing, temporal KGs, and real-time monitoring\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 7: Visualization\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"smart_grid_kg.html\", layout=\"temporal\")\n",
+ "\n",
+ "print(\"Smart grid management analysis complete\")\n",
+ "print(\"Emphasizes: Stream processing, real-time monitoring, failure prediction, anomaly detection\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb b/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb
new file mode 100644
index 00000000..266cd525
--- /dev/null
+++ b/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb
@@ -0,0 +1,221 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb)\n",
+ "\n",
+ "# Supply Chain Data Integration - Multi-Source Ingestion & KG Construction\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **supply chain data integration** using Semantica with focus on **multi-source ingestion**, **relationship mapping**, and **logistics tracking**. The pipeline ingests logistics and supplier data to build a comprehensive supply chain knowledge graph.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Multi-Source Ingestion**: Ingests data from multiple logistics and supplier sources\n",
+ "- **Relationship Mapping**: Maps supplier relationships and logistics routes\n",
+ "- **Logistics Tracking**: Tracks products, routes, and locations\n",
+ "- **KG Construction**: Emphasizes ingestion and KG construction for supply chain\n",
+ "- **Supplier Relationship Mapping**: Maps complex supplier networks\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: Multi-Source Data Ingestion (Logistics, Suppliers)\n",
+ "3. **Phase 2**: Entity Extraction (Supplier, Product, Route, Location, Logistics)\n",
+ "4. **Phase 3**: Supply Chain Knowledge Graph Construction\n",
+ "5. **Phase 4**: Relationship Mapping\n",
+ "6. **Phase 5**: Logistics Tracking\n",
+ "7. **Phase 6**: Visualization & Export\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Supply_Chain_Data_Integration\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\"}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "print(\"Configured for supply chain data integration with multi-source ingestion focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (Logistics RSS Feeds)\n",
+ "\n",
+ "Ingest supply chain data from logistics RSS feeds.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, FileIngestor\n",
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.deduplication import DuplicateDetector\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "# Ingest from logistics RSS feeds\n",
+ "logistics_feeds = [\n",
+ " # Add logistics news RSS feeds here\n",
+ "]\n",
+ "\n",
+ "documents = []\n",
+ "for feed_url in logistics_feeds:\n",
+ " try:\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " feed_documents = feed_ingestor.ingest(feed_url, method=\"rss\")\n",
+ " documents.extend(feed_documents)\n",
+ " except Exception as e:\n",
+ " print(f\"Feed ingestion failed: {e}\")\n",
+ "\n",
+ "# Fallback: Sample data\n",
+ "if not documents:\n",
+ " supply_data = \"\"\"\n",
+ " Supplier A provides Product X to Warehouse W1 located in City C1.\n",
+ " Supplier B provides Product Y to Warehouse W2 located in City C2.\n",
+ " Route R1 connects Warehouse W1 to Distribution Center D1.\n",
+ " Logistics: Product X shipped via Route R1 from W1 to D1.\n",
+ " \"\"\"\n",
+ " with open(\"data/supply_chain.txt\", \"w\") as f:\n",
+ " f.write(supply_data)\n",
+ " documents = FileIngestor().ingest(\"data/supply_chain.txt\")\n",
+ " print(f\"Ingested {len(documents)} documents from sample data\")\n",
+ "\n",
+ "# Normalize supplier names\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Build supply chain knowledge graph\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=normalized_documents,\n",
+ " custom_entity_types=[\"Supplier\", \"Product\", \"Route\", \"Location\", \"Logistics\"],\n",
+ " graph=True\n",
+ ")\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "entities = result[\"entities\"]\n",
+ "\n",
+ "# Deduplicate suppliers\n",
+ "suppliers = [e for e in entities if e.get(\"type\") == \"Supplier\" or \"supplier\" in e.get(\"type\", \"\").lower()]\n",
+ "detector = DuplicateDetector()\n",
+ "duplicates = detector.detect_duplicates(suppliers, threshold=0.9)\n",
+ "deduplicated_suppliers = detector.resolve_duplicates(suppliers, duplicates)\n",
+ "\n",
+ "print(f\"Built supply chain KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"Deduplicated: {len(suppliers)} -> {len(deduplicated_suppliers)} unique suppliers\")\n",
+ "print(\"Focus: Multi-source ingestion, relationship mapping, logistics tracking, KG construction\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Map supplier relationships\n",
+ "supplier_relations = [r for r in kg.get(\"relationships\", []) \n",
+ " if \"supplier\" in str(r.get(\"predicate\", \"\")).lower() or\n",
+ " \"provides\" in str(r.get(\"predicate\", \"\")).lower()]\n",
+ "\n",
+ "# Track logistics routes\n",
+ "logistics_routes = [e for e in kg.get(\"entities\", []) \n",
+ " if e.get(\"type\") == \"Route\" or e.get(\"type\") == \"Logistics\"]\n",
+ "\n",
+ "print(f\"Relationship mapping: {len(supplier_relations)} supplier relationships mapped\")\n",
+ "print(f\"Logistics tracking: {len(logistics_routes)} routes tracked\")\n",
+ "print(\"This cookbook emphasizes multi-source ingestion and relationship mapping\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 6: Visualization\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"supply_chain_kg.html\")\n",
+ "\n",
+ "print(\"Supply chain data integration complete\")\n",
+ "print(\"Emphasizes: Multi-source ingestion, relationship mapping, logistics tracking\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb b/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb
new file mode 100644
index 00000000..6caa8232
--- /dev/null
+++ b/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb
@@ -0,0 +1,226 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb)\n",
+ "\n",
+ "# Supply Chain Risk Management - Dependency Analysis & Reasoning\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **supply chain risk management** using Semantica with focus on **dependency analysis**, **risk pattern detection**, and **external feed correlation**. The pipeline detects risks in the supply chain by analyzing dependencies and external feeds using reasoning and analytics.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Dependency Analysis**: Analyzes supply chain dependencies using graph reasoning\n",
+ "- **Risk Pattern Detection**: Detects risk patterns in the supply chain\n",
+ "- **External Feed Correlation**: Correlates external feeds with supply chain data\n",
+ "- **Reasoning**: Emphasizes reasoning and analytics for risk detection\n",
+ "- **Risk Mitigation**: Identifies mitigation strategies through graph analysis\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: Supply Chain & External Feed Ingestion\n",
+ "3. **Phase 2**: Entity Extraction (Dependency, Risk, Disruption, Impact, Mitigation)\n",
+ "4. **Phase 3**: Supply Chain Knowledge Graph Construction\n",
+ "5. **Phase 4**: Dependency Analysis\n",
+ "6. **Phase 5**: Risk Pattern Detection\n",
+ "7. **Phase 6**: External Feed Correlation\n",
+ "8. **Phase 7**: Visualization & Risk Reporting\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.reasoning import GraphReasoner\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Supply_Chain_Risk_Management\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\"}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "print(\"Configured for supply chain risk management with reasoning focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (Supply Chain RSS Feeds)\n",
+ "\n",
+ "Ingest supply chain risk data from RSS feeds.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, FileIngestor\n",
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.conflicts import ConflictDetector\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "# Ingest from supply chain RSS feeds\n",
+ "supply_feeds = [\n",
+ " # Add supply chain news RSS feeds here\n",
+ "]\n",
+ "\n",
+ "documents = []\n",
+ "for feed_url in supply_feeds:\n",
+ " try:\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " feed_documents = feed_ingestor.ingest(feed_url, method=\"rss\")\n",
+ " documents.extend(feed_documents)\n",
+ " except Exception as e:\n",
+ " print(f\"Feed ingestion failed: {e}\")\n",
+ "\n",
+ "# Fallback: Sample data\n",
+ "if not documents:\n",
+ " risk_data = \"\"\"\n",
+ " Supplier A depends on raw materials from Region R1 (high risk region).\n",
+ " Disruption in Region R1 impacts Supplier A, causing supply chain risk.\n",
+ " External feed: Weather alert in Region R1 may disrupt logistics.\n",
+ " Risk mitigation: Identify alternative suppliers in Region R2.\n",
+ " \"\"\"\n",
+ " with open(\"data/supply_chain_risks.txt\", \"w\") as f:\n",
+ " f.write(risk_data)\n",
+ " documents = FileIngestor().ingest(\"data/supply_chain_risks.txt\")\n",
+ " print(f\"Ingested {len(documents)} documents from sample data\")\n",
+ "\n",
+ "# Normalize risk data\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Build supply chain risk knowledge graph\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=normalized_documents,\n",
+ " custom_entity_types=[\"Dependency\", \"Risk\", \"Disruption\", \"Impact\", \"Mitigation\"],\n",
+ " graph=True\n",
+ ")\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "entities = result[\"entities\"]\n",
+ "\n",
+ "# Detect conflicts in risk data\n",
+ "detector = ConflictDetector()\n",
+ "conflicts = detector.detect_conflicts(entities, kg.get(\"relationships\", []))\n",
+ "\n",
+ "print(f\"Built risk management KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"Detected {len(conflicts)} conflicts in risk data\")\n",
+ "if conflicts:\n",
+ " resolved = detector.resolve_conflicts(conflicts, strategy=\"highest_confidence\")\n",
+ " print(f\"Resolved {len(resolved)} conflicts\")\n",
+ "print(\"Focus: Dependency analysis, risk pattern detection, external feed correlation, reasoning\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Analyze dependencies using reasoning\n",
+ "reasoner = GraphReasoner(kg)\n",
+ "dependencies = reasoner.find_patterns(pattern_type=\"dependency\")\n",
+ "risk_patterns = reasoner.find_patterns(pattern_type=\"risk\")\n",
+ "\n",
+ "# Identify high-risk dependencies\n",
+ "high_risk = [e for e in kg.get(\"entities\", []) \n",
+ " if e.get(\"type\") == \"Risk\" and \n",
+ " \"high\" in str(e.get(\"text\", \"\")).lower()]\n",
+ "\n",
+ "print(f\"Dependency analysis: {len(dependencies)} dependencies identified\")\n",
+ "print(f\"Risk pattern detection: {len(risk_patterns)} risk patterns found\")\n",
+ "print(f\"High-risk items: {len(high_risk)} high-risk dependencies flagged\")\n",
+ "print(\"This cookbook emphasizes reasoning and analytics for risk management\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 7: Visualization\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"supply_chain_risk_kg.html\")\n",
+ "\n",
+ "print(\"Supply chain risk management analysis complete\")\n",
+ "print(\"Emphasizes: Dependency analysis, risk pattern detection, external feed correlation, reasoning\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/trading/01_Risk_Assessment.ipynb b/cookbook/use_cases/trading/01_Risk_Assessment.ipynb
new file mode 100644
index 00000000..2a844251
--- /dev/null
+++ b/cookbook/use_cases/trading/01_Risk_Assessment.ipynb
@@ -0,0 +1,263 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/trading/01_Risk_Assessment.ipynb)\n",
+ "\n",
+ "# Risk Assessment - Graph Analytics & Portfolio Risk Modeling\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **portfolio risk assessment** using Semantica with focus on **graph-based analytics**, **portfolio risk modeling**, **market simulation**, and **dependency analysis**. The pipeline assesses portfolio risk using graph-based analytics and market simulations.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Graph-Based Analytics**: Uses graph analytics for portfolio risk analysis\n",
+ "- **Portfolio Risk Modeling**: Models portfolio relationships and dependencies\n",
+ "- **Market Simulation**: Simulates market scenarios using graph data\n",
+ "- **Dependency Analysis**: Analyzes dependencies between portfolio components\n",
+ "- **Risk Modeling**: Emphasizes graph analytics, reasoning, and risk modeling\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: Portfolio Data Ingestion\n",
+ "3. **Phase 2**: Entity Extraction (Price, Signal, Pattern, Indicator, Strategy)\n",
+ "4. **Phase 3**: Financial Knowledge Graph Construction\n",
+ "5. **Phase 4**: Graph Analytics (Dependencies, Relationships)\n",
+ "6. **Phase 5**: Portfolio Risk Modeling\n",
+ "7. **Phase 6**: Market Simulation\n",
+ "8. **Phase 7**: Visualization & Risk Reporting\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.kg import GraphAnalytics\n",
+ "from semantica.reasoning import GraphReasoner\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"Risk_Assessment\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\"}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "print(\"Configured for risk assessment with graph analytics focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (Yahoo Finance API & RSS Feeds)\n",
+ "\n",
+ "Ingest portfolio data from Yahoo Finance API and financial RSS feeds.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import WebIngestor, FeedIngestor, FileIngestor\n",
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.deduplication import DuplicateDetector\n",
+ "from semantica.split import TextSplitter\n",
+ "from semantica.context import AgentContext\n",
+ "from semantica.vector_store import VectorStore\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "documents = []\n",
+ "\n",
+ "# Option 1: Ingest from Yahoo Finance API\n",
+ "yahoo_api = \"https://query1.finance.yahoo.com/v8/finance/chart/AAPL\"\n",
+ "try:\n",
+ " web_ingestor = WebIngestor()\n",
+ " api_documents = web_ingestor.ingest(yahoo_api, method=\"url\")\n",
+ " documents.extend(api_documents)\n",
+ "except Exception as e:\n",
+ " print(f\"API ingestion failed: {e}\")\n",
+ "\n",
+ "# Option 2: Ingest from financial RSS feeds\n",
+ "financial_feeds = [\n",
+ " # Add financial news RSS feeds here\n",
+ "]\n",
+ "\n",
+ "for feed_url in financial_feeds:\n",
+ " try:\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " feed_documents = feed_ingestor.ingest(feed_url, method=\"rss\")\n",
+ " documents.extend(feed_documents)\n",
+ " except Exception as e:\n",
+ " print(f\"Feed ingestion failed: {e}\")\n",
+ "\n",
+ "# Fallback: Sample data\n",
+ "if not documents:\n",
+ " portfolio_data = \"\"\"\n",
+ " Portfolio contains: Stock AAPL (30%), Stock MSFT (25%), Stock GOOGL (20%), Bond BND (25%).\n",
+ " AAPL price correlates with tech sector performance.\n",
+ " MSFT depends on cloud services market growth.\n",
+ " Portfolio risk: High concentration in tech sector (75%).\n",
+ " Dependency: Tech sector downturn impacts 75% of portfolio.\n",
+ " \"\"\"\n",
+ " with open(\"data/portfolio.txt\", \"w\") as f:\n",
+ " f.write(portfolio_data)\n",
+ " documents = FileIngestor().ingest(\"data/portfolio.txt\")\n",
+ " print(f\"Ingested {len(documents)} documents from sample data\")\n",
+ "\n",
+ "# Normalize financial data\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " normalize_numbers=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Use entity-aware or graph-based chunking for portfolio relationships\n",
+ "splitter = TextSplitter(method=\"entity_aware\", ner_method=\"llm\", chunk_size=1000, chunk_overlap=200)\n",
+ "# Alternative: graph_based chunking\n",
+ "# splitter = TextSplitter(method=\"graph_based\", knowledge_graph=None, chunk_size=1000)\n",
+ "\n",
+ "chunked_docs = []\n",
+ "for doc_text in normalized_documents:\n",
+ " chunks = splitter.split(doc_text)\n",
+ " chunked_docs.extend([chunk.content if hasattr(chunk, 'content') else str(chunk) for chunk in chunks])\n",
+ "\n",
+ "print(f\"Created {len(chunked_docs)} entity-aware chunks\")\n",
+ "\n",
+ "# Build financial knowledge graph\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=chunked_docs,\n",
+ " custom_entity_types=[\"Price\", \"Signal\", \"Pattern\", \"Indicator\", \"Strategy\"],\n",
+ " graph=True,\n",
+ " embeddings=True\n",
+ ")\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "entities = result[\"entities\"]\n",
+ "\n",
+ "# Deduplicate portfolio entities\n",
+ "portfolio_entities = [e for e in entities if e.get(\"type\") in [\"Price\", \"Signal\", \"Pattern\"]]\n",
+ "detector = DuplicateDetector()\n",
+ "duplicates = detector.detect_duplicates(portfolio_entities, threshold=0.9)\n",
+ "deduplicated = detector.resolve_duplicates(portfolio_entities, duplicates)\n",
+ "\n",
+ "print(f\"Built portfolio KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"Deduplicated: {len(portfolio_entities)} -> {len(deduplicated)} unique entities\")\n",
+ "\n",
+ "# Setup GraphRAG for portfolio analysis\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=384)\n",
+ "if result.get(\"embeddings\"):\n",
+ " vector_store.store_vectors(\n",
+ " vectors=result[\"embeddings\"][\"vectors\"],\n",
+ " metadata=result[\"embeddings\"][\"metadata\"]\n",
+ " )\n",
+ "context = AgentContext(vector_store=vector_store, knowledge_graph=kg)\n",
+ "\n",
+ "print(\"Focus: Graph analytics, GraphRAG, portfolio risk modeling, market simulation, dependency analysis\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Perform graph analytics for risk assessment\n",
+ "analytics = GraphAnalytics(kg)\n",
+ "centrality = analytics.calculate_centrality(method=\"betweenness\")\n",
+ "\n",
+ "# Use reasoning for dependency analysis\n",
+ "reasoner = GraphReasoner(kg)\n",
+ "dependencies = reasoner.find_patterns(pattern_type=\"dependency\")\n",
+ "risk_patterns = reasoner.find_patterns(pattern_type=\"risk\")\n",
+ "\n",
+ "print(f\"Graph analytics: {len(centrality)} nodes analyzed for centrality\")\n",
+ "print(f\"Dependency analysis: {len(dependencies)} portfolio dependencies identified\")\n",
+ "print(f\"Risk modeling: {len(risk_patterns)} risk patterns detected\")\n",
+ "print(\"This cookbook emphasizes graph analytics, reasoning, and risk modeling\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 7: Visualization\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"portfolio_risk_kg.html\")\n",
+ "\n",
+ "print(\"Risk assessment analysis complete\")\n",
+ "print(\"Emphasizes: Graph analytics, portfolio risk modeling, market simulation, dependency analysis\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/trading/02_News_Sentiment_Analysis.ipynb b/cookbook/use_cases/trading/02_News_Sentiment_Analysis.ipynb
new file mode 100644
index 00000000..8bf0ff37
--- /dev/null
+++ b/cookbook/use_cases/trading/02_News_Sentiment_Analysis.ipynb
@@ -0,0 +1,249 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/trading/02_News_Sentiment_Analysis.ipynb)\n",
+ "\n",
+ "# News Sentiment Analysis - Semantic Extraction & Correlation\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **news sentiment analysis** using Semantica with focus on **sentiment extraction**, **correlation analysis**, **financial KG**, and **price movement prediction**. The pipeline correlates news sentiment with price movements using financial knowledge graphs.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Sentiment Extraction**: Extracts sentiment from financial news articles\n",
+ "- **Correlation Analysis**: Correlates sentiment with price movements\n",
+ "- **Financial Knowledge Graph**: Builds financial KGs for correlation analysis\n",
+ "- **Price Movement Prediction**: Predicts price movements based on sentiment\n",
+ "- **Semantic Extraction**: Emphasizes semantic extraction and correlation analysis\n",
+ "\n",
+ "### Pipeline Architecture\n",
+ "\n",
+ "1. **Phase 0**: Setup & Configuration\n",
+ "2. **Phase 1**: Financial News Ingestion\n",
+ "3. **Phase 2**: Sentiment Extraction\n",
+ "4. **Phase 3**: Financial Entity Extraction (Article, Sentiment, Price, Correlation, Trend)\n",
+ "5. **Phase 4**: Financial Knowledge Graph Construction\n",
+ "6. **Phase 5**: Sentiment-Price Correlation Analysis\n",
+ "7. **Phase 6**: Price Movement Prediction\n",
+ "8. **Phase 7**: Visualization & Export\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 0: Setup & Configuration\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from semantica.core import Semantica, ConfigManager\n",
+ "from semantica.semantic_extract import SentimentAnalyzer\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "\n",
+ "config_dict = {\n",
+ " \"project_name\": \"News_Sentiment_Analysis\",\n",
+ " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
+ " \"knowledge_graph\": {\"backend\": \"networkx\"}\n",
+ "}\n",
+ "\n",
+ "config = ConfigManager().load_from_dict(config_dict)\n",
+ "core = Semantica(config=config)\n",
+ "sentiment_analyzer = SentimentAnalyzer()\n",
+ "print(\"Configured for news sentiment analysis with semantic extraction focus\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 1: Real Data Ingestion (Financial RSS Feeds)\n",
+ "\n",
+ "Ingest financial news from RSS feeds.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, FileIngestor\n",
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.split import TextSplitter\n",
+ "from semantica.context import AgentContext\n",
+ "from semantica.vector_store import VectorStore\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "# Ingest from financial RSS feeds\n",
+ "financial_feeds = [\n",
+ " # Add financial news RSS feeds here\n",
+ "]\n",
+ "\n",
+ "documents = []\n",
+ "for feed_url in financial_feeds:\n",
+ " try:\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " feed_documents = feed_ingestor.ingest(feed_url, method=\"rss\")\n",
+ " documents.extend(feed_documents)\n",
+ " except Exception as e:\n",
+ " print(f\"Feed ingestion failed: {e}\")\n",
+ "\n",
+ "# Fallback: Sample data\n",
+ "if not documents:\n",
+ " news_data = \"\"\"\n",
+ " 2024-01-01: Positive news about AAPL earnings beat expectations. Stock price rose 5%.\n",
+ " 2024-01-02: Negative sentiment: MSFT faces regulatory concerns. Stock price dropped 3%.\n",
+ " 2024-01-03: Mixed sentiment: GOOGL announces new product. Stock price stable.\n",
+ " Correlation: Positive news correlates with price increases. Negative news correlates with price drops.\n",
+ " \"\"\"\n",
+ " with open(\"data/financial_news.txt\", \"w\") as f:\n",
+ " f.write(news_data)\n",
+ " documents = FileIngestor().ingest(\"data/financial_news.txt\")\n",
+ " print(f\"Ingested {len(documents)} documents from sample data\")\n",
+ "\n",
+ "# Normalize sentiment data\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "\n",
+ "# Use semantic_transformer or entity_aware chunking for semantic article chunking\n",
+ "splitter = TextSplitter(method=\"semantic_transformer\", chunk_size=1000, similarity_threshold=0.7)\n",
+ "# Alternative: entity_aware for financial entity preservation\n",
+ "# splitter = TextSplitter(method=\"entity_aware\", ner_method=\"llm\", chunk_size=1000)\n",
+ "\n",
+ "chunked_docs = []\n",
+ "for doc_text in normalized_documents:\n",
+ " chunks = splitter.split(doc_text)\n",
+ " chunked_docs.extend([chunk.content if hasattr(chunk, 'content') else str(chunk) for chunk in chunks])\n",
+ "\n",
+ "print(f\"Created {len(chunked_docs)} semantic chunks\")\n",
+ "\n",
+ "# Extract sentiment\n",
+ "sentiments = sentiment_analyzer.analyze_sentiment([doc for doc in chunked_docs])\n",
+ "\n",
+ "# Build financial knowledge graph with sentiment\n",
+ "result = core.build_knowledge_base(\n",
+ " sources=chunked_docs,\n",
+ " custom_entity_types=[\"Article\", \"Sentiment\", \"Price\", \"Correlation\", \"Trend\"],\n",
+ " graph=True,\n",
+ " embeddings=True\n",
+ ")\n",
+ "\n",
+ "kg = result[\"knowledge_graph\"]\n",
+ "\n",
+ "# Setup enhanced GraphRAG\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=384)\n",
+ "if result.get(\"embeddings\"):\n",
+ " vector_store.store_vectors(\n",
+ " vectors=result[\"embeddings\"][\"vectors\"],\n",
+ " metadata=result[\"embeddings\"][\"metadata\"]\n",
+ " )\n",
+ "context = AgentContext(vector_store=vector_store, knowledge_graph=kg)\n",
+ "\n",
+ "print(f\"Built financial KG with {len(kg.get('entities', []))} entities\")\n",
+ "print(f\"Extracted {len(sentiments)} sentiment scores\")\n",
+ "print(\"Focus: Sentiment extraction, enhanced GraphRAG, correlation analysis, financial KG, price movement prediction\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Correlate sentiment with price movements\n",
+ "from semantica.reasoning import GraphReasoner\n",
+ "\n",
+ "reasoner = GraphReasoner(kg)\n",
+ "correlations = reasoner.find_correlations(\n",
+ " source_types=[\"Sentiment\"],\n",
+ " target_types=[\"Price\"]\n",
+ ")\n",
+ "\n",
+ "# Identify sentiment-price correlations\n",
+ "sentiment_price_rels = [r for r in kg.get(\"relationships\", []) \n",
+ " if \"correlate\" in str(r.get(\"predicate\", \"\")).lower() or\n",
+ " \"sentiment\" in str(r.get(\"predicate\", \"\")).lower()]\n",
+ "\n",
+ "print(f\"Correlation analysis: {len(correlations)} sentiment-price correlations found\")\n",
+ "print(f\"Sentiment-price relationships: {len(sentiment_price_rels)} relationships identified\")\n",
+ "print(\"This cookbook emphasizes semantic extraction and correlation analysis\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Phase 7: Visualization\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(kg, output_path=\"news_sentiment_kg.html\")\n",
+ "\n",
+ "print(\"News sentiment analysis complete\")\n",
+ "print(\"Emphasizes: Sentiment extraction, correlation analysis, financial KG, price movement prediction\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/docs/cookbook.md b/docs/cookbook.md
index 2ca6b518..67def4b1 100644
--- a/docs/cookbook.md
+++ b/docs/cookbook.md
@@ -96,7 +96,7 @@ Hand-picked tutorials to show you the power of Semantica.
**Difficulty**: Advanced
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Anomaly_Detection_Real_Time.ipynb)
+ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb)
</div>
@@ -339,9 +339,9 @@ Real-world examples and end-to-end applications across various industries.
- :material-pill: **Drug Discovery Pipeline**
---
- Accelerating drug discovery by connecting genes, proteins, and drugs.
+ Accelerating drug discovery by connecting genes, proteins, and drugs using PubMed RSS feeds, entity-aware chunking, GraphRAG, and vector similarity search.
- **Topics**: Bioinformatics, KG Construction
+ **Topics**: Bioinformatics, KG Construction, GraphRAG, Vector Search
**Difficulty**: Advanced
@@ -349,9 +349,9 @@ Real-world examples and end-to-end applications across various industries.
- :material-dna: **Genomic Variant Analysis**
---
- Analyzing genomic variants and their implications for disease.
+ Analyzing genomic variants and their implications for disease using bioRxiv RSS feeds, temporal knowledge graphs, deduplication, and pathway analysis.
- **Topics**: Genomics, Variant Calling
+ **Topics**: Genomics, Variant Calling, Temporal KGs, Graph Analytics
**Difficulty**: Advanced
@@ -365,63 +365,23 @@ Real-world examples and end-to-end applications across various industries.
- :material-hospital-box: **Clinical Reports Processing**
---
- Processing and structuring unstructured clinical reports.
+ Processing and structuring unstructured clinical reports with FDA RSS feeds, HL7/FHIR integration, and patient record deduplication.
- **Topics**: NLP, Medical Records
+ **Topics**: NLP, Medical Records, EHR Integration, Deduplication
**Difficulty**: Intermediate
[Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb)
-- :material-virus: **Disease Network Analysis**
- ---
- Analyzing disease networks and comorbidities for population health.
-
- **Topics**: Disease Modeling, Comorbidity Networks
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/02_Disease_Network_Analysis.ipynb)
-
- :material-pill-multiple: **Drug Interactions Analysis**
---
- Identifying potential drug interactions and contraindications.
-
- **Topics**: Pharmacology, Drug Safety
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/03_Drug_Interactions_Analysis.ipynb)
-
-- :material-robot-love: **Healthcare GraphRAG Hybrid**
- ---
- Hybrid RAG system for healthcare knowledge retrieval.
+ Identifying potential drug interactions and contraindications using medical RSS feeds, relation-aware chunking, conflict detection, and safety ontology generation.
- **Topics**: RAG, Medical Knowledge, LLMs
+ **Topics**: Pharmacology, Drug Safety, Ontology, Conflict Resolution
**Difficulty**: Advanced
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb)
-
-- :material-database-plus: **Medical Database Integration**
- ---
- Integrating multiple medical databases into unified knowledge graphs.
-
- **Topics**: Data Integration, Medical Databases
-
- **Difficulty**: Intermediate
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/05_Medical_Database_Integration.ipynb)
-
-- :material-account-heart: **Patient Records Temporal**
- ---
- Analyzing patient records over time to track health progression.
-
- **Topics**: Temporal Analysis, Patient Journeys
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/06_Patient_Records_Temporal.ipynb)
+ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynb)
</div>
@@ -429,55 +389,25 @@ Real-world examples and end-to-end applications across various industries.
<div class="grid cards" markdown>
-- :material-finance: **Financial Data Integration**
- ---
- Merging financial data from reports, news, and market feeds.
-
- **Topics**: Finance, Data Fusion
-
- **Difficulty**: Intermediate
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/01_Financial_Data_Integration.ipynb)
-
-- :material-file-chart: **Financial Reports Analysis**
+- :material-finance: **Financial Data Integration MCP**
---
- Extracting insights from financial reports and earnings calls.
+ Merging financial data from Alpha Vantage API, MCP servers, RSS feeds, and market feeds with seed data integration.
- **Topics**: Financial Analysis, NLP
+ **Topics**: Finance, Data Fusion, MCP Integration, Real-Time Ingestion
**Difficulty**: Intermediate
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/02_Financial_Reports_Analysis.ipynb)
+ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb)
- :material-incognito: **Fraud Detection**
---
- Identifying fraudulent activities and patterns in transaction networks.
-
- **Topics**: Anomaly Detection, Graph Mining
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/03_Fraud_Detection.ipynb)
-
-- :material-chart-box: **Investment Analysis Hybrid RAG**
- ---
- AI-powered investment analysis using hybrid RAG approach.
+ Identifying fraudulent activities and patterns in transaction networks using temporal knowledge graphs, conflict detection, and pattern recognition.
- **Topics**: Investment Research, RAG, Financial Analysis
+ **Topics**: Anomaly Detection, Graph Mining, Temporal Analysis, Pattern Detection
**Difficulty**: Advanced
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/04_Investment_Analysis_Hybrid_RAG.ipynb)
-
-- :material-gavel: **Regulatory Compliance**
- ---
- Ensuring compliance with financial regulations using knowledge graphs.
-
- **Topics**: Compliance, Regulatory Analysis
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/05_Regulatory_Compliance.ipynb)
+ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/02_Fraud_Detection.ipynb)
</div>
@@ -487,9 +417,9 @@ Real-world examples and end-to-end applications across various industries.
- :material-bitcoin: **DeFi Protocol Intelligence**
---
- Analyzing decentralized finance protocols and transaction flows.
+ Analyzing decentralized finance protocols and transaction flows using CoinDesk RSS feeds, ontology-aware chunking, conflict detection, and ontology generation.
- **Topics**: Blockchain, DeFi, Smart Contracts
+ **Topics**: Blockchain, DeFi, Smart Contracts, Ontology, Conflict Resolution
**Difficulty**: Advanced
@@ -497,9 +427,9 @@ Real-world examples and end-to-end applications across various industries.
- :material-network: **Transaction Network Analysis**
---
- Mapping and analyzing blockchain transaction networks.
+ Mapping and analyzing blockchain transaction networks using blockchain APIs, deduplication, and network pattern detection.
- **Topics**: Blockchain Analytics, Network Analysis
+ **Topics**: Blockchain Analytics, Network Analysis, Deduplication, Pattern Detection
**Difficulty**: Advanced
@@ -511,65 +441,25 @@ Real-world examples and end-to-end applications across various industries.
<div class="grid cards" markdown>
-- :material-shield-alert: **Anomaly Detection Real-Time**
- ---
- Detecting anomalies in real-time network traffic streams.
-
- **Topics**: Network Security, Streaming
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Anomaly_Detection_Real_Time.ipynb)
-
-- :material-shield-search: **Incident Analysis**
- ---
- Analyzing security incidents and breaches using graph forensics.
-
- **Topics**: Incident Response, Forensics
-
- **Difficulty**: Intermediate
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/02_Incident_Analysis.ipynb)
-
-- :material-shield-link-variant: **Threat Correlation**
+- :material-shield-alert: **Real-Time Anomaly Detection**
---
- Correlating threats across different vectors to identify campaigns.
+ Detecting anomalies in real-time network traffic streams using CVE RSS feeds, Kafka streams, temporal knowledge graphs, and sentence chunking.
- **Topics**: Threat Intel, Correlation
+ **Topics**: Network Security, Streaming, Temporal KGs, Pattern Detection
**Difficulty**: Advanced
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/03_Threat_Correlation.ipynb)
+ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb)
- :material-robot-angry: **Threat Intelligence Hybrid RAG**
---
- Combining RAG with threat intelligence for enhanced security insights.
-
- **Topics**: Threat Intelligence, RAG, Security
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/04_Threat_Intelligence_Hybrid_RAG.ipynb)
-
-- :material-shield-plus: **Threat Intelligence Integration**
- ---
- Integrating threat feeds into a unified knowledge graph.
+ Combining enhanced GraphRAG with threat intelligence for security insights using security RSS feeds, entity-aware chunking, deduplication, and temporal knowledge graphs.
- **Topics**: STIX/TAXII, Threat Feeds, Integration
+ **Topics**: Threat Intelligence, GraphRAG, Security, Hybrid Retrieval
**Difficulty**: Advanced
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/05_Threat_Intelligence_Integration.ipynb)
-
-- :material-bug: **Vulnerability Tracking**
- ---
- Tracking and managing system vulnerabilities using knowledge graphs.
-
- **Topics**: CVE, Vulnerability Management
-
- **Difficulty**: Intermediate
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/06_Vulnerability_Tracking.ipynb)
+ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb)
</div>
@@ -579,33 +469,23 @@ Real-world examples and end-to-end applications across various industries.
- :material-account-network: **Criminal Network Analysis**
---
- Analyze criminal networks with graph analytics and key player detection.
+ Analyze criminal networks with graph analytics and key player detection using OSINT RSS feeds, deduplication, and network centrality analysis.
- **Topics**: Forensics, Social Network Analysis
+ **Topics**: Forensics, Social Network Analysis, Deduplication, Graph Analytics
**Difficulty**: Advanced
[Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb)
-- :material-file-search: **Intelligence Analysis**
+- :material-file-search: **Intelligence Analysis Orchestrator Worker**
---
- Comprehensive intelligence analysis using orchestrator-worker pattern with graph analytics and hybrid RAG.
+ Comprehensive intelligence analysis using pipeline orchestrator with multiple RSS feeds, conflict detection, and multi-source integration.
- **Topics**: Intelligence Analysis, Orchestrator-Worker, Graph Analytics
+ **Topics**: Intelligence Analysis, Pipeline Orchestration, Multi-Source Integration, Conflict Resolution
**Difficulty**: Advanced
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/02_Intelligence_Analysis.ipynb)
-
-- :material-gavel: **Law Enforcement Forensics**
- ---
- Forensic analysis pipeline for processing case files and evidence.
-
- **Topics**: Forensics, Evidence Analysis, Case Correlation
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/03_Law_Enforcement_Forensics.ipynb)
+ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb)
</div>
@@ -613,56 +493,26 @@ Real-world examples and end-to-end applications across various industries.
<div class="grid cards" markdown>
-- :material-chart-areaspline: **Market Data Analysis**
+- :material-shield-check: **Risk Assessment**
---
- Analyzing trading market data for patterns and opportunities.
+ Assessing trading risks using knowledge graphs, GraphRAG, entity-aware chunking, and portfolio risk modeling with Yahoo Finance API and RSS feeds.
- **Topics**: Trading, Market Analysis
+ **Topics**: Risk Management, Portfolio Analysis, GraphRAG, Dependency Analysis
- **Difficulty**: Intermediate
+ **Difficulty**: Advanced
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/trading/01_Market_Data_Analysis.ipynb)
+ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/trading/01_Risk_Assessment.ipynb)
- :material-newspaper-variant: **News Sentiment Analysis**
---
- Analyzing news sentiment for trading signals and market predictions.
+ Analyzing news sentiment for trading signals and market predictions using financial RSS feeds, semantic transformer chunking, enhanced GraphRAG, and sentiment extraction.
- **Topics**: Sentiment Analysis, Trading Signals
+ **Topics**: Sentiment Analysis, Trading Signals, GraphRAG, Correlation Analysis
**Difficulty**: Intermediate
[Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/trading/02_News_Sentiment_Analysis.ipynb)
-- :material-monitor-dashboard: **Real-Time Monitoring**
- ---
- Monitoring trading systems and positions in real-time.
-
- **Topics**: Monitoring, Real-Time Systems
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/trading/03_Real_Time_Monitoring.ipynb)
-
-- :material-shield-check: **Risk Assessment**
- ---
- Assessing trading risks using knowledge graphs and analytics.
-
- **Topics**: Risk Management, Portfolio Analysis
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/trading/04_Risk_Assessment.ipynb)
-
-- :material-history: **Strategy Backtesting**
- ---
- Backtesting trading strategies using historical data and graphs.
-
- **Topics**: Backtesting, Strategy Optimization
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/trading/05_Strategy_Backtesting.ipynb)
-
</div>
### Renewable Energy
@@ -671,43 +521,23 @@ Real-world examples and end-to-end applications across various industries.
- :material-wind-turbine: **Energy Market Analysis**
---
- Analyzing trends and pricing in the renewable energy market.
+ Analyzing trends and pricing in the renewable energy market using energy RSS feeds, EIA API, temporal knowledge graphs, TemporalPatternDetector, and seed data integration.
- **Topics**: Energy, Time Series
+ **Topics**: Energy, Time Series, Temporal Analysis, Trend Prediction
**Difficulty**: Intermediate
[Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb)
-- :material-leaf: **Environmental Impact**
- ---
- Assessing environmental impact of energy projects and policies.
-
- **Topics**: Environmental Science, Impact Analysis
-
- **Difficulty**: Intermediate
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/02_Environmental_Impact.ipynb)
-
-- :material-transmission-tower: **Grid Management**
- ---
- Optimizing power grid management and distribution.
-
- **Topics**: Grid Optimization, Energy Distribution
-
- **Difficulty**: Advanced
-
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/03_Grid_Management.ipynb)
-
-- :material-solar-power: **Resource Optimization**
+- :material-transmission-tower: **Smart Grid Management**
---
- Optimizing renewable energy resources and generation.
+ Optimizing power grid management and distribution using sensor streams, temporal knowledge graphs, token chunking, and real-time monitoring with failure prediction.
- **Topics**: Resource Management, Optimization
+ **Topics**: Grid Optimization, Energy Distribution, Stream Processing, Real-Time Monitoring
**Difficulty**: Advanced
- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/04_Resource_Optimization.ipynb)
+ [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/02_Smart_Grid_Management.ipynb)
</div>
@@ -717,9 +547,9 @@ Real-world examples and end-to-end applications across various industries.
- :material-truck-delivery: **Supply Chain Data Integration**
---
- Integrating supply chain data to optimize logistics and reduce risk.
+ Integrating supply chain data to optimize logistics and reduce risk using logistics RSS feeds, deduplication, and multi-source relationship mapping.
- **Topics**: Logistics, Risk Management
+ **Topics**: Logistics, Risk Management, Data Integration, Deduplication
**Difficulty**: Advanced
@@ -727,9 +557,9 @@ Real-world examples and end-to-end applications across various industries.
- :material-alert-octagon: **Supply Chain Risk Management**
---
- Managing and mitigating supply chain risks using knowledge graphs.
+ Managing and mitigating supply chain risks using knowledge graphs with supply chain RSS feeds, conflict detection, and dependency analysis.
- **Topics**: Risk Management, Supply Chain Resilience
+ **Topics**: Risk Management, Supply Chain Resilience, Conflict Resolution, Dependency Analysis
**Difficulty**: Advanced
diff --git a/docs/use-cases.md b/docs/use-cases.md
index 10623609..abed9648 100644
--- a/docs/use-cases.md
+++ b/docs/use-cases.md
@@ -127,7 +127,7 @@ ontology = ontology_gen.generate_from_graph(kg)
**Goal**: Ingest earnings call transcripts, news articles, and analyst reports to gauge market sentiment.
- [:material-arrow-right: View Cookbook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/01_Financial_Data_Integration.ipynb)
+ [:material-arrow-right: View Cookbook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb)
- :material-chart-line: **Algorithmic Trading Signals**
---
@@ -135,7 +135,7 @@ ontology = ontology_gen.generate_from_graph(kg)
**Goal**: Build a graph of companies, supply chains, and global events to identify non-obvious trading signals.
- [:material-arrow-right: View Cookbook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/trading/01_Market_Data_Analysis.ipynb)
+ [:material-arrow-right: View Cookbook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/trading/01_Risk_Assessment.ipynb)
- :material-bitcoin: **Blockchain Analytics**
---
@@ -181,37 +181,31 @@ ontology = ontology_gen.generate_from_graph(kg)
**Goal**: Ingest threat feeds (STIX/TAXII), CVE databases, and system logs to map attack vectors.
- [:material-arrow-right: View Cookbook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Anomaly_Detection_Real_Time.ipynb)
-
-- :material-eye: **Open Source Intelligence (OSINT)**
- ---
- Gather and analyze public information for intelligence purposes.
-
- **Goal**: Connect data from social media, news, and public records to build profiles.
-
- [:material-arrow-right: View Cookbook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb)
+ [:material-arrow-right: View Cookbook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb)
- :material-account-network: **Criminal Network Analysis**
---
- Analyze criminal networks to identify key players, communities, and suspicious patterns.
+ Analyze criminal networks to identify key players, communities, and suspicious patterns using OSINT RSS feeds, deduplication, and network centrality analysis.
**Goal**: Build knowledge graphs from police reports, court records, and surveillance data.
[:material-arrow-right: View Cookbook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb)
-- :material-shield-search: **Law Enforcement and Forensics**
+- :material-file-search: **Intelligence Analysis Orchestrator Worker**
---
- Process forensic evidence and correlate cases using temporal knowledge graphs.
+ Comprehensive intelligence analysis using pipeline orchestrator with multiple RSS feeds, conflict detection, and multi-source integration.
- **Goal**: Extract entities from case files to build temporal case timelines.
+ **Goal**: Process multiple intelligence sources in parallel using orchestrator-worker pattern.
- [:material-arrow-right: View Cookbook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/03_Law_Enforcement_Forensics.ipynb)
+ [:material-arrow-right: View Cookbook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb)
- :material-incognito: **Fraud Detection**
---
- Detect complex fraud rings.
+ Detect complex fraud rings using temporal knowledge graphs and pattern detection.
**Goal**: Build a graph of Users, Devices, IP Addresses, and Transactions to find cycles.
+
+ [:material-arrow-right: View Cookbook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/02_Fraud_Detection.ipynb)
</div>