Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
Refactor blockchain notebooks: Use modular architecture with comprehensive data sources and all Semantica modules
KaifAhmad15e220dc341e0
diff --git a/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb b/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynbindex d3ba3e62..70dda657 100644--- a/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb+++ b/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb@@ -598,4 +598,4 @@},"nbformat": 4,"nbformat_minor": 2-}\ No newline at end of file+}diff --git a/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb b/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynbindex 2dee6a96..51fe271e 100644--- a/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb+++ b/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb@@ -1,298 +1,682 @@{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](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+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "[](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 from multiple sources, extracts protocol entities, builds 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",+ "- **Comprehensive Data Sources**: Multiple RSS feeds, APIs, and databases\n",+ "- **Modular Architecture**: Direct use of Semantica modules without core orchestrator\n",+ "\n",+ "### Learning Objectives\n",+ "\n",+ "- Ingest DeFi data from multiple sources (RSS feeds, APIs, databases)\n",+ "- Extract DeFi entities (Protocols, Tokens, Pools, Transactions, Risks)\n",+ "- Build and analyze DeFi knowledge graphs\n",+ "- Generate and utilize DeFi ontologies\n",+ "- Perform risk assessment using graph reasoning\n",+ "- Store and query DeFi data using vector stores and graph stores\n",+ "\n",+ "### Pipeline Flow\n",+ "\n",+ "```mermaid\n",+ "graph TD\n",+ " A[Data Ingestion] --> B[Document Parsing]\n",+ " B --> C[Text Processing]\n",+ " C --> D[Entity Extraction]\n",+ " D --> E[Relationship Extraction]\n",+ " E --> F[Deduplication]\n",+ " F --> G[Conflict Detection]\n",+ " G --> H[Knowledge Graph]\n",+ " H --> I[Embeddings]\n",+ " I --> J[Vector Store]\n",+ " H --> K[Ontology Generation]\n",+ " K --> L[Reasoning & Risk]\n",+ " J --> M[GraphRAG Queries]\n",+ " L --> M\n",+ " H --> N[Graph Store]\n",+ " K --> O[Triplet Store]\n",+ " M --> P[Visualization]\n",+ " N --> P\n",+ " O --> P\n",+ " P --> Q[Export]\n",+ "```\n",+ "\n",+ "### Data Sources\n",+ "\n",+ "#### Crypto News RSS Feeds\n",+ "- **CoinDesk**: https://www.coindesk.com/arc/outboundfeeds/rss/\n",+ "- **CoinTelegraph**: https://cointelegraph.com/rss\n",+ "- **Decrypt**: https://decrypt.co/feed\n",+ "- **The Block**: https://www.theblock.co/rss.xml\n",+ "- **CryptoSlate**: https://cryptoslate.com/feed/\n",+ "- **CryptoNews**: https://cryptonews.com/news/feed/\n",+ "\n",+ "#### DeFi Data Sources\n",+ "- **DeFiPulse**: https://defipulse.com/\n",+ "- **DeFiLlama**: https://defillama.com/\n",+ "- **CoinGecko**: https://www.coingecko.com/en/api\n",+ "- **DeBank**: https://debank.com/\n",+ "- **Zapper**: https://zapper.fi/\n",+ "\n",+ "#### API Links\n",+ "- **Etherscan API**: https://etherscan.io/apis\n",+ "- **The Graph**: https://thegraph.com/\n",+ "- **Moralis**: https://moralis.io/\n",+ "- **Alchemy**: https://www.alchemy.com/\n",+ "- **Infura**: https://www.infura.io/\n",+ "- **QuickNode**: https://www.quicknode.com/\n",+ "\n",+ "#### Database Links\n",+ "- **CoinMarketCap**: https://coinmarketcap.com/api/\n",+ "- **Dune Analytics**: https://dune.com/\n",+ "- **Nansen**: https://www.nansen.ai/\n",+ "- **Glassnode**: https://glassnode.com/\n",+ "- **Messari**: https://messari.io/api\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 beautifulsoup4 groq sentence-transformers scikit-learn\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Configuration & Setup\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "import os\n",+ "\n",+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key-here\")\n",+ "\n",+ "# Configuration constants\n",+ "EMBEDDING_DIMENSION = 384\n",+ "EMBEDDING_MODEL = \"all-MiniLM-L6-v2\"\n",+ "CHUNK_SIZE = 1000\n",+ "CHUNK_OVERLAP = 200\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Ingesting DeFi Data from Multiple Sources\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.ingest import FeedIngestor, FileIngestor, WebIngestor\n",+ "import os\n",+ "from contextlib import redirect_stderr\n",+ "from io import StringIO\n",+ "\n",+ "os.makedirs(\"data\", exist_ok=True)\n",+ "\n",+ "feed_sources = [\n",+ " # Crypto News RSS Feeds\n",+ " (\"CoinDesk\", \"https://www.coindesk.com/arc/outboundfeeds/rss/\"),\n",+ " (\"CoinTelegraph\", \"https://cointelegraph.com/rss\"),\n",+ " (\"Decrypt\", \"https://decrypt.co/feed\"),\n",+ " (\"The Block\", \"https://www.theblock.co/rss.xml\"),\n",+ " (\"CryptoSlate\", \"https://cryptoslate.com/feed/\"),\n",+ " (\"CryptoNews\", \"https://cryptonews.com/news/feed/\"),\n",+ "]\n",+ "\n",+ "feed_ingestor = FeedIngestor()\n",+ "all_documents = []\n",+ "\n",+ "for feed_name, feed_url in feed_sources:\n",+ " try:\n",+ " with redirect_stderr(StringIO()):\n",+ " feed_data = feed_ingestor.ingest_feed(feed_url, validate=False)\n",+ " for item in feed_data.items:\n",+ " if not item.content:\n",+ " item.content = item.description or item.title or \"\"\n",+ " if item.content:\n",+ " if not hasattr(item, 'metadata'):\n",+ " item.metadata = {}\n",+ " item.metadata['source'] = feed_name\n",+ " all_documents.append(item)\n",+ " except Exception:\n",+ " continue\n",+ "\n",+ "if not all_documents:\n",+ " defi_data = \"\"\"\n",+ " Uniswap is a decentralized exchange protocol with high liquidity pools. It uses automated market makers (AMMs) for token swaps.\n",+ " Aave is a lending protocol that offers variable and stable interest rates. Users can deposit assets to earn yield.\n",+ " Compound is a money market protocol for lending and borrowing cryptocurrencies. It uses algorithmic interest rates.\n",+ " MakerDAO uses collateralized debt positions (CDPs) for stablecoin generation. DAI is the stablecoin created.\n",+ " Curve Finance is a decentralized exchange optimized for stablecoin trading with low slippage.\n",+ " Yearn Finance aggregates yield farming strategies across multiple DeFi protocols.\n",+ " SushiSwap is a decentralized exchange and automated market maker with yield farming features.\n",+ " Balancer is a protocol for programmable liquidity and automated portfolio management.\n",+ " \"\"\"\n",+ " with open(\"data/defi_protocols.txt\", \"w\") as f:\n",+ " f.write(defi_data)\n",+ " file_ingestor = FileIngestor()\n",+ " all_documents = file_ingestor.ingest(\"data/defi_protocols.txt\")\n",+ "\n",+ "documents = all_documents\n",+ "print(f\"Ingested {len(documents)} documents\")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.parse import DocumentParser\n",+ "\n",+ "parser = DocumentParser()\n",+ "\n",+ "parsed_documents = []\n",+ "for doc in documents:\n",+ " try:\n",+ " parsed = parser.parse(\n",+ " doc.content if hasattr(doc, 'content') else str(doc),\n",+ " content_type=\"text\"\n",+ " )\n",+ " parsed_documents.append(parsed)\n",+ " except Exception:\n",+ " parsed_documents.append(doc)\n",+ "\n",+ "documents = parsed_documents\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Normalizing and Chunking DeFi Documents\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.normalize import TextNormalizer\n",+ "from semantica.split import TextSplitter\n",+ "\n",+ "normalizer = TextNormalizer()\n",+ "splitter = TextSplitter(\n",+ " method=\"entity_aware\",\n",+ " ner_method=\"spacy\",\n",+ " chunk_size=CHUNK_SIZE,\n",+ " chunk_overlap=CHUNK_OVERLAP\n",+ ")\n",+ "\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\n",+ " )\n",+ " normalized_documents.append(normalized_text)\n",+ "\n",+ "chunked_documents = []\n",+ "for doc_text in normalized_documents:\n",+ " try:\n",+ " with redirect_stderr(StringIO()):\n",+ " chunks = splitter.split(doc_text)\n",+ " chunked_documents.extend(chunks)\n",+ " except Exception:\n",+ " simple_splitter = TextSplitter(method=\"recursive\", chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)\n",+ " chunks = simple_splitter.split(doc_text)\n",+ " chunked_documents.extend(chunks)\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Extracting DeFi Entities\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.semantic_extract import NERExtractor\n",+ "\n",+ "entity_extractor = NERExtractor(\n",+ " method=\"llm\",\n",+ " provider=\"groq\",\n",+ " llm_model=\"llama-3.1-8b-instant\",\n",+ " temperature=0.0\n",+ ")\n",+ "\n",+ "all_entities = []\n",+ "for chunk in chunked_documents:\n",+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",+ " try:\n",+ " entities = entity_extractor.extract_entities(\n",+ " chunk_text,\n",+ " entity_types=[\"Protocol\", \"Token\", \"Pool\", \"Transaction\", \"Risk\"]\n",+ " )\n",+ " all_entities.extend(entities)\n",+ " except Exception:\n",+ " continue\n",+ "\n",+ "protocols = [e for e in all_entities if e.label == \"Protocol\" or \"protocol\" in e.label.lower()]\n",+ "tokens = [e for e in all_entities if e.label == \"Token\" or \"token\" in e.label.lower()]\n",+ "risks = [e for e in all_entities if e.label == \"Risk\" or \"risk\" in e.label.lower()]\n",+ "\n",+ "print(f\"Extracted {len(protocols)} protocols, {len(tokens)} tokens, {len(risks)} risks\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Extracting DeFi Relationships\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.semantic_extract import RelationExtractor\n",+ "\n",+ "relation_extractor = RelationExtractor(\n",+ " method=\"llm\",\n",+ " provider=\"groq\",\n",+ " llm_model=\"llama-3.1-8b-instant\",\n",+ " temperature=0.0\n",+ ")\n",+ "\n",+ "all_relationships = []\n",+ "for chunk in chunked_documents:\n",+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",+ " try:\n",+ " relationships = relation_extractor.extract_relations(\n",+ " chunk_text,\n",+ " entities=all_entities,\n",+ " relation_types=[\"uses\", \"governs\", \"provides\", \"has_risk\", \"interacts_with\", \"depends_on\"]\n",+ " )\n",+ " all_relationships.extend(relationships)\n",+ " except Exception:\n",+ " continue\n",+ "\n",+ "print(f\"Extracted {len(all_relationships)} relationships\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Resolving Duplicate Entities\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.deduplication import DuplicateDetector\n",+ "\n",+ "duplicate_detector = DuplicateDetector(\n",+ " similarity_threshold=0.85,\n",+ " method=\"semantic\"\n",+ ")\n",+ "\n",+ "deduplicated_entities = duplicate_detector.detect_duplicates(all_entities)\n",+ "merged_entities = duplicate_detector.merge_duplicates(deduplicated_entities)\n",+ "\n",+ "print(f\"Deduplicated {len(all_entities)} entities to {len(merged_entities)} unique entities\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Detecting and Resolving Conflicts\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.conflicts import ConflictDetector\n",+ "\n",+ "conflict_detector = ConflictDetector()\n",+ "\n",+ "conflicts = conflict_detector.detect_conflicts(merged_entities, all_relationships)\n",+ "\n",+ "if conflicts:\n",+ " resolved = conflict_detector.resolve_conflicts(conflicts, strategy=\"highest_confidence\")\n",+ " print(f\"Detected {len(conflicts)} conflicts, resolved {len(resolved)}\")\n",+ "else:\n",+ " print(\"No conflicts detected\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Building DeFi Knowledge Graph\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.kg import GraphBuilder\n",+ "\n",+ "graph_builder = GraphBuilder(\n",+ " merge_entities=True,\n",+ " resolve_conflicts=True,\n",+ " entity_resolution_strategy=\"fuzzy\"\n",+ ")\n",+ "\n",+ "kg_sources = [{\n",+ " \"entities\": [{\"text\": e.text, \"type\": e.label, \"confidence\": e.confidence} for e in merged_entities],\n",+ " \"relationships\": [{\"source\": r.source, \"target\": r.target, \"type\": r.label, \"confidence\": r.confidence} for r in all_relationships]\n",+ "}]\n",+ "\n",+ "kg = graph_builder.build(kg_sources)\n",+ "\n",+ "entities_count = len(kg.get('entities', []))\n",+ "relationships_count = len(kg.get('relationships', []))\n",+ "print(f\"Graph: {entities_count} entities, {relationships_count} relationships\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Generating Embeddings for Protocols and Tokens\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.embeddings import EmbeddingGenerator\n",+ "\n",+ "embedding_gen = EmbeddingGenerator(\n",+ " provider=\"sentence_transformers\",\n",+ " model=EMBEDDING_MODEL\n",+ ")\n",+ "\n",+ "protocol_texts = [f\"{p.text} {getattr(p, 'description', '')}\" for p in protocols]\n",+ "protocol_embeddings = embedding_gen.generate_embeddings(protocol_texts)\n",+ "\n",+ "token_texts = [f\"{t.text} {getattr(t, 'description', '')}\" for t in tokens]\n",+ "token_embeddings = embedding_gen.generate_embeddings(token_texts)\n",+ "\n",+ "print(f\"Generated {len(protocol_embeddings)} protocol embeddings and {len(token_embeddings)} token embeddings\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Populating Vector Store\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.vector_store import VectorStore\n",+ "\n",+ "vector_store = VectorStore(backend=\"faiss\", dimension=EMBEDDING_DIMENSION)\n",+ "\n",+ "protocol_ids = vector_store.store_vectors(\n",+ " vectors=protocol_embeddings,\n",+ " metadata=[{\"type\": \"protocol\", \"name\": p.text, \"label\": p.label} for p in protocols]\n",+ ")\n",+ "\n",+ "token_ids = vector_store.store_vectors(\n",+ " vectors=token_embeddings,\n",+ " metadata=[{\"type\": \"token\", \"name\": t.text, \"label\": t.label} for t in tokens]\n",+ ")\n",+ "\n",+ "print(f\"Stored {len(protocol_ids)} protocol vectors and {len(token_ids)} token vectors\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Generating DeFi Ontology\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.ontology import OntologyGenerator\n",+ "\n",+ "ontology_gen = OntologyGenerator(base_uri=\"https://defi.example.org/ontology/\")\n",+ "ontology = ontology_gen.generate_from_graph(kg)\n",+ "\n",+ "print(f\"Generated DeFi ontology with {len(ontology.get('classes', []))} classes\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Reasoning and Risk Assessment\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.reasoning import Reasoner\n",+ "\n",+ "reasoner = Reasoner()\n",+ "\n",+ "reasoner.add_rule(\"IF Protocol has_risk Risk AND Risk severity high THEN Protocol risk_level critical\")\n",+ "reasoner.add_rule(\"IF Protocol depends_on Protocol AND Protocol has_risk Risk THEN Protocol inherits Risk\")\n",+ "\n",+ "inferred_facts = reasoner.infer_facts(kg)\n",+ "\n",+ "risk_paths = reasoner.find_paths(\n",+ " kg,\n",+ " source_type=\"Protocol\",\n",+ " target_type=\"Risk\",\n",+ " max_hops=2\n",+ ")\n",+ "\n",+ "print(f\"Inferred {len(inferred_facts)} facts\")\n",+ "print(f\"Found {len(risk_paths)} risk paths\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Storing Knowledge Graph (Optional)\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.graph_store import GraphStore\n",+ "\n",+ "# Optional: Store to persistent graph database\n",+ "# graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",+ "# graph_store.store_graph(kg)\n",+ "\n",+ "print(\"Graph store configured (commented out for demo)\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Storing Ontology as RDF Triplets (Optional)\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.triplet_store import TripletStore\n",+ "\n",+ "# Optional: Store ontology as RDF triplets\n",+ "# triplet_store = TripletStore(backend=\"blazegraph\", endpoint=\"http://localhost:9999/blazegraph\")\n",+ "# triplet_store.add_triplets_from_ontology(ontology)\n",+ "\n",+ "print(\"Triplet store configured (commented out for demo)\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## GraphRAG: Hybrid Vector + Graph Queries\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.context import AgentContext\n",+ "\n",+ "context = AgentContext(vector_store=vector_store, knowledge_graph=kg)\n",+ "\n",+ "query = \"What protocols have high risk?\"\n",+ "results = context.retrieve(\n",+ " query,\n",+ " max_results=10,\n",+ " use_graph=True,\n",+ " expand_graph=True,\n",+ " include_entities=True,\n",+ " include_relationships=True\n",+ ")\n",+ "\n",+ "print(f\"GraphRAG query: '{query}'\")\n",+ "print(f\"\\nRetrieved {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": [+ "## Visualizing the DeFi Knowledge Graph\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.visualization import KGVisualizer\n",+ "\n",+ "visualizer = KGVisualizer()\n",+ "visualizer.visualize(\n",+ " kg,\n",+ " output_path=\"defi_protocol_kg.html\",\n",+ " layout=\"spring\",\n",+ " node_size=20\n",+ ")\n",+ "\n",+ "print(\"Visualization saved to defi_protocol_kg.html\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Exporting Results\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.export import GraphExporter\n",+ "\n",+ "exporter = GraphExporter()\n",+ "exporter.export(kg, output_path=\"defi_protocol_kg.json\", format=\"json\")\n",+ "exporter.export(kg, output_path=\"defi_protocol_kg.graphml\", format=\"graphml\")\n",+ "exporter.export(ontology, output_path=\"defi_ontology.ttl\", format=\"rdf\")\n",+ "\n",+ "print(\"Exported knowledge graph to JSON and GraphML formats\")\n",+ "print(\"Exported ontology to RDF/TTL format\")\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.ipynbindex 7d79b7ea..1eb73ab0 100644--- a/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb+++ b/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb@@ -16,20 +16,74 @@"\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",+ "- **Temporal Analysis**: Time-aware queries and transaction evolution tracking\n","- **Whale Tracking**: Identifies large transaction movements\n","- **Flow Analysis**: Analyzes token flows through the network\n",+ "- **Comprehensive Data Sources**: Multiple blockchain APIs, analytics platforms, and databases\n","\n",- "### Pipeline Architecture\n",+ "### Learning Objectives\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",+ "- Ingest blockchain transaction data from multiple sources\n",+ "- Extract transaction entities (Transactions, Wallets, Addresses, Blocks, Flows)\n",+ "- Build temporal transaction network graphs\n",+ "- Perform graph analytics (centrality, communities, connectivity)\n",+ "- Detect patterns and whale movements\n",+ "- Analyze token flows and transaction paths\n",+ "- Store and query transaction data using vector stores and graph stores\n",+ "\n",+ "### Pipeline Flow\n",+ "\n",+ "```mermaid\n",+ "graph TD\n",+ " A[Data Ingestion] --> B[Document Parsing]\n",+ " B --> C[Text Processing]\n",+ " C --> D[Entity Extraction]\n",+ " D --> E[Relationship Extraction]\n",+ " E --> F[Deduplication]\n",+ " F --> G[Conflict Detection]\n",+ " G --> H[Transaction Network Graph]\n",+ " H --> I[Embeddings]\n",+ " I --> J[Vector Store]\n",+ " H --> K[Graph Analytics]\n",+ " K --> L[Temporal Queries]\n",+ " L --> M[Pattern Detection]\n",+ " M --> N[Flow Analysis]\n",+ " J --> O[GraphRAG Queries]\n",+ " H --> P[Graph Store]\n",+ " O --> Q[Visualization]\n",+ " P --> Q\n",+ " Q --> R[Export]\n",+ "```\n",+ "\n",+ "### Data Sources\n",+ "\n",+ "#### Blockchain APIs\n",+ "- **Etherscan API**: https://etherscan.io/apis\n",+ "- **Blockchain.com API**: https://www.blockchain.com/api\n",+ "- **BlockCypher API**: https://www.blockcypher.com/dev/\n",+ "- **BscScan API**: https://bscscan.com/apis\n",+ "- **PolygonScan API**: https://polygonscan.com/apis\n",+ "- **Arbiscan API**: https://arbiscan.io/apis\n",+ "\n",+ "#### Analytics Platforms\n",+ "- **Dune Analytics**: https://dune.com/\n",+ "- **Nansen**: https://www.nansen.ai/\n",+ "- **Glassnode**: https://glassnode.com/\n",+ "- **The Graph**: https://thegraph.com/\n",+ "- **Flipside Crypto**: https://flipsidecrypto.xyz/\n",+ "\n",+ "#### Stream Sources\n",+ "- **WebSocket Feeds**: Real-time transaction streams\n",+ "- **Alchemy Webhooks**: https://www.alchemy.com/\n",+ "- **Infura Webhooks**: https://www.infura.io/\n",+ "- **QuickNode Webhooks**: https://www.quicknode.com/\n",+ "\n",+ "#### Database Links\n",+ "- **Etherscan**: https://etherscan.io/\n",+ "- **BscScan**: https://bscscan.com/\n",+ "- **PolygonScan**: https://polygonscan.com/\n",+ "- **Arbiscan**: https://arbiscan.io/\n",+ "- **Optimistic Etherscan**: https://optimistic.etherscan.io/\n","\n","---\n","\n",@@ -42,16 +96,14 @@"metadata": {},"outputs": [],"source": [- "%pip install -qU semantica networkx matplotlib plotly pandas groq\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"+ "## Configuration & Setup\n"]},{@@ -61,31 +113,22 @@"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",+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key-here\")\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"+ "# Configuration constants\n",+ "EMBEDDING_DIMENSION = 384\n",+ "EMBEDDING_MODEL = \"all-MiniLM-L6-v2\"\n",+ "CHUNK_SIZE = 1000\n",+ "CHUNK_OVERLAP = 200\n",+ "TEMPORAL_GRANULARITY = \"day\"\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"+ "## Ingesting Blockchain Transaction Data\n"]},{@@ -94,46 +137,89 @@"metadata": {},"outputs": [],"source": [- "from semantica.ingest import WebIngestor, FileIngestor\n",+ "from semantica.ingest import WebIngestor, FileIngestor, FeedIngestor\n","import os\n",+ "from contextlib import redirect_stderr\n",+ "from io import StringIO\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",+ "# Example blockchain API endpoints (in production, use actual API keys)\n",+ "api_sources = [\n",+ " (\"Blockchain.com Stats\", \"https://api.blockchain.info/stats\"),\n",+ " # Add more API endpoints as needed\n",+ "]\n",+ "\n",+ "web_ingestor = WebIngestor()\n",+ "all_documents = []\n",+ "\n",+ "for api_name, api_url in api_sources:\n",+ " try:\n",+ " with redirect_stderr(StringIO()):\n",+ " api_documents = web_ingestor.ingest(api_url, method=\"url\")\n",+ " for doc in api_documents:\n",+ " if not hasattr(doc, 'metadata'):\n",+ " doc.metadata = {}\n",+ " doc.metadata['source'] = api_name\n",+ " all_documents.append(doc)\n",+ " except Exception:\n",+ " continue\n",+ "\n",+ "if not all_documents:\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",+ " Transaction 0x123 transfers 1000 ETH from wallet 0xABC to wallet 0xDEF at block 18500000.\n",+ " Transaction 0x456 transfers 500 BTC from wallet 0xGHI to wallet 0xJKL at block 18500001.\n",+ " Large transaction 0x789 moves 10000 ETH (whale movement) from wallet 0xMNO to wallet 0xPQR at block 18500002.\n",+ " Transaction 0xabc transfers 200 USDT from wallet 0xSTU to wallet 0xVWX at block 18500003.\n",+ " Transaction 0xdef transfers 5000 ETH from wallet 0xYZA to wallet 0xBCD at block 18500004.\n",+ " Transaction 0x111 transfers 3000 DAI from wallet 0xEFG to wallet 0xHIJ at block 18500005.\n",+ " Transaction 0x222 transfers 1500 USDC from wallet 0xKLM to wallet 0xNOP at block 18500006.\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"+ " file_ingestor = FileIngestor()\n",+ " all_documents = file_ingestor.ingest(\"data/transactions.txt\")\n",+ "\n",+ "documents = all_documents\n",+ "print(f\"Ingested {len(documents)} documents\")\n"]},{"cell_type": "markdown","metadata": {},"source": [- "---\n",+ "## Parsing Transaction Documents\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.parse import DocumentParser\n","\n",- "## Phase 2: Text Normalization & Deduplication\n",+ "parser = DocumentParser()\n","\n",- "Normalize addresses and detect duplicate transactions.\n"+ "parsed_documents = []\n",+ "for doc in documents:\n",+ " try:\n",+ " parsed = parser.parse(\n",+ " doc.content if hasattr(doc, 'content') else str(doc),\n",+ " content_type=\"text\"\n",+ " )\n",+ " parsed_documents.append(parsed)\n",+ " except Exception:\n",+ " parsed_documents.append(doc)\n",+ "\n",+ "documents = parsed_documents\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Normalizing and Chunking Transaction Data\n"]},{@@ -143,47 +229,86 @@"outputs": [],"source": ["from semantica.normalize import TextNormalizer\n",- "from semantica.deduplication import DuplicateDetector\n",+ "from semantica.split import TextSplitter\n","\n",- "# Normalize addresses and transaction data\n","normalizer = TextNormalizer()\n",+ "splitter = TextSplitter(\n",+ " method=\"entity_aware\",\n",+ " ner_method=\"spacy\",\n",+ " chunk_size=CHUNK_SIZE,\n",+ " chunk_overlap=CHUNK_OVERLAP\n",+ ")\n",+ "\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",+ " remove_extra_whitespace=True,\n",+ " lowercase=False\n"," )\n"," normalized_documents.append(normalized_text)\n","\n",- "print(f\"Normalized {len(normalized_documents)} documents\")\n",+ "chunked_documents = []\n",+ "for doc_text in normalized_documents:\n",+ " try:\n",+ " with redirect_stderr(StringIO()):\n",+ " chunks = splitter.split(doc_text)\n",+ " chunked_documents.extend(chunks)\n",+ " except Exception:\n",+ " simple_splitter = TextSplitter(method=\"recursive\", chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)\n",+ " chunks = simple_splitter.split(doc_text)\n",+ " chunked_documents.extend(chunks)\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Extracting Transaction Entities\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.semantic_extract import NERExtractor\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",+ "entity_extractor = NERExtractor(\n",+ " method=\"llm\",\n",+ " provider=\"groq\",\n",+ " llm_model=\"llama-3.1-8b-instant\",\n",+ " temperature=0.0\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",+ "all_entities = []\n",+ "for chunk in chunked_documents:\n",+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",+ " try:\n",+ " entities = entity_extractor.extract_entities(\n",+ " chunk_text,\n",+ " entity_types=[\"Transaction\", \"Wallet\", \"Address\", \"Block\", \"Flow\"]\n",+ " )\n",+ " all_entities.extend(entities)\n",+ " except Exception:\n",+ " continue\n","\n",- "detector = DuplicateDetector()\n",- "duplicates = detector.detect_duplicates(transactions, threshold=0.9)\n",- "deduplicated_transactions = detector.resolve_duplicates(transactions, duplicates)\n",+ "transactions = [e for e in all_entities if e.label == \"Transaction\" or \"transaction\" in e.label.lower()]\n",+ "wallets = [e for e in all_entities if e.label in [\"Wallet\", \"Address\"] or \"wallet\" in e.label.lower() or \"address\" in e.label.lower()]\n",+ "blocks = [e for e in all_entities if e.label == \"Block\" or \"block\" in e.label.lower()]\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"+ "print(f\"Extracted {len(transactions)} transactions, {len(wallets)} wallets/addresses, {len(blocks)} blocks\")\n"]},{"cell_type": "markdown","metadata": {},- "source": []+ "source": [+ "## Extracting Transaction Relationships\n"+ ]},{"cell_type": "code",@@ -191,35 +316,392 @@"metadata": {},"outputs": [],"source": [- "# Perform network analytics\n",- "analytics = GraphAnalytics(kg)\n",- "centrality = analytics.calculate_centrality(method=\"degree\")\n",- "communities = analytics.detect_communities()\n",+ "from semantica.semantic_extract import RelationExtractor\n",+ "\n",+ "relation_extractor = RelationExtractor(\n",+ " method=\"llm\",\n",+ " provider=\"groq\",\n",+ " llm_model=\"llama-3.1-8b-instant\",\n",+ " temperature=0.0\n",+ ")\n","\n",+ "all_relationships = []\n",+ "for chunk in chunked_documents:\n",+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",+ " try:\n",+ " relationships = relation_extractor.extract_relations(\n",+ " chunk_text,\n",+ " entities=all_entities,\n",+ " relation_types=[\"transfers\", \"from\", \"to\", \"in_block\", \"contains\", \"flows_to\"]\n",+ " )\n",+ " all_relationships.extend(relationships)\n",+ " except Exception:\n",+ " continue\n",+ "\n",+ "print(f\"Extracted {len(all_relationships)} relationships\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Resolving Duplicate Transactions\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.deduplication import DuplicateDetector\n",+ "\n",+ "duplicate_detector = DuplicateDetector(\n",+ " similarity_threshold=0.85,\n",+ " method=\"semantic\"\n",+ ")\n",+ "\n",+ "deduplicated_entities = duplicate_detector.detect_duplicates(all_entities)\n",+ "merged_entities = duplicate_detector.merge_duplicates(deduplicated_entities)\n",+ "\n",+ "print(f\"Deduplicated {len(all_entities)} entities to {len(merged_entities)} unique entities\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Detecting Transaction Conflicts\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.conflicts import ConflictDetector\n",+ "\n",+ "conflict_detector = ConflictDetector()\n",+ "\n",+ "conflicts = conflict_detector.detect_conflicts(merged_entities, all_relationships)\n",+ "\n",+ "if conflicts:\n",+ " resolved = conflict_detector.resolve_conflicts(conflicts, strategy=\"highest_confidence\")\n",+ " print(f\"Detected {len(conflicts)} conflicts, resolved {len(resolved)}\")\n",+ "else:\n",+ " print(\"No conflicts detected\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Building Temporal Transaction Network Graph\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.kg import GraphBuilder\n",+ "\n",+ "graph_builder = GraphBuilder(\n",+ " merge_entities=True,\n",+ " resolve_conflicts=True,\n",+ " entity_resolution_strategy=\"fuzzy\",\n",+ " enable_temporal=True,\n",+ " temporal_granularity=TEMPORAL_GRANULARITY\n",+ ")\n",+ "\n",+ "kg_sources = [{\n",+ " \"entities\": [{\"text\": e.text, \"type\": e.label, \"confidence\": e.confidence} for e in merged_entities],\n",+ " \"relationships\": [{\"source\": r.source, \"target\": r.target, \"type\": r.label, \"confidence\": r.confidence} for r in all_relationships]\n",+ "}]\n",+ "\n",+ "kg = graph_builder.build(kg_sources)\n",+ "\n",+ "entities_count = len(kg.get('entities', []))\n",+ "relationships_count = len(kg.get('relationships', []))\n",+ "print(f\"Graph: {entities_count} entities, {relationships_count} relationships\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Generating Embeddings for Transactions and Wallets\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.embeddings import EmbeddingGenerator\n",+ "\n",+ "embedding_gen = EmbeddingGenerator(\n",+ " provider=\"sentence_transformers\",\n",+ " model=EMBEDDING_MODEL\n",+ ")\n",+ "\n",+ "transaction_texts = [f\"{t.text} {getattr(t, 'description', '')}\" for t in transactions]\n",+ "transaction_embeddings = embedding_gen.generate_embeddings(transaction_texts)\n",+ "\n",+ "wallet_texts = [f\"{w.text} {getattr(w, 'description', '')}\" for w in wallets]\n",+ "wallet_embeddings = embedding_gen.generate_embeddings(wallet_texts)\n",+ "\n",+ "print(f\"Generated {len(transaction_embeddings)} transaction embeddings and {len(wallet_embeddings)} wallet embeddings\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Populating Vector Store\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.vector_store import VectorStore\n",+ "\n",+ "vector_store = VectorStore(backend=\"faiss\", dimension=EMBEDDING_DIMENSION)\n",+ "\n",+ "transaction_ids = vector_store.store_vectors(\n",+ " vectors=transaction_embeddings,\n",+ " metadata=[{\"type\": \"transaction\", \"name\": t.text, \"label\": t.label} for t in transactions]\n",+ ")\n",+ "\n",+ "wallet_ids = vector_store.store_vectors(\n",+ " vectors=wallet_embeddings,\n",+ " metadata=[{\"type\": \"wallet\", \"name\": w.text, \"label\": w.label} for w in wallets]\n",+ ")\n",+ "\n",+ "print(f\"Stored {len(transaction_ids)} transaction vectors and {len(wallet_ids)} wallet vectors\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Analyzing Graph Structure\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.kg import GraphAnalyzer, CentralityCalculator, CommunityDetector\n",+ "\n",+ "graph_analyzer = GraphAnalyzer()\n",+ "centrality_calc = CentralityCalculator()\n",+ "community_detector = CommunityDetector()\n",+ "\n",+ "analysis = graph_analyzer.analyze_graph(kg)\n",+ "\n",+ "degree_centrality = centrality_calc.calculate_degree_centrality(kg)\n",+ "betweenness_centrality = centrality_calc.calculate_betweenness_centrality(kg)\n",+ "closeness_centrality = centrality_calc.calculate_closeness_centrality(kg)\n",+ "\n",+ "communities = community_detector.detect_communities(kg, method=\"louvain\")\n",+ "connectivity = graph_analyzer.analyze_connectivity(kg)\n",+ "\n",+ "print(f\"Graph analytics:\")\n",+ "print(f\" - Communities: {len(communities)}\")\n",+ "print(f\" - Connected components: {len(connectivity.get('components', []))}\")\n",+ "print(f\" - Graph density: {analysis.get('density', 0):.3f}\")\n",+ "print(f\" - Central nodes (degree): {len(degree_centrality)}\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Temporal Graph Queries\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.kg import TemporalGraphQuery\n",+ "\n",+ "temporal_query = TemporalGraphQuery(\n",+ " enable_temporal_reasoning=True,\n",+ " temporal_granularity=TEMPORAL_GRANULARITY\n",+ ")\n",+ "\n",+ "query_results = temporal_query.query_at_time(\n",+ " kg,\n",+ " query={\"type\": \"Transaction\"},\n",+ " at_time=\"2024-01-01\"\n",+ ")\n",+ "\n",+ "evolution = temporal_query.analyze_evolution(kg)\n",+ "temporal_patterns = temporal_query.detect_temporal_patterns(kg, pattern_type=\"sequence\")\n",+ "\n",+ "print(f\"Temporal queries: {len(query_results)} transactions at query time\")\n",+ "print(f\"Temporal patterns detected: {len(temporal_patterns)}\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Detecting Patterns and Whale Movements\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": ["# 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",+ "whale_wallets = []\n",+ "for entity in kg.get(\"entities\", []):\n",+ " if entity.get(\"type\") in [\"Wallet\", \"Address\"]:\n",+ " # Check for large transaction relationships\n",+ " related_rels = [r for r in kg.get(\"relationships\", []) \n",+ " if r.get(\"source\") == entity.get(\"id\") or r.get(\"target\") == entity.get(\"id\")]\n",+ " if any(\"large\" in str(r.get(\"type\", \"\")).lower() or \"whale\" in str(r.get(\"type\", \"\")).lower() \n",+ " for r in related_rels):\n",+ " whale_wallets.append(entity)\n",+ "\n",+ "# Detect suspicious patterns (high frequency transactions)\n",+ "suspicious_patterns = []\n",+ "for wallet in wallets[:10]:\n",+ " wallet_name = wallet.text\n",+ " paths = graph_analyzer.find_paths(\n",+ " kg,\n",+ " source=wallet_name,\n",+ " target_type=\"Transaction\",\n",+ " max_hops=1\n",+ " )\n",+ " if len(paths) > 5: # High transaction frequency\n",+ " suspicious_patterns.append({\n",+ " 'wallet': wallet_name,\n",+ " 'transaction_count': len(paths)\n",+ " })\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"+ "print(f\"Suspicious patterns: {len(suspicious_patterns)} high-frequency wallets\")\n"]},{"cell_type": "markdown","metadata": {},"source": [- "---\n",+ "## Analyzing Token Flows\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Analyze token flows through the network\n",+ "flow_analysis = []\n",+ "for transaction in transactions[:10]:\n",+ " tx_name = transaction.text\n",+ " paths = graph_analyzer.find_paths(\n",+ " kg,\n",+ " source=tx_name,\n",+ " target_type=\"Wallet\",\n",+ " max_hops=2\n",+ " )\n",+ " for path in paths:\n",+ " if path.get('target_type') in ['Wallet', 'Address']:\n",+ " flow_analysis.append({\n",+ " 'transaction': tx_name,\n",+ " 'flow_path': path.get('path', []),\n",+ " 'target': path.get('target'),\n",+ " 'path_length': len(path.get('path', []))\n",+ " })\n",+ "\n",+ "flow_analysis.sort(key=lambda x: x['path_length'])\n",+ "\n",+ "print(f\"Flow analysis: {len(flow_analysis)} token flow paths identified\")\n",+ "for i, flow in enumerate(flow_analysis[:5], 1):\n",+ " print(f\"{i}. {flow['transaction']} -> {flow['target']} (path length: {flow['path_length']})\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Storing Transaction Network (Optional)\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.graph_store import GraphStore\n",+ "\n",+ "# Optional: Store to persistent graph database\n",+ "# graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",+ "# graph_store.store_graph(kg)\n",+ "\n",+ "print(\"Graph store configured (commented out for demo)\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## GraphRAG: Hybrid Vector + Graph Queries\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.context import AgentContext\n",+ "\n",+ "context = AgentContext(vector_store=vector_store, knowledge_graph=kg)\n","\n",- "## Phase 6-7: Visualization & Export\n"+ "query = \"What are the largest transactions?\"\n",+ "results = context.retrieve(\n",+ " query,\n",+ " max_results=10,\n",+ " use_graph=True,\n",+ " expand_graph=True,\n",+ " include_entities=True,\n",+ " include_relationships=True\n",+ ")\n",+ "\n",+ "print(f\"GraphRAG query: '{query}'\")\n",+ "print(f\"\\nRetrieved {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": [+ "## Visualizing the Transaction Network\n"]},{@@ -231,10 +713,37 @@"from semantica.visualization import KGVisualizer\n","\n","visualizer = KGVisualizer()\n",- "visualizer.visualize(kg, output_path=\"transaction_network.html\", layout=\"force-directed\")\n",+ "visualizer.visualize(\n",+ " kg,\n",+ " output_path=\"transaction_network.html\",\n",+ " layout=\"hierarchical\",\n",+ " node_size=20\n",+ ")\n",+ "\n",+ "print(\"Visualization saved to transaction_network.html\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Exporting Results\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.export import GraphExporter\n",+ "\n",+ "exporter = GraphExporter()\n",+ "exporter.export(kg, output_path=\"transaction_network.json\", format=\"json\")\n",+ "exporter.export(kg, output_path=\"transaction_network.graphml\", format=\"graphml\")\n",+ "exporter.export(kg, output_path=\"transaction_network.csv\", format=\"csv\")\n","\n",- "print(\"Transaction network analysis complete\")\n",- "print(\"Emphasizes: Graph analytics, pattern detection, network analysis\")\n"+ "print(\"Exported transaction network to JSON, GraphML, and CSV formats\")\n"]}],