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
Add progress tracking and ETA to GraphBuilder
KaifAhmad1f53935e0a1b2
diff --git a/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb b/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynbindex 31dcce0d..33731d7b 100644--- a/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb+++ b/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb@@ -60,9 +60,32 @@},{"cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],+ "execution_count": 1,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Note: you may need to restart the kernel to use updated packages.\n"+ ]+ },+ {+ "name": "stderr",+ "output_type": "stream",+ "text": [+ "WARNING: Ignoring invalid distribution ~gno (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~lotly (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~ython-socketio (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~gno (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~lotly (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~ython-socketio (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~gno (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~lotly (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~ython-socketio (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n"+ ]+ }+ ],"source": ["%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq sentence-transformers scikit-learn\n"]@@ -76,13 +99,13 @@},{"cell_type": "code",- "execution_count": null,+ "execution_count": 2,"metadata": {},"outputs": [],"source": ["import os\n","\n",- "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key-here\")\n",+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"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\")\n","\n","# Configuration constants\n","EMBEDDING_DIMENSION = 384\n",@@ -101,9 +124,54 @@},{"cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],+ "execution_count": 3,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Ingesting from 8 RSS feed sources...\n"+ ]+ },+ {+ "data": {+ "text/html": [+ "<div style='font-family: monospace;'><h4>π§ Semantica - π Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>β</td><td>Semantica is parsing</td><td>π parse</td><td>DocumentParser</td><td>p>\n",+ "</td><td>0.00s</td></tr><tr><td>β</td><td>Semantica is parsing</td><td>π parse</td><td>DocumentParser</td><td>p>\n",+ "</td><td>0.00s</td></tr><tr><td>β</td><td>Semantica is parsing</td><td>π parse</td><td>DocumentParser</td><td>p>\n",+ "</td><td>0.00s</td></tr><tr><td>β</td><td>Semantica is parsing</td><td>π parse</td><td>DocumentParser</td><td>p>\n",+ "</td><td>0.00s</td></tr><tr><td>β</td><td>Semantica is parsing</td><td>π parse</td><td>DocumentParser</td><td>p>\n",+ "</td><td>0.02s</td></tr><tr><td>β </td><td>Semantica is normalizing</td><td>π§ normalize</td><td>TextNormalizer</td><td>-</td><td>0.00s</td></tr><tr><td>π</td><td>Semantica is extracting</td><td>π― semantic_extract</td><td>NERExtractor</td><td>-</td><td>0.00s</td></tr><tr><td>β </td><td>Semantica is extracting</td><td>π― semantic_extract</td><td>RelationExtractor</td><td>-</td><td>0.57s</td></tr><tr><td>β </td><td>Semantica is resolving</td><td>β οΈ conflicts</td><td>ConflictDetector</td><td>-</td><td>0.01s</td></tr><tr><td>π</td><td>Semantica is building</td><td>π§ kg</td><td>GraphBuilder</td><td>-</td><td>630.57s</td></tr></table></div>"+ ],+ "text/plain": [+ "<IPython.core.display.HTML object>"+ ]+ },+ "metadata": {},+ "output_type": "display_data"+ },+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ " [1/8] CoinDesk: 25 documents\n",+ " [2/8] CoinTelegraph: 30 documents\n",+ " [3/8] Decrypt: 51 documents\n",+ " [4/8] The Block: 19 documents\n",+ " [5/8] CryptoSlate: 10 documents\n",+ " [6/8] CryptoNews: 20 documents\n",+ "\n",+ "Ingesting from 3 web sources...\n",+ " Warning: Blockchain.com Stats failed: 'WebIngestor' object has no attribute 'ingest'\n",+ " Warning: Etherscan failed: 'WebIngestor' object has no attribute 'ingest'\n",+ "\n",+ "β Total ingested: 155 documents\n",+ " Sources: 6 unique sources\n",+ " Source list: CoinDesk, CoinTelegraph, CryptoNews, CryptoSlate, Decrypt, The Block\n"+ ]+ }+ ],"source": ["from semantica.ingest import WebIngestor, FileIngestor, FeedIngestor\n","import os\n",@@ -112,35 +180,82 @@"\n","os.makedirs(\"data\", exist_ok=True)\n","\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",+ "# Blockchain and crypto news RSS feeds\n",+ "feed_sources = [\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",+ " (\"Bitcoin Magazine\", \"https://bitcoinmagazine.com/.rss/full/\"),\n",+ " (\"Ethereum News\", \"https://ethereum.org/en/feed.xml\"),\n","]\n","\n",+ "# Blockchain data and analytics web sources\n",+ "web_sources = [\n",+ " (\"Blockchain.com Stats\", \"https://www.blockchain.com/explorer\"),\n",+ " (\"Etherscan\", \"https://etherscan.io/\"),\n",+ " (\"Bitcoin Explorer\", \"https://blockstream.info/\"),\n",+ "]\n",+ "\n",+ "# Initialize ingestors\n",+ "feed_ingestor = FeedIngestor()\n","web_ingestor = WebIngestor()\n","all_documents = []\n","\n",- "print(f\"Ingesting from {len(api_sources)} API sources...\")\n",- "for i, (api_name, api_url) in enumerate(api_sources, 1):\n",+ "# Ingest from RSS feeds\n",+ "print(f\"Ingesting from {len(feed_sources)} RSS feed sources...\")\n",+ "for i, (feed_name, feed_url) in enumerate(feed_sources, 1):\n",+ " try:\n",+ " with redirect_stderr(StringIO()):\n",+ " feed_data = feed_ingestor.ingest_feed(feed_url, validate=False)\n",+ " \n",+ " feed_count = 0\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",+ " item.metadata['type'] = 'feed'\n",+ " all_documents.append(item)\n",+ " feed_count += 1\n",+ " \n",+ " if feed_count > 0:\n",+ " print(f\" [{i}/{len(feed_sources)}] {feed_name}: {feed_count} documents\")\n",+ " except Exception as e:\n",+ " if i <= 3: # Show first few errors\n",+ " print(f\" Warning: {feed_name} failed: {str(e)[:50]}\")\n",+ " continue\n",+ "\n",+ "# Ingest from web sources (transaction-related pages)\n",+ "print(f\"\\nIngesting from {len(web_sources)} web sources...\")\n",+ "for i, (web_name, web_url) in enumerate(web_sources, 1):\n"," try:\n"," with redirect_stderr(StringIO()):\n",- " api_documents = web_ingestor.ingest(api_url, method=\"url\")\n",+ " web_documents = web_ingestor.ingest(web_url, method=\"url\")\n"," \n",- " api_count = 0\n",- " for doc in api_documents:\n",+ " web_count = 0\n",+ " for doc in web_documents:\n"," if not hasattr(doc, 'metadata'):\n"," doc.metadata = {}\n",- " doc.metadata['source'] = api_name\n",+ " doc.metadata['source'] = web_name\n",+ " doc.metadata['type'] = 'web'\n"," all_documents.append(doc)\n",- " api_count += 1\n",+ " web_count += 1\n"," \n",- " if api_count > 0:\n",- " print(f\" [{i}/{len(api_sources)}] {api_name}: {api_count} documents\")\n",- " except Exception:\n",+ " if web_count > 0:\n",+ " print(f\" [{i}/{len(web_sources)}] {web_name}: {web_count} documents\")\n",+ " except Exception as e:\n",+ " if i <= 2: # Show first few errors\n",+ " print(f\" Warning: {web_name} failed: {str(e)[:50]}\")\n"," continue\n","\n",+ "# Fallback to sample transaction data if no documents ingested\n","if not all_documents:\n",+ " print(\"\\nβ οΈ No documents ingested from feeds/web sources. Using sample transaction data...\")\n"," tx_data = \"\"\"\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",@@ -149,14 +264,36 @@" 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",+ " Transaction 0x333 transfers 2500 LINK from wallet 0xQRS to wallet 0xTUV at block 18500007.\n",+ " Transaction 0x444 transfers 8000 MATIC from wallet 0xWXY to wallet 0xZAB at block 18500008.\n",+ " Transaction 0x555 transfers 12000 UNI from wallet 0xCDE to wallet 0xFGH at block 18500009.\n"," \"\"\"\n"," with open(\"data/transactions.txt\", \"w\") as f:\n"," f.write(tx_data)\n"," file_ingestor = FileIngestor()\n"," all_documents = file_ingestor.ingest(\"data/transactions.txt\")\n",+ " for doc in all_documents:\n",+ " if not hasattr(doc, 'metadata'):\n",+ " doc.metadata = {}\n",+ " doc.metadata['source'] = 'Sample Data'\n",+ " doc.metadata['type'] = 'sample'\n","\n","documents = all_documents\n",- "print(f\"Ingested {len(documents)} documents\")\n"+ "\n",+ "# Count unique sources properly handling different document types\n",+ "unique_sources = set()\n",+ "for d in documents:\n",+ " if hasattr(d, 'metadata') and d.metadata:\n",+ " source = d.metadata.get('source', 'Unknown')\n",+ " unique_sources.add(source)\n",+ " elif isinstance(d, dict) and 'metadata' in d:\n",+ " source = d['metadata'].get('source', 'Unknown')\n",+ " unique_sources.add(source)\n",+ "\n",+ "print(f\"\\nβ Total ingested: {len(documents)} documents\")\n",+ "print(f\" Sources: {len(unique_sources)} unique sources\")\n",+ "if unique_sources:\n",+ " print(f\" Source list: {', '.join(sorted(unique_sources))}\")\n"]},{@@ -168,9 +305,21 @@},{"cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],+ "execution_count": 4,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Parsing 155 documents...\n",+ " Parsed 50/155 documents...\n",+ " Parsed 100/155 documents...\n",+ " Parsed 150/155 documents...\n",+ " Parsed 155/155 documents...\n"+ ]+ }+ ],"source": ["from semantica.parse import DocumentParser\n","\n",@@ -202,9 +351,27 @@},{"cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],+ "execution_count": 5,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Normalizing 155 documents...\n",+ " Normalized 50/155 documents...\n",+ " Normalized 100/155 documents...\n",+ " Normalized 150/155 documents...\n",+ " Normalized 155/155 documents...\n",+ "Chunking 155 documents...\n",+ " Chunked 50/155 documents (50 chunks so far)\n",+ " Chunked 100/155 documents (101 chunks so far)\n",+ " Chunked 150/155 documents (151 chunks so far)\n",+ " Chunked 155/155 documents (156 chunks so far)\n",+ "Created 156 chunks from 155 documents\n"+ ]+ }+ ],"source": ["from semantica.normalize import TextNormalizer\n","from semantica.split import TextSplitter\n",@@ -257,40 +424,72 @@},{"cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],+ "execution_count": 6,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Extracting entities from 156 chunks using ML (spaCy)...\n",+ "\n",+ "β Extraction complete!\n",+ " Total entities: 2420\n",+ " Standard labels: ['CARDINAL', 'GPE', 'ORG', 'PERSON', 'FAC', 'MONEY', 'DATE', 'NORP', 'LOC', 'ORDINAL', 'PRODUCT', 'LAW', 'PERCENT', 'WORK_OF_ART', 'EVENT', 'TIME']\n",+ " Transactions (filtered): 149\n",+ " Wallets/Addresses (filtered): 10\n",+ " Blocks (filtered): 398\n"+ ]+ }+ ],"source": ["from semantica.semantic_extract import NERExtractor\n","\n",+ "# Initialize NERExtractor with ML method only (spaCy)\n",+ "# Note: ML method extracts standard NER labels (PERSON, ORG, GPE, MONEY, etc.)\n","entity_extractor = NERExtractor(\n",- " method=\"llm\",\n",- " provider=\"groq\",\n",- " llm_model=\"llama-3.1-8b-instant\",\n",- " temperature=0.0\n",+ " method=[\"ml\"],\n",+ " min_confidence=0.5\n",")\n","\n",- "all_entities = []\n",- "print(f\"Extracting entities from {len(chunked_documents)} chunks...\")\n",- "for i, chunk in enumerate(chunked_documents, 1):\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",- " if i % 20 == 0 or i == len(chunked_documents):\n",- " print(f\" Processed {i}/{len(chunked_documents)} chunks ({len(all_entities)} entities found)\")\n",+ "# Extract all entities using Semantica's extract() method - handles batch processing\n",+ "print(f\"Extracting entities from {len(chunked_documents)} chunks using ML (spaCy)...\")\n",+ "batch_results = entity_extractor.extract(chunked_documents)\n",+ "\n",+ "# Flatten results (extract() returns List[List[Entity]] for batch input)\n",+ "all_entities = [entity for entity_list in batch_results for entity in entity_list]\n",+ "\n",+ "# Use Semantica's classify_entities to group by standard labels\n",+ "classified = entity_extractor.classify_entities(all_entities)\n","\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",+ "# Filter entities for blockchain transaction domain\n",+ "# Look for transaction hashes, wallet addresses, block numbers, and crypto tokens\n",+ "transaction_keywords = [\"transaction\", \"tx\", \"0x\", \"transfer\", \"sent\", \"received\"]\n",+ "wallet_keywords = [\"wallet\", \"address\", \"0x\", \"account\"]\n",+ "block_keywords = [\"block\", \"blockchain\", \"height\", \"block number\"]\n","\n",- "print(f\"Extracted {len(transactions)} transactions, {len(wallets)} wallets/addresses, {len(blocks)} blocks\")\n"+ "transactions = [\n",+ " e for e in all_entities \n",+ " if any(kw in e.text.lower() for kw in transaction_keywords) \n",+ " or e.label == \"MONEY\" # Money entities often represent transactions\n",+ "]\n",+ "wallets = [\n",+ " e for e in all_entities \n",+ " if any(kw in e.text.lower() for kw in wallet_keywords)\n",+ " or (len(e.text) >= 26 and e.text.startswith(\"0x\")) # Ethereum addresses\n",+ "]\n",+ "blocks = [\n",+ " e for e in all_entities \n",+ " if any(kw in e.text.lower() for kw in block_keywords)\n",+ " or e.label == \"CARDINAL\" # Block numbers are often cardinal numbers\n",+ "]\n",+ "\n",+ "print(f\"\\nβ Extraction complete!\")\n",+ "print(f\" Total entities: {len(all_entities)}\")\n",+ "print(f\" Standard labels: {list(classified.keys())}\")\n",+ "print(f\" Transactions (filtered): {len(transactions)}\")\n",+ "print(f\" Wallets/Addresses (filtered): {len(wallets)}\")\n",+ "print(f\" Blocks (filtered): {len(blocks)}\")\n"]},{@@ -302,99 +501,121 @@},{"cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],+ "execution_count": 7,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Extracting relationships from 156 chunks using ML (dependency parsing)...\n",+ " Processed 20/156 chunks (36 relationships found)\n",+ " Processed 40/156 chunks (102 relationships found)\n",+ " Processed 60/156 chunks (169 relationships found)\n",+ " Processed 80/156 chunks (215 relationships found)\n",+ " Processed 100/156 chunks (361 relationships found)\n",+ " Processed 120/156 chunks (436 relationships found)\n",+ " Processed 140/156 chunks (570 relationships found)\n",+ " Processed 156/156 chunks (648 relationships found)\n",+ "\n",+ "β Extracted 648 relationships\n"+ ]+ }+ ],"source": ["from semantica.semantic_extract import RelationExtractor\n","\n",+ "# Use ML-based dependency parsing to avoid rate limits\n","relation_extractor = RelationExtractor(\n",- " method=\"llm\",\n",- " provider=\"groq\",\n",- " llm_model=\"llama-3.1-8b-instant\",\n",- " temperature=0.0\n",+ " method=\"dependency\", # ML/NLP method - no API calls needed\n",+ " verbose=True\n",")\n","\n","all_relationships = []\n",- "print(f\"Extracting relationships from {len(chunked_documents)} chunks...\")\n",+ "error_count = 0\n",+ "print(f\"Extracting relationships from {len(chunked_documents)} chunks using ML (dependency parsing)...\")\n",+ "\n","for i, chunk in enumerate(chunked_documents, 1):\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",+ " relation_types=[\"transfers\", \"from\", \"to\", \"in_block\", \"contains\", \"flows_to\"],\n",+ " verbose=True\n"," )\n"," all_relationships.extend(relationships)\n",- " except Exception:\n",- " continue\n",+ " except Exception as e:\n",+ " error_count += 1\n",+ " if error_count <= 3:\n",+ " print(f\" Warning: Error on chunk {i}: {str(e)[:100]}\")\n"," \n"," if i % 20 == 0 or i == len(chunked_documents):\n"," print(f\" Processed {i}/{len(chunked_documents)} chunks ({len(all_relationships)} relationships found)\")\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.kg import EntityResolver\n",- "from semantica.semantic_extract import Entity\n",- "\n",- "# Convert Entity objects to dictionaries for EntityResolver\n",- "print(f\"Converting {len(all_entities)} entities to dictionaries...\")\n",- "entity_dicts = [{\"name\": e.text, \"type\": e.label, \"confidence\": e.confidence} for e in all_entities]\n",- "\n",- "# Use EntityResolver class to resolve duplicates\n",- "entity_resolver = EntityResolver(strategy=\"fuzzy\", similarity_threshold=0.85)\n",- "\n",- "print(f\"Resolving duplicates in {len(entity_dicts)} entities...\")\n",- "resolved_entities = entity_resolver.resolve_entities(entity_dicts)\n",+ "if error_count > 0:\n",+ " print(f\" Note: {error_count} chunks had errors during relation extraction\")\n","\n",- "# Convert back to Entity objects\n",- "print(f\"Converting {len(resolved_entities)} resolved entities back to Entity objects...\")\n",- "merged_entities = [\n",- " Entity(text=e[\"name\"], label=e[\"type\"], confidence=e.get(\"confidence\", 1.0))\n",- " for e in resolved_entities\n",- "]\n",- "\n",- "print(f\"Deduplicated {len(entity_dicts)} entities to {len(merged_entities)} unique entities\")\n"+ "print(f\"\\nβ Extracted {len(all_relationships)} relationships\")\n"]},{"cell_type": "markdown","metadata": {},"source": [- "## Detecting Transaction Conflicts\n"+ "## Detecting Transaction Conflicts\n",+ "\n",+ "- **Multi-Type Detection**: Detects entity, relationship, and temporal conflicts across transaction network\n",+ "- **Most Recent Strategy**: Uses `most_recent` resolution for transaction data (most accurate for blockchain)\n",+ "- **Source-Aware Resolution**: Considers source reliability and confidence scores for conflict resolution\n"]},{"cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.conflicts import ConflictDetector\n",- "\n",+ "execution_count": 8,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Detecting conflicts in 2420 entities and 648 relationships...\n",+ "Detected 0 total conflicts\n",+ "β No conflicts detected - data is consistent\n"+ ]+ }+ ],+ "source": [+ "from semantica.conflicts import ConflictDetector, ConflictResolver\n",+ "\n",+ "# Initialize conflict detection and resolution\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",+ "conflict_resolver = ConflictResolver()\n",+ "\n",+ "# Use Semantica's conflict detection methods directly\n",+ "# Detects entity, relationship, and temporal conflicts\n",+ "print(f\"Detecting conflicts in {len(all_entities)} entities and {len(all_relationships)} relationships...\")\n",+ "\n",+ "# Convert to dict format for conflict detection (Semantica expects dicts)\n",+ "entity_dicts = [{\"id\": e.text, \"text\": e.text, \"type\": e.label, \"confidence\": getattr(e, 'confidence', 1.0)} for e in all_entities]\n",+ "relationship_dicts = [{\"id\": f\"{r.subject.text}_{r.predicate}_{r.object.text}\", \"source_id\": r.subject.text, \"target_id\": r.object.text, \"type\": r.predicate} for r in all_relationships]\n",+ "\n",+ "# Detect all conflict types using Semantica's methods\n",+ "all_conflicts = []\n",+ "all_conflicts.extend(conflict_detector.detect_entity_conflicts(entity_dicts))\n",+ "all_conflicts.extend(conflict_detector.detect_relationship_conflicts(relationship_dicts))\n",+ "all_conflicts.extend(conflict_detector.detect_temporal_conflicts(entity_dicts))\n",+ "\n",+ "print(f\"Detected {len(all_conflicts)} total conflicts\")\n",+ "\n",+ "# Resolve conflicts using best strategy for transaction networks\n",+ "if all_conflicts:\n",+ " print(f\"Resolving conflicts using 'most_recent' strategy (best for transaction data)...\")\n",+ " resolved = conflict_resolver.resolve_conflicts(all_conflicts, strategy=\"most_recent\")\n",+ " resolved_count = len([r for r in resolved if r.resolved])\n",+ " print(f\"β Resolved {resolved_count}/{len(all_conflicts)} conflicts\")\n","else:\n",- " print(\"No conflicts detected\")\n"+ " print(\"β No conflicts detected - data is consistent\")\n"]},{@@ -408,29 +629,36 @@"cell_type": "code","execution_count": null,"metadata": {},- "outputs": [],+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Building temporal transaction network graph...\n"+ ]+ }+ ],"source": ["from semantica.kg import GraphBuilder\n","\n",+ "# Conflicts already resolved - disable expensive operations\n","graph_builder = GraphBuilder(\n",- " merge_entities=True,\n",- " resolve_conflicts=True,\n",- " entity_resolution_strategy=\"fuzzy\",\n",+ " merge_entities=False, # Skip entity merging (already done in conflict resolution)\n",+ " resolve_conflicts=False, # Conflicts already resolved\n",+ " entity_resolution_strategy=\"exact\", \n"," enable_temporal=True,\n",- " temporal_granularity=TEMPORAL_GRANULARITY\n",+ " temporal_granularity=TEMPORAL_GRANULARITY,\n",+ " track_history=True, \n",+ " version_snapshots=True \n",")\n","\n",- "print(f\"Building knowledge graph...\")\n",+ "# Build graph - Semantica's build() method automatically shows progress and ETA\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",+ " \"entities\": [{\"text\": e.text, \"type\": e.label, \"confidence\": getattr(e, 'confidence', 1.0)} for e in all_entities],\n",+ " \"relationships\": [{\"source\": r.subject.text, \"target\": r.object.text, \"type\": r.predicate, \"confidence\": getattr(r, 'confidence', 1.0)} 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"+ "kg = graph_builder.build(kg_sources)\n"]},{@@ -755,8 +983,22 @@}],"metadata": {+ "kernelspec": {+ "display_name": "Python 3",+ "language": "python",+ "name": "python3"+ },"language_info": {- "name": "python"+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3",+ "version": "3.11.9"}},"nbformat": 4,diff --git a/cookbook/use_cases/blockchain/data/transactions.txt b/cookbook/use_cases/blockchain/data/transactions.txtnew file mode 100644index 00000000..12e746e3--- /dev/null+++ b/cookbook/use_cases/blockchain/data/transactions.txt@@ -0,0 +1,9 @@++ Transaction 0x123 transfers 1000 ETH from wallet 0xABC to wallet 0xDEF at block 18500000.+ Transaction 0x456 transfers 500 BTC from wallet 0xGHI to wallet 0xJKL at block 18500001.+ Large transaction 0x789 moves 10000 ETH (whale movement) from wallet 0xMNO to wallet 0xPQR at block 18500002.+ Transaction 0xabc transfers 200 USDT from wallet 0xSTU to wallet 0xVWX at block 18500003.+ Transaction 0xdef transfers 5000 ETH from wallet 0xYZA to wallet 0xBCD at block 18500004.+ Transaction 0x111 transfers 3000 DAI from wallet 0xEFG to wallet 0xHIJ at block 18500005.+ Transaction 0x222 transfers 1500 USDC from wallet 0xKLM to wallet 0xNOP at block 18500006.+\ No newline at end of filediff --git a/semantica/kg/graph_builder.py b/semantica/kg/graph_builder.pyindex f5db8dc3..ee67a2e2 100644--- a/semantica/kg/graph_builder.py+++ b/semantica/kg/graph_builder.py@@ -24,6 +24,7 @@ License: MITfrom datetime import datetimefrom typing import Any, Dict, List, Optional, Union+import timeclass GraphBuilder:@@ -266,6 +267,7 @@ class GraphBuilder:sources = [sources]# Track graph building+ build_start_time = time.time()tracking_id = self.progress_tracker.start_tracking(module="kg",submodule="GraphBuilder",@@ -288,35 +290,54 @@ class GraphBuilder:relationships_list = source_dict.get("relationships", [])if entities_list or relationships_list:- print(f"Processing {len(entities_list)} entities, {len(relationships_list)} relationships...")+ total_items = len(entities_list) + len(relationships_list)+ print(f"Processing {len(entities_list)} entities, {len(relationships_list)} relationships ({total_items} total)...")- # Process entities with progress+ # Process entities with progress and ETAif entities_list:- batch_size = max(500, len(entities_list) // 10) # Show ~10 progress updates+ entity_start_time = time.time()+ batch_size = max(100, len(entities_list) // 20) # Show ~20 progress updates for better granularityfor i in range(0, len(entities_list), batch_size):+ batch_start = time.time()batch = entities_list[i:i + batch_size]for item in batch:self._process_item(item, all_entities, all_relationships, **options)processed = min(i + batch_size, len(entities_list))remaining = len(entities_list) - processed- if remaining > 0:- print(f" Processed {processed}/{len(entities_list)} entities ({remaining} remaining)")++ # Calculate ETA+ elapsed = time.time() - entity_start_time+ if processed > 0 and elapsed > 0:+ rate = processed / elapsed+ eta_seconds = remaining / rate if rate > 0 else 0+ eta_str = f"{eta_seconds:.1f}s" if eta_seconds < 60 else f"{eta_seconds/60:.1f}m"+ progress_pct = (processed / len(entities_list)) * 100+ print(f" Entities: {processed}/{len(entities_list)} ({progress_pct:.1f}%) | ETA: {eta_str} | Rate: {rate:.1f}/s")else:- print(f" Processed {processed}/{len(entities_list)} entities (complete)")+ print(f" Entities: {processed}/{len(entities_list)}")- # Process relationships with progress+ # Process relationships with progress and ETAif relationships_list:- batch_size = max(500, len(relationships_list) // 10) # Show ~10 progress updates+ rel_start_time = time.time()+ batch_size = max(100, len(relationships_list) // 20) # Show ~20 progress updatesfor i in range(0, len(relationships_list), batch_size):+ batch_start = time.time()batch = relationships_list[i:i + batch_size]for item in batch:self._process_item(item, all_entities, all_relationships, **options)processed = min(i + batch_size, len(relationships_list))remaining = len(relationships_list) - processed- if remaining > 0:- print(f" Processed {processed}/{len(relationships_list)} relationships ({remaining} remaining)")++ # Calculate ETA+ elapsed = time.time() - rel_start_time+ if processed > 0 and elapsed > 0:+ rate = processed / elapsed+ eta_seconds = remaining / rate if rate > 0 else 0+ eta_str = f"{eta_seconds:.1f}s" if eta_seconds < 60 else f"{eta_seconds/60:.1f}m"+ progress_pct = (processed / len(relationships_list)) * 100+ print(f" Relationships: {processed}/{len(relationships_list)} ({progress_pct:.1f}%) | ETA: {eta_str} | Rate: {rate:.1f}/s")else:- print(f" Processed {processed}/{len(relationships_list)} relationships (complete)")+ print(f" Relationships: {processed}/{len(relationships_list)}")else:# Process sources (which might be entities)for source in sources:@@ -355,13 +376,17 @@ class GraphBuilder:self.logger.info(f"Resolving {len(all_entities)} entities using {self.entity_resolution_strategy} strategy")+ resolution_start = time.time()resolved_entities = resolver_to_use.resolve_entities(all_entities)- print(f"Resolved to {len(resolved_entities)} unique entities")+ resolution_time = time.time() - resolution_start+ print(f"β Resolved to {len(resolved_entities)} unique entities ({resolution_time:.2f}s)")self.logger.info(f"Entity resolution complete: {len(all_entities)} -> {len(resolved_entities)} unique entities")# Build graph structure+ print("Building graph structure...")+ structure_start = time.time()graph = {"entities": resolved_entities,"relationships": all_relationships,@@ -373,18 +398,25 @@ class GraphBuilder:"entity_resolution_applied": resolver_to_use is not None,},}+ structure_time = time.time() - structure_start+ print(f"β Graph structure built ({structure_time:.2f}s)")# Persist to GraphStore if availableif self.graph_store:+ print("Persisting knowledge graph to GraphStore...")self.logger.info("Persisting knowledge graph to GraphStore")self.progress_tracker.update_tracking(tracking_id, message="Persisting to GraphStore...")+ store_start = time.time()# Add nodesnode_count = self.graph_store.add_nodes(resolved_entities)+ node_time = time.time() - store_start+ print(f" Added {node_count} nodes ({node_time:.2f}s)")# Prepare edges for add_edges (expects source_id, target_id, type)+ edge_prep_start = time.time()formatted_edges = []for rel in all_relationships:formatted_edges.append({@@ -393,8 +425,14 @@ class GraphBuilder:"type": rel.get("type", "RELATED_TO"),"properties": rel.get("metadata", {})})+ edge_prep_time = time.time() - edge_prep_start+ edge_start = time.time()edge_count = self.graph_store.add_edges(formatted_edges)+ edge_time = time.time() - edge_start+ total_store_time = time.time() - store_start+ print(f" Added {edge_count} edges ({edge_time:.2f}s)")+ print(f"β GraphStore persistence complete ({total_store_time:.2f}s total)")self.logger.info(f"Persisted {node_count} nodes and {edge_count} edges")# Detect and resolve conflicts if conflict detector is available@@ -423,10 +461,19 @@ class GraphBuilder:self.logger.warning("No conflicts were automatically resolved")# Log final graph statistics+ total_build_time = time.time() - build_start_timeself.logger.info(f"Knowledge graph built successfully: "f"{len(resolved_entities)} entities, {len(all_relationships)} relationships")++ # Print final summary with timing+ print(f"\n{'='*60}")+ print(f"β Knowledge Graph Build Complete")+ print(f" Entities: {len(resolved_entities)}")+ print(f" Relationships: {len(all_relationships)}")+ print(f" Total time: {total_build_time:.2f}s")+ print(f"{'='*60}")self.progress_tracker.stop_tracking(tracking_id,