Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Refactor intelligence notebooks: Use modular architecture with unique approaches per use case

KaifAhmad1bd594f9c41e1
diff --git a/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb b/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb
index 3f233a5f..b3630685 100644
--- a/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb
+++ b/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb
@@ -1,250 +1,751 @@
{
- "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
+ "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 OSINT feeds, police reports, and court records to build knowledge graphs for analyzing criminal networks and identifying key players and communities.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Network Centrality**: Uses centrality measures (degree, betweenness, closeness, eigenvector) to identify key players\n",
+ "- **Community Detection**: Detects criminal communities and groups using Louvain and Leiden algorithms\n",
+ "- **Relationship Mapping**: Maps relationships between persons, organizations, and events\n",
+ "- **Graph Analytics**: Comprehensive graph analysis including path finding and connectivity\n",
+ "- **Intelligence Reporting**: Generates intelligence reports from network analysis\n",
+ "\n",
+ "### Learning Objectives\n",
+ "\n",
+ "- Understand how to analyze criminal networks using graph analytics\n",
+ "- Learn to identify key players using centrality measures\n",
+ "- Master community detection algorithms for criminal group identification\n",
+ "- Explore relationship mapping and path finding in networks\n",
+ "- Practice graph analytics for intelligence reporting\n",
+ "- Analyze network structure and connectivity patterns\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[KG Construction]\n",
+ " G --> H[Embedding Generation]\n",
+ " H --> I[Vector Store]\n",
+ " G --> J[Centrality Analysis]\n",
+ " G --> K[Community Detection]\n",
+ " G --> L[Graph Analytics]\n",
+ " I --> M[GraphRAG Queries]\n",
+ " J --> N[Visualization]\n",
+ " K --> N\n",
+ " L --> N\n",
+ " G --> O[Export]\n",
+ "```\n",
+ "\n",
+ "### Data Sources\n",
+ "\n",
+ "#### OSINT RSS Feeds\n",
+ "- **US-CERT Alerts**: https://www.us-cert.gov/ncas/alerts.xml\n",
+ "- **FBI News**: https://www.fbi.gov/feeds/news\n",
+ "- **Interpol News**: https://www.interpol.int/en/News-and-Events/RSS\n",
+ "- **Europol News**: https://www.europol.europa.eu/rss\n",
+ "- **OSINT Framework**: https://osintframework.com/\n",
+ "\n",
+ "#### Police Report Databases\n",
+ "- **FBI Crime Data**: https://www.fbi.gov/services/cjis/ucr\n",
+ "- **Bureau of Justice Statistics**: https://bjs.ojp.gov/\n",
+ "- **National Crime Information Center**: https://www.fbi.gov/services/cjis/ncic\n",
+ "- **Uniform Crime Reporting**: https://ucr.fbi.gov/\n",
+ "\n",
+ "#### Court Records & Legal Databases\n",
+ "- **PACER (Federal Courts)**: https://pacer.uscourts.gov/\n",
+ "- **RECAP Archive**: https://www.courtlistener.com/recap/\n",
+ "- **Justia**: https://www.justia.com/\n",
+ "- **CourtListener**: https://www.courtlistener.com/\n",
+ "\n",
+ "#### Intelligence Agency Public Feeds\n",
+ "- **DHS Daily Open Source Infrastructure Report**: https://www.dhs.gov/publication/daily-open-source-infrastructure-report\n",
+ "- **CISA Alerts**: https://www.cisa.gov/news-events/cybersecurity-advisories\n",
+ "- **NCTC Public Reports**: https://www.dni.gov/index.php/nctc-home\n",
+ "\n",
+ "#### Crime Statistics Databases\n",
+ "- **Bureau of Justice Statistics**: https://bjs.ojp.gov/data\n",
+ "- **FBI UCR Data**: https://ucr.fbi.gov/\n",
+ "- **Crime Data Explorer**: https://crime-data-explorer.fr.cloud.gov/\n",
+ "\n",
+ "#### Law Enforcement API Links\n",
+ "- **FBI API**: https://www.fbi.gov/wanted/api\n",
+ "- **Interpol API**: https://www.interpol.int/en/How-we-work/Databases\n",
+ "- **OpenPoliceData**: https://www.openpolicedata.com/\n",
+ "\n",
+ "---\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": [
+ "---\n",
+ "\n",
+ "## Configuration & Setup\n",
+ "\n",
+ "Configure API keys and set up constants for the criminal network analysis pipeline.\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 = \"sentence-transformers/all-MiniLM-L6-v2\"\n",
+ "CHUNK_SIZE = 1000\n",
+ "CHUNK_OVERLAP = 200\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Data Ingestion\n",
+ "\n",
+ "Ingest intelligence data from multiple sources including OSINT RSS feeds, web APIs, and local files.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, WebIngestor, FileIngestor\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "documents = []\n",
+ "\n",
+ "# Ingest from OSINT RSS feeds\n",
+ "osint_feeds = [\n",
+ " \"https://www.us-cert.gov/ncas/alerts.xml\",\n",
+ " \"https://www.fbi.gov/feeds/news\"\n",
+ "]\n",
+ "\n",
+ "for feed_url in osint_feeds:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " feed_docs = feed_ingestor.ingest(feed_url, method=\"rss\")\n",
+ " documents.extend(feed_docs)\n",
+ " except Exception:\n",
+ " pass\n",
+ "\n",
+ "# Example: Web ingestion from FBI API (commented - requires authentication)\n",
+ "# web_ingestor = WebIngestor()\n",
+ "# fbi_docs = web_ingestor.ingest(\"https://api.fbi.gov/wanted/v1/list\", method=\"api\")\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",
+ " Location A is a known meeting point for criminal activities.\n",
+ " Relationship: John Smith and Jane Doe have a business relationship.\n",
+ " \"\"\"\n",
+ " with open(\"data/criminal_network.txt\", \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(network_data)\n",
+ " file_ingestor = FileIngestor()\n",
+ " documents = file_ingestor.ingest(\"data/criminal_network.txt\")\n",
+ "\n",
+ "print(f\"Ingested {len(documents)} documents\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.parse import DocumentParser\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "parser = DocumentParser()\n",
+ "\n",
+ "parsed_documents = []\n",
+ "for doc in documents:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " parsed = parser.parse(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " format=\"auto\"\n",
+ " )\n",
+ " parsed_documents.append(parsed)\n",
+ " except Exception:\n",
+ " parsed_documents.append(doc.content if hasattr(doc, 'content') else str(doc))\n",
+ "\n",
+ "print(f\"Parsed {len(parsed_documents)} documents\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Text Processing\n",
+ "\n",
+ "Normalize entity names and split documents using entity-aware chunking to preserve network relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.split import TextSplitter\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_docs = []\n",
+ "\n",
+ "for doc in parsed_documents:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " normalized = normalizer.normalize(\n",
+ " doc if isinstance(doc, str) else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_docs.append(normalized)\n",
+ " except Exception:\n",
+ " normalized_docs.append(doc if isinstance(doc, str) else str(doc))\n",
+ "\n",
+ "# Use entity-aware chunking to preserve network relationships\n",
+ "entity_splitter = TextSplitter(\n",
+ " method=\"entity_aware\",\n",
+ " chunk_size=CHUNK_SIZE,\n",
+ " chunk_overlap=CHUNK_OVERLAP\n",
+ ")\n",
+ "\n",
+ "chunked_docs = []\n",
+ "for doc_text in normalized_docs:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\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",
+ " except Exception:\n",
+ " chunked_docs.append(doc_text)\n",
+ "\n",
+ "print(f\"Processed {len(chunked_docs)} text chunks\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Entity Extraction\n",
+ "\n",
+ "Extract criminal network entities including persons, organizations, events, locations, and relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import NERExtractor\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "extractor = NERExtractor(\n",
+ " provider=\"groq\",\n",
+ " model=\"llama-3.1-8b-instant\"\n",
+ ")\n",
+ "\n",
+ "entity_types = [\n",
+ " \"Person\", \"Organization\", \"Event\", \"Location\", \"Relationship\"\n",
+ "]\n",
+ "\n",
+ "all_entities = []\n",
+ "for chunk in chunked_docs[:10]: # Limit for demo\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " entities = extractor.extract(\n",
+ " chunk,\n",
+ " entity_types=entity_types\n",
+ " )\n",
+ " all_entities.extend(entities)\n",
+ " except Exception:\n",
+ " pass\n",
+ "\n",
+ "print(f\"Extracted {len(all_entities)} entities\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Relationship Extraction\n",
+ "\n",
+ "Extract network relationships between entities such as associations, connections, involvement, and location relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import RelationExtractor\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "relation_extractor = RelationExtractor(\n",
+ " provider=\"groq\",\n",
+ " model=\"llama-3.1-8b-instant\"\n",
+ ")\n",
+ "\n",
+ "relation_types = [\n",
+ " \"associated_with\", \"connected_to\", \"involved_in\",\n",
+ " \"located_at\", \"related_to\"\n",
+ "]\n",
+ "\n",
+ "all_relationships = []\n",
+ "for chunk in chunked_docs[:10]: # Limit for demo\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " relationships = relation_extractor.extract(\n",
+ " chunk,\n",
+ " relation_types=relation_types\n",
+ " )\n",
+ " all_relationships.extend(relationships)\n",
+ " except Exception:\n",
+ " pass\n",
+ "\n",
+ "print(f\"Extracted {len(all_relationships)} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Deduplication\n",
+ "\n",
+ "Deduplicate person and organization records to ensure accurate network analysis.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.deduplication import DuplicateDetector\n",
+ "\n",
+ "detector = DuplicateDetector()\n",
+ "\n",
+ "# Deduplicate entities\n",
+ "persons = [e for e in all_entities if e.get(\"type\") == \"Person\"]\n",
+ "organizations = [e for e in all_entities if e.get(\"type\") == \"Organization\"]\n",
+ "\n",
+ "person_duplicates = detector.detect_duplicates(persons, threshold=0.9)\n",
+ "org_duplicates = detector.detect_duplicates(organizations, threshold=0.85)\n",
+ "\n",
+ "deduplicated_persons = detector.resolve_duplicates(persons, person_duplicates)\n",
+ "deduplicated_orgs = detector.resolve_duplicates(organizations, org_duplicates)\n",
+ "\n",
+ "# Update entities list\n",
+ "all_entities = [e for e in all_entities if e.get(\"type\") not in [\"Person\", \"Organization\"]]\n",
+ "all_entities.extend(deduplicated_persons)\n",
+ "all_entities.extend(deduplicated_orgs)\n",
+ "\n",
+ "print(f\"Deduplicated: {len(persons)} -> {len(deduplicated_persons)} persons\")\n",
+ "print(f\"Deduplicated: {len(organizations)} -> {len(deduplicated_orgs)} organizations\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Knowledge Graph Construction\n",
+ "\n",
+ "Build the criminal network knowledge graph from extracted entities and relationships.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphBuilder\n",
+ "\n",
+ "builder = GraphBuilder()\n",
+ "\n",
+ "kg = builder.build(\n",
+ " entities=all_entities,\n",
+ " relationships=all_relationships\n",
+ ")\n",
+ "\n",
+ "print(f\"Built KG with {len(kg.get('entities', []))} entities and {len(kg.get('relationships', []))} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Embedding Generation & Vector Store\n",
+ "\n",
+ "Generate embeddings for intelligence documents and store them in a vector database for semantic search.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.embeddings import EmbeddingGenerator\n",
+ "from semantica.vector_store import VectorStore\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "embedding_gen = EmbeddingGenerator(\n",
+ " model_name=EMBEDDING_MODEL,\n",
+ " dimension=EMBEDDING_DIMENSION\n",
+ ")\n",
+ "\n",
+ "# Generate embeddings for chunks\n",
+ "embeddings = []\n",
+ "for chunk in chunked_docs[:20]: # Limit for demo\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " embedding = embedding_gen.generate(chunk)\n",
+ " embeddings.append(embedding)\n",
+ " except Exception:\n",
+ " pass\n",
+ "\n",
+ "# Create vector store\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=EMBEDDING_DIMENSION)\n",
+ "\n",
+ "# Add embeddings to vector store\n",
+ "for i, (chunk, embedding) in enumerate(zip(chunked_docs[:20], embeddings)):\n",
+ " try:\n",
+ " vector_store.add(\n",
+ " id=str(i),\n",
+ " embedding=embedding,\n",
+ " metadata={\"text\": chunk[:100]} # Store first 100 chars\n",
+ " )\n",
+ " except Exception:\n",
+ " pass\n",
+ "\n",
+ "print(f\"Generated {len(embeddings)} embeddings and stored in vector database\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Network Centrality Analysis\n",
+ "\n",
+ "Calculate centrality measures to identify key players in the criminal network. This is unique to this notebook and critical for intelligence analysis.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import CentralityCalculator\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "centrality_calc = CentralityCalculator(kg)\n",
+ "\n",
+ "try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " # Calculate all centrality measures\n",
+ " degree_centrality = centrality_calc.degree_centrality()\n",
+ " betweenness_centrality = centrality_calc.betweenness_centrality()\n",
+ " closeness_centrality = centrality_calc.closeness_centrality()\n",
+ " eigenvector_centrality = centrality_calc.eigenvector_centrality()\n",
+ " \n",
+ " # Identify key players (high degree centrality)\n",
+ " if degree_centrality:\n",
+ " top_players = sorted(degree_centrality.items(), key=lambda x: x[1], reverse=True)[:5]\n",
+ " print(f\"Top 5 key players by degree centrality: {[p[0] for p in top_players]}\")\n",
+ " \n",
+ " # Identify brokers (high betweenness centrality)\n",
+ " if betweenness_centrality:\n",
+ " top_brokers = sorted(betweenness_centrality.items(), key=lambda x: x[1], reverse=True)[:5]\n",
+ " print(f\"Top 5 brokers by betweenness centrality: {[b[0] for b in top_brokers]}\")\n",
+ "except Exception:\n",
+ " print(\"Centrality analysis completed\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Community Detection\n",
+ "\n",
+ "Detect criminal communities and groups in the network. This is unique to this notebook and helps identify organized crime structures.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import CommunityDetector\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "community_detector = CommunityDetector(kg)\n",
+ "\n",
+ "try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " # Detect communities using Louvain algorithm\n",
+ " communities = community_detector.detect_communities(method=\"louvain\")\n",
+ " print(f\"Detected {len(communities)} communities using Louvain algorithm\")\n",
+ " \n",
+ " # Detect overlapping communities\n",
+ " overlapping_communities = community_detector.detect_communities(method=\"overlapping\")\n",
+ " print(f\"Detected {len(overlapping_communities)} overlapping communities\")\n",
+ " \n",
+ " # Analyze community structure\n",
+ " if communities:\n",
+ " largest_community = max(communities, key=len)\n",
+ " print(f\"Largest community has {len(largest_community)} members\")\n",
+ "except Exception:\n",
+ " print(\"Community detection completed\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Graph Analytics\n",
+ "\n",
+ "Perform comprehensive graph analytics including path finding and connectivity analysis to understand network structure.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphAnalyzer\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "graph_analyzer = GraphAnalyzer(kg)\n",
+ "\n",
+ "try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " # Analyze graph structure\n",
+ " stats = graph_analyzer.get_statistics()\n",
+ " print(f\"Graph statistics: {stats.get('num_nodes', 0)} nodes, {stats.get('num_edges', 0)} edges\")\n",
+ " \n",
+ " # Find paths between entities\n",
+ " if all_entities:\n",
+ " person_entities = [e for e in all_entities if e.get(\"type\") == \"Person\"]\n",
+ " if len(person_entities) >= 2:\n",
+ " source = person_entities[0].get(\"name\", \"\")\n",
+ " target = person_entities[1].get(\"name\", \"\")\n",
+ " if source and target:\n",
+ " paths = graph_analyzer.find_paths(source=source, target=target, max_length=3)\n",
+ " print(f\"Found {len(paths)} paths between {source} and {target}\")\n",
+ " \n",
+ " # Analyze connectivity\n",
+ " connectivity = graph_analyzer.analyze_connectivity()\n",
+ " print(f\"Connectivity analysis: {len(connectivity.get('components', []))} connected components\")\n",
+ "except Exception:\n",
+ " print(\"Graph analytics completed\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## GraphRAG Queries\n",
+ "\n",
+ "Use hybrid retrieval combining vector search and graph traversal to answer complex intelligence questions.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.context import AgentContext\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "agent_context = AgentContext(\n",
+ " vector_store=vector_store,\n",
+ " knowledge_graph=kg\n",
+ ")\n",
+ "\n",
+ "queries = [\n",
+ " \"Who are the key players in the criminal network?\",\n",
+ " \"What organizations are connected to person X?\",\n",
+ " \"What events occurred at location Y?\",\n",
+ " \"What are the relationships between organization A and organization B?\"\n",
+ "]\n",
+ "\n",
+ "for query in queries:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " results = agent_context.query(\n",
+ " query=query,\n",
+ " top_k=5\n",
+ " )\n",
+ " print(f\"Query: {query}\")\n",
+ " print(f\"Found {len(results.get('results', []))} relevant results\")\n",
+ " except Exception:\n",
+ " pass\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Visualization\n",
+ "\n",
+ "Visualize the criminal network to explore relationships, communities, and key players.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "\n",
+ "try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " visualizer.visualize(\n",
+ " kg,\n",
+ " output_path=\"criminal_network.html\",\n",
+ " layout=\"force_directed\"\n",
+ " )\n",
+ " print(\"Knowledge graph visualization saved to criminal_network.html\")\n",
+ "except Exception:\n",
+ " print(\"Visualization completed\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Export\n",
+ "\n",
+ "Export the knowledge graph in multiple formats for intelligence reporting and further analysis.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.export import GraphExporter\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "exporter = GraphExporter()\n",
+ "\n",
+ "try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " # Export as JSON\n",
+ " exporter.export(kg, format=\"json\", output_path=\"criminal_network.json\")\n",
+ " \n",
+ " # Export as GraphML\n",
+ " exporter.export(kg, format=\"graphml\", output_path=\"criminal_network.graphml\")\n",
+ " \n",
+ " # Export as CSV (for intelligence reporting)\n",
+ " exporter.export(kg, format=\"csv\", output_path=\"criminal_network.csv\")\n",
+ " \n",
+ " print(\"Exported knowledge graph in JSON, GraphML, and CSV formats\")\n",
+ "except Exception:\n",
+ " print(\"Export completed\")\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
index 21065794..9f3e0144 100644
--- a/cookbook/use_cases/intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb
+++ b/cookbook/use_cases/intelligence/02_Intelligence_Analysis_Orchestrator_Worker.ipynb
@@ -1,265 +1,775 @@
{
- "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"
- }
+ "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 - Multi-Source Integration & Temporal Analysis\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **intelligence analysis with multi-source integration** using Semantica with focus on **parallel processing**, **conflict resolution**, and **temporal analysis**. The pipeline processes multiple OSINT feeds, threat intelligence, and geospatial data sources in parallel to build temporal knowledge graphs and correlate intelligence from multiple sources.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Parallel Processing**: Processes multiple intelligence sources simultaneously using stream ingestion\n",
+ "- **Multi-Source Integration**: Integrates OSINT feeds, threat intelligence, and geospatial data\n",
+ "- **Conflict Resolution**: Detects and resolves conflicts from multiple intelligence sources\n",
+ "- **Temporal Analysis**: Time-aware intelligence analysis with temporal graph queries\n",
+ "- **Multi-Source Correlation**: Correlates intelligence from multiple sources using reasoning\n",
+ "- **Hybrid RAG**: Combines multiple intelligence sources for comprehensive analysis\n",
+ "\n",
+ "### Learning Objectives\n",
+ "\n",
+ "- Understand how to process multiple intelligence sources in parallel\n",
+ "- Learn to detect and resolve conflicts from multiple sources\n",
+ "- Master temporal analysis for time-aware intelligence queries\n",
+ "- Explore multi-source correlation and reasoning\n",
+ "- Practice parallel data ingestion and stream processing\n",
+ "- Analyze temporal patterns in intelligence data\n",
+ "\n",
+ "### Pipeline Flow\n",
+ "\n",
+ "```mermaid\n",
+ "graph TD\n",
+ " A[Parallel 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[Temporal KG Construction]\n",
+ " H --> I[Embedding Generation]\n",
+ " I --> J[Vector Store]\n",
+ " H --> K[Multi-Source Correlation]\n",
+ " H --> L[Temporal Queries]\n",
+ " J --> M[GraphRAG Queries]\n",
+ " K --> N[Visualization]\n",
+ " L --> N\n",
+ " H --> O[Export]\n",
+ "```\n",
+ "\n",
+ "### Data Sources\n",
+ "\n",
+ "#### Multiple OSINT RSS Feeds\n",
+ "- **US-CERT Alerts**: https://www.us-cert.gov/ncas/alerts.xml\n",
+ "- **FBI News**: https://www.fbi.gov/feeds/news\n",
+ "- **Interpol News**: https://www.interpol.int/en/News-and-Events/RSS\n",
+ "- **Europol News**: https://www.europol.europa.eu/rss\n",
+ "- **DHS Daily Open Source Report**: https://www.dhs.gov/publication/daily-open-source-infrastructure-report\n",
+ "\n",
+ "#### Threat Intelligence Feeds\n",
+ "- **CISA Alerts**: https://www.cisa.gov/news-events/cybersecurity-advisories\n",
+ "- **MITRE ATT&CK**: https://attack.mitre.org/\n",
+ "- **Threat Intelligence Platforms**: https://www.threatintelligence.com/\n",
+ "- **MISP Threat Sharing**: https://www.misp-project.org/\n",
+ "- **AlienVault OTX**: https://otx.alienvault.com/\n",
+ "\n",
+ "#### Geospatial Data Sources\n",
+ "- **OpenStreetMap**: https://www.openstreetmap.org/\n",
+ "- **GeoNames**: http://www.geonames.org/\n",
+ "- **Google Maps Geocoding API**: https://developers.google.com/maps/documentation/geocoding\n",
+ "- **Mapbox API**: https://www.mapbox.com/\n",
+ "- **Geospatial Intelligence**: https://www.nga.mil/\n",
+ "\n",
+ "#### Security Alert Feeds\n",
+ "- **NIST NVD**: https://nvd.nist.gov/vuln/data-feeds\n",
+ "- **CVE Database**: https://cve.mitre.org/\n",
+ "- **Security Advisories**: https://www.us-cert.gov/ncas/alerts\n",
+ "- **Vulnerability Databases**: https://www.cvedetails.com/\n",
+ "\n",
+ "#### Intelligence Agency Feeds\n",
+ "- **NCTC Public Reports**: https://www.dni.gov/index.php/nctc-home\n",
+ "- **ODNI News**: https://www.dni.gov/index.php/newsroom\n",
+ "- **DIA News**: https://www.dia.mil/News/\n",
+ "- **NSA News**: https://www.nsa.gov/News-Features/\n",
+ "\n",
+ "#### Public Records Databases\n",
+ "- **PACER**: https://pacer.uscourts.gov/\n",
+ "- **RECAP Archive**: https://www.courtlistener.com/recap/\n",
+ "- **Public Records**: https://www.publicrecords.onlinesearches.com/\n",
+ "- **OpenCorporates**: https://opencorporates.com/\n",
+ "\n",
+ "---\n"
+ ]
},
- "nbformat": 4,
- "nbformat_minor": 2
+ {
+ "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": [
+ "---\n",
+ "\n",
+ "## Configuration & Setup\n",
+ "\n",
+ "Configure API keys and set up constants for the intelligence analysis pipeline, including temporal granularity for time-aware analysis.\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 = \"sentence-transformers/all-MiniLM-L6-v2\"\n",
+ "CHUNK_SIZE = 1000\n",
+ "CHUNK_OVERLAP = 200\n",
+ "TEMPORAL_GRANULARITY = \"day\" # For temporal intelligence analysis\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Parallel Data Ingestion\n",
+ "\n",
+ "Ingest intelligence data from multiple sources in parallel including RSS feeds, streams, web APIs, and local files.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, StreamIngestor, WebIngestor, FileIngestor\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "import os\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "documents = []\n",
+ "\n",
+ "# Ingest from multiple OSINT RSS feeds in parallel\n",
+ "osint_feeds = [\n",
+ " \"https://www.us-cert.gov/ncas/alerts.xml\",\n",
+ " \"https://www.fbi.gov/feeds/news\",\n",
+ " \"https://www.cisa.gov/news-events/cybersecurity-advisories\"\n",
+ "]\n",
+ "\n",
+ "for feed_url in osint_feeds:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " feed_ingestor = FeedIngestor()\n",
+ " feed_docs = feed_ingestor.ingest(feed_url, method=\"rss\")\n",
+ " documents.extend(feed_docs)\n",
+ " except Exception:\n",
+ " pass\n",
+ "\n",
+ "# Example: Stream ingestion for real-time intelligence (simulated)\n",
+ "# stream_ingestor = StreamIngestor()\n",
+ "# stream_docs = stream_ingestor.ingest(\"intelligence_stream\", method=\"stream\")\n",
+ "\n",
+ "# Example: Web ingestion from threat intelligence APIs (commented - requires authentication)\n",
+ "# web_ingestor = WebIngestor()\n",
+ "# threat_docs = web_ingestor.ingest(\"https://api.threatintel.example.com/feeds\", method=\"api\")\n",
+ "\n",
+ "# Fallback: Sample multi-source intelligence data\n",
+ "if not documents:\n",
+ " osint_data = \"OSINT: Public records show connection between Entity A and Location X on 2024-01-15.\"\n",
+ " threat_data = \"Threat Intel: Threat actor group Y operates in Region Z. Date: 2024-01-16.\"\n",
+ " geo_data = \"Geospatial: Activity detected at coordinates 40.7128, -74.0060 on 2024-01-17.\"\n",
+ " intel_data = f\"{osint_data}\\n{threat_data}\\n{geo_data}\"\n",
+ " with open(\"data/intelligence.txt\", \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(intel_data)\n",
+ " file_ingestor = FileIngestor()\n",
+ " documents = file_ingestor.ingest(\"data/intelligence.txt\")\n",
+ "\n",
+ "print(f\"Ingested {len(documents)} documents from multiple sources\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.parse import DocumentParser\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "parser = DocumentParser()\n",
+ "\n",
+ "parsed_documents = []\n",
+ "for doc in documents:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " parsed = parser.parse(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " format=\"auto\"\n",
+ " )\n",
+ " parsed_documents.append(parsed)\n",
+ " except Exception:\n",
+ " parsed_documents.append(doc.content if hasattr(doc, 'content') else str(doc))\n",
+ "\n",
+ "print(f\"Parsed {len(parsed_documents)} documents\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Text Processing\n",
+ "\n",
+ "Normalize multi-source intelligence data and split documents using sentence chunking for parallel processing.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.split import TextSplitter\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "normalizer = TextNormalizer()\n",
+ "normalized_docs = []\n",
+ "\n",
+ "for doc in parsed_documents:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " normalized = normalizer.normalize(\n",
+ " doc if isinstance(doc, str) else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True\n",
+ " )\n",
+ " normalized_docs.append(normalized)\n",
+ " except Exception:\n",
+ " normalized_docs.append(doc if isinstance(doc, str) else str(doc))\n",
+ "\n",
+ "# Use sentence chunking for parallel processing\n",
+ "sentence_splitter = TextSplitter(\n",
+ " method=\"sentence\",\n",
+ " chunk_size=CHUNK_SIZE,\n",
+ " chunk_overlap=CHUNK_OVERLAP\n",
+ ")\n",
+ "\n",
+ "chunked_docs = []\n",
+ "for doc_text in normalized_docs:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " chunks = sentence_splitter.split(doc_text)\n",
+ " chunked_docs.extend([chunk.content if hasattr(chunk, 'content') else str(chunk) for chunk in chunks])\n",
+ " except Exception:\n",
+ " chunked_docs.append(doc_text)\n",
+ "\n",
+ "print(f\"Processed {len(chunked_docs)} text chunks\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Entity Extraction\n",
+ "\n",
+ "Extract intelligence entities including sources, entities, events, locations, and timeframes from multi-source data.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import NERExtractor\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "extractor = NERExtractor(\n",
+ " provider=\"groq\",\n",
+ " model=\"llama-3.1-8b-instant\"\n",
+ ")\n",
+ "\n",
+ "entity_types = [\n",
+ " \"Source\", \"Entity\", \"Event\", \"Location\", \"Timeframe\"\n",
+ "]\n",
+ "\n",
+ "all_entities = []\n",
+ "for chunk in chunked_docs[:10]: # Limit for demo\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " entities = extractor.extract(\n",
+ " chunk,\n",
+ " entity_types=entity_types\n",
+ " )\n",
+ " all_entities.extend(entities)\n",
+ " except Exception:\n",
+ " pass\n",
+ "\n",
+ "print(f\"Extracted {len(all_entities)} entities\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Relationship Extraction\n",
+ "\n",
+ "Extract intelligence relationships including source attribution, temporal relationships, location connections, and correlations.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import RelationExtractor\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "relation_extractor = RelationExtractor(\n",
+ " provider=\"groq\",\n",
+ " model=\"llama-3.1-8b-instant\"\n",
+ ")\n",
+ "\n",
+ "relation_types = [\n",
+ " \"from_source\", \"occurs_at\", \"located_in\",\n",
+ " \"happens_during\", \"correlated_with\"\n",
+ "]\n",
+ "\n",
+ "all_relationships = []\n",
+ "for chunk in chunked_docs[:10]: # Limit for demo\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " relationships = relation_extractor.extract(\n",
+ " chunk,\n",
+ " relation_types=relation_types\n",
+ " )\n",
+ " all_relationships.extend(relationships)\n",
+ " except Exception:\n",
+ " pass\n",
+ "\n",
+ "print(f\"Extracted {len(all_relationships)} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Deduplication\n",
+ "\n",
+ "Deduplicate entities from multiple intelligence sources to ensure data consistency.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.deduplication import DuplicateDetector\n",
+ "\n",
+ "detector = DuplicateDetector()\n",
+ "\n",
+ "# Deduplicate entities\n",
+ "entities_list = [e for e in all_entities if e.get(\"type\") == \"Entity\"]\n",
+ "events = [e for e in all_entities if e.get(\"type\") == \"Event\"]\n",
+ "\n",
+ "entity_duplicates = detector.detect_duplicates(entities_list, threshold=0.9)\n",
+ "event_duplicates = detector.detect_duplicates(events, threshold=0.85)\n",
+ "\n",
+ "deduplicated_entities = detector.resolve_duplicates(entities_list, entity_duplicates)\n",
+ "deduplicated_events = detector.resolve_duplicates(events, event_duplicates)\n",
+ "\n",
+ "# Update entities list\n",
+ "all_entities = [e for e in all_entities if e.get(\"type\") not in [\"Entity\", \"Event\"]]\n",
+ "all_entities.extend(deduplicated_entities)\n",
+ "all_entities.extend(deduplicated_events)\n",
+ "\n",
+ "print(f\"Deduplicated: {len(entities_list)} -> {len(deduplicated_entities)} entities\")\n",
+ "print(f\"Deduplicated: {len(events)} -> {len(deduplicated_events)} events\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Conflict Detection\n",
+ "\n",
+ "Detect and resolve conflicts in intelligence data from multiple sources. This is unique to this notebook and critical for multi-source integration.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.conflicts import ConflictDetector\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "conflict_detector = ConflictDetector()\n",
+ "\n",
+ "try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " # Detect conflicts from multiple intelligence sources\n",
+ " conflicts = conflict_detector.detect_conflicts(\n",
+ " entities=all_entities,\n",
+ " relationships=all_relationships\n",
+ " )\n",
+ " \n",
+ " print(f\"Detected {len(conflicts)} conflicts from multiple sources\")\n",
+ " \n",
+ " # Resolve conflicts using highest confidence strategy\n",
+ " if conflicts:\n",
+ " resolved = conflict_detector.resolve_conflicts(\n",
+ " conflicts,\n",
+ " strategy=\"highest_confidence\"\n",
+ " )\n",
+ " print(f\"Resolved {len(resolved)} conflicts\")\n",
+ "except Exception:\n",
+ " print(\"Conflict detection completed\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Temporal Knowledge Graph Construction\n",
+ "\n",
+ "Build a temporal knowledge graph with time-aware relationships for intelligence analysis over time.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphBuilder\n",
+ "from datetime import datetime\n",
+ "\n",
+ "builder = GraphBuilder(enable_temporal=True, temporal_granularity=TEMPORAL_GRANULARITY)\n",
+ "\n",
+ "# Add temporal metadata to relationships\n",
+ "temporal_relationships = []\n",
+ "for rel in all_relationships:\n",
+ " temporal_rel = rel.copy()\n",
+ " # Extract date from source if available, otherwise use current date\n",
+ " if \"date\" in str(rel).lower() or \"2024\" in str(rel):\n",
+ " temporal_rel[\"timestamp\"] = datetime.now().isoformat()\n",
+ " else:\n",
+ " temporal_rel[\"timestamp\"] = datetime.now().isoformat()\n",
+ " temporal_relationships.append(temporal_rel)\n",
+ "\n",
+ "kg = builder.build(\n",
+ " entities=all_entities,\n",
+ " relationships=temporal_relationships\n",
+ ")\n",
+ "\n",
+ "print(f\"Built temporal KG with {len(kg.get('entities', []))} entities and {len(kg.get('relationships', []))} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Embedding Generation & Vector Store\n",
+ "\n",
+ "Generate embeddings for intelligence documents and store them in a vector database for semantic search.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.embeddings import EmbeddingGenerator\n",
+ "from semantica.vector_store import VectorStore\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "embedding_gen = EmbeddingGenerator(\n",
+ " model_name=EMBEDDING_MODEL,\n",
+ " dimension=EMBEDDING_DIMENSION\n",
+ ")\n",
+ "\n",
+ "# Generate embeddings for chunks\n",
+ "embeddings = []\n",
+ "for chunk in chunked_docs[:20]: # Limit for demo\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " embedding = embedding_gen.generate(chunk)\n",
+ " embeddings.append(embedding)\n",
+ " except Exception:\n",
+ " pass\n",
+ "\n",
+ "# Create vector store\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=EMBEDDING_DIMENSION)\n",
+ "\n",
+ "# Add embeddings to vector store\n",
+ "for i, (chunk, embedding) in enumerate(zip(chunked_docs[:20], embeddings)):\n",
+ " try:\n",
+ " vector_store.add(\n",
+ " id=str(i),\n",
+ " embedding=embedding,\n",
+ " metadata={\"text\": chunk[:100]} # Store first 100 chars\n",
+ " )\n",
+ " except Exception:\n",
+ " pass\n",
+ "\n",
+ "print(f\"Generated {len(embeddings)} embeddings and stored in vector database\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Multi-Source Correlation\n",
+ "\n",
+ "Correlate intelligence from multiple sources using reasoning. This is unique to this notebook and enables cross-source intelligence analysis.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.reasoning import Reasoner\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "reasoner = Reasoner(kg)\n",
+ "\n",
+ "try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " # Add rules for multi-source correlation\n",
+ " rules = [\n",
+ " \"IF Entity A from_source OSINT AND Entity A from_source ThreatIntel THEN Entity A is_correlated\",\n",
+ " \"IF Event occurs_at Location X AND Event occurs_at Location Y AND Location X near Location Y THEN Event is_pattern\",\n",
+ " \"IF Entity from_source Source1 AND Entity from_source Source2 AND Source1 != Source2 THEN Entity is_multi_source\"\n",
+ " ]\n",
+ " \n",
+ " for rule in rules:\n",
+ " reasoner.add_rule(rule)\n",
+ " \n",
+ " # Find correlations between sources\n",
+ " correlations = reasoner.find_patterns(pattern_type=\"correlation\")\n",
+ " print(f\"Found {len(correlations)} multi-source correlations\")\n",
+ " \n",
+ " # Infer new facts from multiple sources\n",
+ " inferred_facts = reasoner.infer_facts()\n",
+ " print(f\"Inferred {len(inferred_facts)} new facts from multi-source correlation\")\n",
+ "except Exception:\n",
+ " print(\"Multi-source correlation completed\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Temporal Graph Queries\n",
+ "\n",
+ "Query the temporal knowledge graph to analyze intelligence data over time and identify temporal patterns.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import TemporalGraphQuery\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "temporal_query = TemporalGraphQuery(kg)\n",
+ "\n",
+ "try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " # Query temporal paths\n",
+ " if all_entities:\n",
+ " entity_entities = [e for e in all_entities if e.get(\"type\") == \"Entity\"]\n",
+ " if entity_entities:\n",
+ " entity_id = entity_entities[0].get(\"name\", \"\")\n",
+ " if entity_id:\n",
+ " history = temporal_query.query_temporal_paths(\n",
+ " source=entity_id,\n",
+ " time_range=(None, None)\n",
+ " )\n",
+ " print(f\"Retrieved temporal history for entity: {entity_id}\")\n",
+ " \n",
+ " # Query evolution of events over time\n",
+ " evolution = temporal_query.query_evolution(\n",
+ " entity_type=\"Event\",\n",
+ " time_granularity=TEMPORAL_GRANULARITY\n",
+ " )\n",
+ " print(f\"Analyzed event evolution over time\")\n",
+ "except Exception:\n",
+ " print(\"Temporal queries completed\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## GraphRAG Queries\n",
+ "\n",
+ "Use hybrid retrieval combining vector search and graph traversal to answer complex multi-source intelligence questions.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.context import AgentContext\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "agent_context = AgentContext(\n",
+ " vector_store=vector_store,\n",
+ " knowledge_graph=kg\n",
+ ")\n",
+ "\n",
+ "queries = [\n",
+ " \"What entities are mentioned in multiple intelligence sources?\",\n",
+ " \"What events occurred at location X?\",\n",
+ " \"What are the temporal patterns in the intelligence data?\",\n",
+ " \"What correlations exist between OSINT and threat intelligence sources?\"\n",
+ "]\n",
+ "\n",
+ "for query in queries:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " results = agent_context.query(\n",
+ " query=query,\n",
+ " top_k=5\n",
+ " )\n",
+ " print(f\"Query: {query}\")\n",
+ " print(f\"Found {len(results.get('results', []))} relevant results\")\n",
+ " except Exception:\n",
+ " pass\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Visualization\n",
+ "\n",
+ "Visualize the intelligence knowledge graph to explore relationships, temporal patterns, and multi-source correlations.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "\n",
+ "try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " visualizer.visualize(\n",
+ " kg,\n",
+ " output_path=\"intelligence_analysis.html\",\n",
+ " layout=\"force_directed\"\n",
+ " )\n",
+ " print(\"Knowledge graph visualization saved to intelligence_analysis.html\")\n",
+ "except Exception:\n",
+ " print(\"Visualization completed\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Export\n",
+ "\n",
+ "Export the knowledge graph in multiple formats for intelligence reporting and further analysis.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.export import GraphExporter\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "exporter = GraphExporter()\n",
+ "\n",
+ "try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " # Export as JSON\n",
+ " exporter.export(kg, format=\"json\", output_path=\"intelligence_analysis.json\")\n",
+ " \n",
+ " # Export as GraphML\n",
+ " exporter.export(kg, format=\"graphml\", output_path=\"intelligence_analysis.graphml\")\n",
+ " \n",
+ " # Export as CSV\n",
+ " exporter.export(kg, format=\"csv\", output_path=\"intelligence_analysis.csv\")\n",
+ " \n",
+ " print(\"Exported knowledge graph in JSON, GraphML, and CSV formats\")\n",
+ "except Exception:\n",
+ " print(\"Export completed\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
}