Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Refactor cybersecurity notebooks: Use modular architecture with comprehensive data sources and all Semantica modules

KaifAhmad18740379df66e
diff --git a/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb b/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb
index ed81abd3..8ca06b7b 100644
--- a/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb
+++ b/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb
@@ -1,307 +1,717 @@
{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb)\n",
- "\n",
- "# Real-Time Anomaly Detection - Stream Processing & Temporal KGs\n",
- "\n",
- "## Overview\n",
- "\n",
- "This notebook demonstrates **real-time anomaly detection** using Semantica with focus on **stream ingestion**, **temporal knowledge graphs**, and **pattern detection**. The pipeline streams security logs in real-time, builds temporal knowledge graphs, and detects anomalies using pattern detection.\n",
- "\n",
- "### Key Features\n",
- "\n",
- "- **Stream Processing**: Emphasizes real-time log streaming and processing\n",
- "- **Temporal Knowledge Graphs**: Builds temporal KGs to track events over time\n",
- "- **Pattern Detection**: Uses graph patterns to identify anomalies\n",
- "- **Automated Alerting**: Generates alerts for detected anomalies\n",
- "- **Real-Time Processing**: Demonstrates stream ingestion capabilities\n",
- "\n",
- "### Pipeline Architecture\n",
- "\n",
- "1. **Phase 0**: Setup & Configuration\n",
- "2. **Phase 1**: Stream Security Log Ingestion\n",
- "3. **Phase 2**: Real-Time Log Parsing\n",
- "4. **Phase 3**: Entity Extraction (Log, Event, IP, User, Alert)\n",
- "5. **Phase 4**: Temporal Knowledge Graph Construction\n",
- "6. **Phase 5**: Pattern Detection\n",
- "7. **Phase 6**: Anomaly Detection\n",
- "8. **Phase 7**: Alert Generation & Visualization\n",
- "\n",
- "---\n",
- "\n",
- "## Installation\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 0: Setup & Configuration\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import os\n",
- "from semantica.core import Semantica, ConfigManager\n",
- "from semantica.ingest import StreamIngestor\n",
- "\n",
- "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
- "\n",
- "config_dict = {\n",
- " \"project_name\": \"Real_Time_Anomaly_Detection\",\n",
- " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
- " \"knowledge_graph\": {\"backend\": \"networkx\", \"temporal\": True}\n",
- "}\n",
- "\n",
- "config = ConfigManager().load_from_dict(config_dict)\n",
- "core = Semantica(config=config)\n",
- "print(\"Configured for real-time anomaly detection with stream processing focus\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 1: Real Data Ingestion (CVE RSS Feed & Kafka Stream)\n",
- "\n",
- "Ingest security data from CVE RSS feeds and simulated Kafka streams.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.ingest import FeedIngestor, StreamIngestor, FileIngestor\n",
- "import os\n",
- "\n",
- "os.makedirs(\"data\", exist_ok=True)\n",
- "\n",
- "# Option 1: Ingest from CVE RSS feed (real data source)\n",
- "cve_rss_url = \"https://cve.mitre.org/data/downloads/allitems.xml\" # CVE feed\n",
- "\n",
- "documents = []\n",
- "try:\n",
- " feed_ingestor = FeedIngestor()\n",
- " feed_documents = feed_ingestor.ingest(cve_rss_url, method=\"rss\")\n",
- " print(f\"Ingested {len(feed_documents)} documents from CVE RSS feed\")\n",
- " documents.extend(feed_documents)\n",
- "except Exception as e:\n",
- " print(f\"CVE RSS feed ingestion failed: {e}\")\n",
- "\n",
- "# Option 2: Simulate Kafka stream (in production, use actual Kafka)\n",
- "# stream_ingestor = StreamIngestor()\n",
- "# stream_documents = stream_ingestor.ingest(\"kafka://localhost:9092/security-logs\", method=\"kafka\")\n",
- "\n",
- "# Fallback: Sample security log stream data\n",
- "security_logs = \"\"\"\n",
- "2024-01-01 10:00:00 - Login attempt from IP 192.168.1.100 user admin\n",
- "2024-01-01 10:01:00 - Failed login from IP 192.168.1.100 user admin\n",
- "2024-01-01 10:02:00 - Multiple failed logins from IP 192.168.1.100 user admin\n",
- "2024-01-01 10:03:00 - Unusual activity detected from IP 192.168.1.100\n",
- "2024-01-01 10:04:00 - Alert: Potential brute force attack from IP 192.168.1.100\n",
- "2024-01-01 10:05:00 - Login attempt from IP 192.168.1.101 user test\n",
- "\"\"\"\n",
- "\n",
- "with open(\"data/security_logs.txt\", \"w\") as f:\n",
- " f.write(security_logs)\n",
- "\n",
- "stream_documents = FileIngestor().ingest(\"data/security_logs.txt\")\n",
- "documents.extend(stream_documents)\n",
- "print(f\"Added {len(stream_documents)} documents from simulated stream\")\n",
- "print(f\"Total documents: {len(documents)}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 2: Text Normalization & Advanced Chunking\n",
- "\n",
- "Normalize log data and use sentence/recursive chunking for structured logs.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.normalize import TextNormalizer\n",
- "from semantica.split import TextSplitter\n",
- "\n",
- "# Normalize log data\n",
- "normalizer = TextNormalizer()\n",
- "normalized_documents = []\n",
- "for doc in documents:\n",
- " normalized_text = normalizer.normalize(\n",
- " doc.content if hasattr(doc, 'content') else str(doc),\n",
- " clean_html=True,\n",
- " normalize_entities=True,\n",
- " remove_extra_whitespace=True\n",
- " )\n",
- " normalized_documents.append(normalized_text)\n",
- "\n",
- "print(f\"Normalized {len(normalized_documents)} documents\")\n",
- "\n",
- "# Use sentence chunking for log line boundaries (structured logs)\n",
- "splitter = TextSplitter(method=\"sentence\", chunk_size=500, chunk_overlap=50)\n",
- "# Alternative: recursive for hierarchical log structures\n",
- "# splitter = TextSplitter(method=\"recursive\", chunk_size=500, chunk_overlap=50)\n",
- "\n",
- "chunked_docs = []\n",
- "for doc_text in normalized_documents:\n",
- " chunks = splitter.split(doc_text)\n",
- " chunked_docs.extend([chunk.content if hasattr(chunk, 'content') else str(chunk) for chunk in chunks])\n",
- "\n",
- "print(f\"Created {len(chunked_docs)} chunks using sentence chunking\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 3-4: Temporal Knowledge Graph Construction\n",
- "\n",
- "Build full temporal KG with TemporalGraphQuery capabilities.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.kg import GraphBuilder, TemporalGraphQuery\n",
- "\n",
- "# Build temporal knowledge graph\n",
- "result = core.build_knowledge_base(\n",
- " sources=chunked_docs,\n",
- " custom_entity_types=[\"Log\", \"Event\", \"IP\", \"User\", \"Alert\", \"Attack\"],\n",
- " graph=True,\n",
- " temporal=True\n",
- ")\n",
- "\n",
- "kg = result[\"knowledge_graph\"]\n",
- "\n",
- "# Initialize temporal graph query engine\n",
- "temporal_query = TemporalGraphQuery(\n",
- " enable_temporal_reasoning=True,\n",
- " temporal_granularity=\"minute\" # Fine-grained for real-time logs\n",
- ")\n",
- "\n",
- "# Query graph at specific time point\n",
- "query_results = temporal_query.query_at_time(\n",
- " kg,\n",
- " query={\"type\": \"Alert\"},\n",
- " at_time=\"2024-01-01 10:04:00\"\n",
- ")\n",
- "\n",
- "# Analyze temporal evolution\n",
- "evolution = temporal_query.analyze_evolution(kg)\n",
- "\n",
- "print(f\"Built temporal KG with {len(kg.get('entities', []))} entities\")\n",
- "print(f\"Temporal queries: {len(query_results)} alerts at query time\")\n",
- "print(\"Focus: Stream processing, temporal KGs, pattern detection\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": []
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.reasoning import GraphReasoner\n",
- "\n",
- "# Detect anomaly patterns (e.g., multiple failed logins)\n",
- "reasoner = GraphReasoner(kg)\n",
- "anomaly_patterns = reasoner.find_patterns(pattern_type=\"anomaly\")\n",
- "\n",
- "# Temporal pattern detection\n",
- "temporal_patterns = temporal_query.detect_temporal_patterns(kg, pattern_type=\"sequence\")\n",
- "\n",
- "# Identify suspicious IPs\n",
- "suspicious_ips = [e for e in kg.get(\"entities\", []) \n",
- " if e.get(\"type\") == \"IP\" and \n",
- " any(\"alert\" in str(r.get(\"predicate\", \"\")).lower() \n",
- " for r in kg.get(\"relationships\", []) \n",
- " if r.get(\"target\") == e.get(\"id\"))]\n",
- "\n",
- "print(f\"Pattern detection: {len(anomaly_patterns)} anomaly patterns found\")\n",
- "print(f\"Temporal patterns: {len(temporal_patterns)} temporal patterns detected\")\n",
- "print(f\"Anomaly detection: {len(suspicious_ips)} suspicious IPs identified\")\n",
- "print(\"This cookbook emphasizes stream processing, temporal KGs, and pattern detection\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 7: Visualization & Alert Generation\n",
- "\n",
- "Visualize temporal knowledge graph with anomaly alerts.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.visualization import KGVisualizer\n",
- "\n",
- "visualizer = KGVisualizer()\n",
- "visualizer.visualize(kg, output_path=\"anomaly_detection_kg.html\", layout=\"temporal\")\n",
- "\n",
- "print(\"Real-time anomaly detection analysis complete\")\n",
- "print(\"\\n=== Pipeline Summary ===\")\n",
- "print(f\"✓ Ingested {len(documents)} documents from CVE RSS feed and stream\")\n",
- "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
- "print(f\"✓ Created {len(chunked_docs)} chunks using sentence chunking\")\n",
- "print(f\"✓ Built temporal KG with {len(kg.get('entities', []))} entities\")\n",
- "print(f\"✓ Detected {len(anomaly_patterns)} anomaly patterns and {len(suspicious_ips)} suspicious IPs\")\n",
- "print(f\"✓ Emphasizes: Stream processing, temporal KGs, pattern detection\")\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Real_Time_Anomaly_Detection.ipynb)\n",
+ "\n",
+ "# Real-Time Anomaly Detection - Stream Processing & Temporal KGs\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **real-time anomaly detection** using Semantica with focus on **stream ingestion**, **temporal knowledge graphs**, and **pattern detection**. The pipeline streams security logs in real-time, builds temporal knowledge graphs, and detects anomalies using pattern detection.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Stream Processing**: Emphasizes real-time log streaming and processing\n",
+ "- **Temporal Knowledge Graphs**: Builds temporal KGs to track events over time\n",
+ "- **Pattern Detection**: Uses graph patterns to identify anomalies\n",
+ "- **Automated Alerting**: Generates alerts for detected anomalies\n",
+ "- **Comprehensive Data Sources**: Multiple security RSS feeds, APIs, and databases\n",
+ "- **Modular Architecture**: Direct use of Semantica modules without core orchestrator\n",
+ "\n",
+ "### Learning Objectives\n",
+ "\n",
+ "- Ingest security data from multiple sources (RSS feeds, APIs, streams)\n",
+ "- Extract security entities (Logs, Events, IPs, Users, Alerts, Attacks)\n",
+ "- Build temporal security knowledge graphs\n",
+ "- Perform temporal queries and pattern detection\n",
+ "- Detect anomalies using graph reasoning\n",
+ "- Store and query security data using vector stores and graph stores\n",
+ "\n",
+ "### Pipeline Flow\n",
+ "\n",
+ "```mermaid\n",
+ "graph TD\n",
+ " A[Data Ingestion] --> B[Document Parsing]\n",
+ " B --> C[Text Processing]\n",
+ " C --> D[Entity Extraction]\n",
+ " D --> E[Relationship Extraction]\n",
+ " E --> F[Deduplication]\n",
+ " F --> G[Conflict Detection]\n",
+ " G --> H[Temporal Knowledge Graph]\n",
+ " H --> I[Embeddings]\n",
+ " I --> J[Vector Store]\n",
+ " H --> K[Temporal Queries]\n",
+ " K --> L[Pattern Detection]\n",
+ " L --> M[Reasoning & Anomaly]\n",
+ " J --> N[GraphRAG Queries]\n",
+ " M --> N\n",
+ " H --> O[Graph Store]\n",
+ " N --> P[Visualization]\n",
+ " O --> P\n",
+ " P --> Q[Export]\n",
+ "```\n",
+ "\n",
+ "### Data Sources\n",
+ "\n",
+ "#### Security RSS Feeds\n",
+ "- **CVE Database**: https://cve.mitre.org/data/downloads/allitems.xml\n",
+ "- **US-CERT Alerts**: https://www.us-cert.gov/ncas/alerts.xml\n",
+ "- **SANS Internet Storm Center**: https://isc.sans.edu/rssfeed.xml\n",
+ "- **Krebs on Security**: https://krebsonsecurity.com/feed/\n",
+ "- **ThreatPost**: https://threatpost.com/feed/\n",
+ "- **BleepingComputer**: https://www.bleepingcomputer.com/feed/\n",
+ "\n",
+ "#### Security APIs\n",
+ "- **CVE API**: https://cve.mitre.org/api/\n",
+ "- **MITRE ATT&CK**: https://attack.mitre.org/\n",
+ "- **VirusTotal API**: https://www.virustotal.com/gui/join-us\n",
+ "- **AbuseIPDB API**: https://www.abuseipdb.com/api\n",
+ "- **Shodan API**: https://www.shodan.io/\n",
+ "- **AlienVault OTX**: https://otx.alienvault.com/api\n",
+ "\n",
+ "#### Stream Sources\n",
+ "- **Kafka Streams**: Real-time log streaming\n",
+ "- **WebSocket Feeds**: Real-time security event feeds\n",
+ "- **Syslog**: System log streams\n",
+ "- **ELK Stack**: Elasticsearch, Logstash, Kibana\n",
+ "\n",
+ "#### Database Links\n",
+ "- **CVE Database**: https://cve.mitre.org/\n",
+ "- **MITRE ATT&CK**: https://attack.mitre.org/\n",
+ "- **NVD (National Vulnerability Database)**: https://nvd.nist.gov/\n",
+ "- **Exploit-DB**: https://www.exploit-db.com/\n",
+ "- **CAPEC (Common Attack Pattern)**: https://capec.mitre.org/\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq sentence-transformers scikit-learn\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Configuration & Setup\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key-here\")\n",
+ "\n",
+ "# Configuration constants\n",
+ "EMBEDDING_DIMENSION = 384\n",
+ "EMBEDDING_MODEL = \"all-MiniLM-L6-v2\"\n",
+ "CHUNK_SIZE = 500\n",
+ "CHUNK_OVERLAP = 50\n",
+ "TEMPORAL_GRANULARITY = \"minute\"\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Ingesting Security Data from Multiple Sources\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, StreamIngestor, FileIngestor\n",
+ "import os\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "feed_sources = [\n",
+ " # Security RSS Feeds\n",
+ " (\"US-CERT Alerts\", \"https://www.us-cert.gov/ncas/alerts.xml\"),\n",
+ " (\"SANS ISC\", \"https://isc.sans.edu/rssfeed.xml\"),\n",
+ " (\"Krebs on Security\", \"https://krebsonsecurity.com/feed/\"),\n",
+ " (\"ThreatPost\", \"https://threatpost.com/feed/\"),\n",
+ " (\"BleepingComputer\", \"https://www.bleepingcomputer.com/feed/\"),\n",
+ "]\n",
+ "\n",
+ "feed_ingestor = FeedIngestor()\n",
+ "all_documents = []\n",
+ "\n",
+ "for feed_name, feed_url in feed_sources:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " feed_data = feed_ingestor.ingest_feed(feed_url, validate=False)\n",
+ " for item in feed_data.items:\n",
+ " if not item.content:\n",
+ " item.content = item.description or item.title or \"\"\n",
+ " if item.content:\n",
+ " if not hasattr(item, 'metadata'):\n",
+ " item.metadata = {}\n",
+ " item.metadata['source'] = feed_name\n",
+ " all_documents.append(item)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "# Simulate stream ingestion (in production, use actual Kafka/WebSocket)\n",
+ "if not all_documents:\n",
+ " security_logs = \"\"\"\n",
+ " 2024-01-01 10:00:00 - Login attempt from IP 192.168.1.100 user admin\n",
+ " 2024-01-01 10:01:00 - Failed login from IP 192.168.1.100 user admin\n",
+ " 2024-01-01 10:02:00 - Multiple failed logins from IP 192.168.1.100 user admin\n",
+ " 2024-01-01 10:03:00 - Unusual activity detected from IP 192.168.1.100\n",
+ " 2024-01-01 10:04:00 - Alert: Potential brute force attack from IP 192.168.1.100\n",
+ " 2024-01-01 10:05:00 - Login attempt from IP 192.168.1.101 user test\n",
+ " 2024-01-01 10:06:00 - Suspicious file access from IP 192.168.1.102\n",
+ " 2024-01-01 10:07:00 - Multiple connection attempts from IP 192.168.1.103\n",
+ " \"\"\"\n",
+ " with open(\"data/security_logs.txt\", \"w\") as f:\n",
+ " f.write(security_logs)\n",
+ " file_ingestor = FileIngestor()\n",
+ " all_documents = file_ingestor.ingest(\"data/security_logs.txt\")\n",
+ "\n",
+ "documents = all_documents\n",
+ "print(f\"Ingested {len(documents)} documents\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.parse import DocumentParser\n",
+ "\n",
+ "parser = DocumentParser()\n",
+ "\n",
+ "parsed_documents = []\n",
+ "for doc in documents:\n",
+ " try:\n",
+ " parsed = parser.parse(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " content_type=\"text\"\n",
+ " )\n",
+ " parsed_documents.append(parsed)\n",
+ " except Exception:\n",
+ " parsed_documents.append(doc)\n",
+ "\n",
+ "documents = parsed_documents\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Normalizing and Chunking Security Logs\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.split import TextSplitter\n",
+ "\n",
+ "normalizer = TextNormalizer()\n",
+ "# Use sentence chunking for log line boundaries (structured logs)\n",
+ "splitter = TextSplitter(method=\"sentence\", chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)\n",
+ "\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True,\n",
+ " lowercase=False\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "chunked_documents = []\n",
+ "for doc_text in normalized_documents:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " chunks = splitter.split(doc_text)\n",
+ " chunked_documents.extend(chunks)\n",
+ " except Exception:\n",
+ " simple_splitter = TextSplitter(method=\"recursive\", chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)\n",
+ " chunks = simple_splitter.split(doc_text)\n",
+ " chunked_documents.extend(chunks)\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Extracting Security Entities\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import NERExtractor\n",
+ "\n",
+ "entity_extractor = NERExtractor(\n",
+ " method=\"llm\",\n",
+ " provider=\"groq\",\n",
+ " llm_model=\"llama-3.1-8b-instant\",\n",
+ " temperature=0.0\n",
+ ")\n",
+ "\n",
+ "all_entities = []\n",
+ "for chunk in chunked_documents:\n",
+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",
+ " try:\n",
+ " entities = entity_extractor.extract_entities(\n",
+ " chunk_text,\n",
+ " entity_types=[\"Log\", \"Event\", \"IP\", \"User\", \"Alert\", \"Attack\"]\n",
+ " )\n",
+ " all_entities.extend(entities)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "ips = [e for e in all_entities if e.label == \"IP\" or \"ip\" in e.label.lower()]\n",
+ "users = [e for e in all_entities if e.label == \"User\" or \"user\" in e.label.lower()]\n",
+ "alerts = [e for e in all_entities if e.label == \"Alert\" or \"alert\" in e.label.lower()]\n",
+ "\n",
+ "print(f\"Extracted {len(ips)} IPs, {len(users)} users, {len(alerts)} alerts\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Extracting Security Relationships\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import RelationExtractor\n",
+ "\n",
+ "relation_extractor = RelationExtractor(\n",
+ " method=\"llm\",\n",
+ " provider=\"groq\",\n",
+ " llm_model=\"llama-3.1-8b-instant\",\n",
+ " temperature=0.0\n",
+ ")\n",
+ "\n",
+ "all_relationships = []\n",
+ "for chunk in chunked_documents:\n",
+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",
+ " try:\n",
+ " relationships = relation_extractor.extract_relations(\n",
+ " chunk_text,\n",
+ " entities=all_entities,\n",
+ " relation_types=[\"from\", \"attempts\", \"triggers\", \"detects\", \"associated_with\", \"causes\"]\n",
+ " )\n",
+ " all_relationships.extend(relationships)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "print(f\"Extracted {len(all_relationships)} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Resolving Duplicate Events\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.deduplication import DuplicateDetector\n",
+ "\n",
+ "duplicate_detector = DuplicateDetector(\n",
+ " similarity_threshold=0.85,\n",
+ " method=\"semantic\"\n",
+ ")\n",
+ "\n",
+ "deduplicated_entities = duplicate_detector.detect_duplicates(all_entities)\n",
+ "merged_entities = duplicate_detector.merge_duplicates(deduplicated_entities)\n",
+ "\n",
+ "print(f\"Deduplicated {len(all_entities)} entities to {len(merged_entities)} unique entities\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Detecting Security Conflicts\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.conflicts import ConflictDetector\n",
+ "\n",
+ "conflict_detector = ConflictDetector()\n",
+ "\n",
+ "conflicts = conflict_detector.detect_conflicts(merged_entities, all_relationships)\n",
+ "\n",
+ "if conflicts:\n",
+ " resolved = conflict_detector.resolve_conflicts(conflicts, strategy=\"highest_confidence\")\n",
+ " print(f\"Detected {len(conflicts)} conflicts, resolved {len(resolved)}\")\n",
+ "else:\n",
+ " print(\"No conflicts detected\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Building Temporal Security Knowledge Graph\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphBuilder\n",
+ "\n",
+ "graph_builder = GraphBuilder(\n",
+ " merge_entities=True,\n",
+ " resolve_conflicts=True,\n",
+ " entity_resolution_strategy=\"fuzzy\",\n",
+ " enable_temporal=True,\n",
+ " temporal_granularity=TEMPORAL_GRANULARITY\n",
+ ")\n",
+ "\n",
+ "kg_sources = [{\n",
+ " \"entities\": [{\"text\": e.text, \"type\": e.label, \"confidence\": e.confidence} for e in merged_entities],\n",
+ " \"relationships\": [{\"source\": r.source, \"target\": r.target, \"type\": r.label, \"confidence\": r.confidence} for r in all_relationships]\n",
+ "}]\n",
+ "\n",
+ "kg = graph_builder.build(kg_sources)\n",
+ "\n",
+ "entities_count = len(kg.get('entities', []))\n",
+ "relationships_count = len(kg.get('relationships', []))\n",
+ "print(f\"Graph: {entities_count} entities, {relationships_count} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Generating Embeddings for Events and IPs\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.embeddings import EmbeddingGenerator\n",
+ "\n",
+ "embedding_gen = EmbeddingGenerator(\n",
+ " provider=\"sentence_transformers\",\n",
+ " model=EMBEDDING_MODEL\n",
+ ")\n",
+ "\n",
+ "event_texts = [f\"{e.text} {getattr(e, 'description', '')}\" for e in all_entities if e.label in [\"Event\", \"Log\", \"Alert\"]]\n",
+ "event_embeddings = embedding_gen.generate_embeddings(event_texts)\n",
+ "\n",
+ "ip_texts = [f\"{ip.text} {getattr(ip, 'description', '')}\" for ip in ips]\n",
+ "ip_embeddings = embedding_gen.generate_embeddings(ip_texts)\n",
+ "\n",
+ "print(f\"Generated {len(event_embeddings)} event embeddings and {len(ip_embeddings)} IP embeddings\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Populating Vector Store\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.vector_store import VectorStore\n",
+ "\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=EMBEDDING_DIMENSION)\n",
+ "\n",
+ "event_ids = vector_store.store_vectors(\n",
+ " vectors=event_embeddings,\n",
+ " metadata=[{\"type\": \"event\", \"name\": e.text, \"label\": e.label} for e in all_entities if e.label in [\"Event\", \"Log\", \"Alert\"]]\n",
+ ")\n",
+ "\n",
+ "ip_ids = vector_store.store_vectors(\n",
+ " vectors=ip_embeddings,\n",
+ " metadata=[{\"type\": \"ip\", \"name\": ip.text, \"label\": ip.label} for ip in ips]\n",
+ ")\n",
+ "\n",
+ "print(f\"Stored {len(event_ids)} event vectors and {len(ip_ids)} IP vectors\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Temporal Graph Queries\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import TemporalGraphQuery\n",
+ "\n",
+ "temporal_query = TemporalGraphQuery(\n",
+ " enable_temporal_reasoning=True,\n",
+ " temporal_granularity=TEMPORAL_GRANULARITY\n",
+ ")\n",
+ "\n",
+ "query_results = temporal_query.query_at_time(\n",
+ " kg,\n",
+ " query={\"type\": \"Alert\"},\n",
+ " at_time=\"2024-01-01 10:04:00\"\n",
+ ")\n",
+ "\n",
+ "evolution = temporal_query.analyze_evolution(kg)\n",
+ "temporal_patterns = temporal_query.detect_temporal_patterns(kg, pattern_type=\"sequence\")\n",
+ "\n",
+ "print(f\"Temporal queries: {len(query_results)} alerts at query time\")\n",
+ "print(f\"Temporal patterns detected: {len(temporal_patterns)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Detecting Anomaly Patterns\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphAnalyzer\n",
+ "\n",
+ "graph_analyzer = GraphAnalyzer()\n",
+ "\n",
+ "# Detect suspicious IPs\n",
+ "suspicious_ips = []\n",
+ "for entity in kg.get(\"entities\", []):\n",
+ " if entity.get(\"type\") == \"IP\":\n",
+ " related_rels = [r for r in kg.get(\"relationships\", []) \n",
+ " if r.get(\"source\") == entity.get(\"id\") or r.get(\"target\") == entity.get(\"id\")]\n",
+ " if any(\"alert\" in str(r.get(\"type\", \"\")).lower() or \"attack\" in str(r.get(\"type\", \"\")).lower() \n",
+ " for r in related_rels):\n",
+ " suspicious_ips.append(entity)\n",
+ "\n",
+ "# Detect anomaly patterns (multiple failed logins, unusual activity)\n",
+ "anomaly_patterns = []\n",
+ "for ip in ips[:10]:\n",
+ " ip_name = ip.text\n",
+ " paths = graph_analyzer.find_paths(\n",
+ " kg,\n",
+ " source=ip_name,\n",
+ " target_type=\"Alert\",\n",
+ " max_hops=2\n",
+ " )\n",
+ " if len(paths) > 0:\n",
+ " anomaly_patterns.append({\n",
+ " 'ip': ip_name,\n",
+ " 'alert_count': len(paths),\n",
+ " 'pattern': 'suspicious_activity'\n",
+ " })\n",
+ "\n",
+ "print(f\"Pattern detection: {len(anomaly_patterns)} anomaly patterns found\")\n",
+ "print(f\"Suspicious IPs: {len(suspicious_ips)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Reasoning and Anomaly Detection\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.reasoning import Reasoner\n",
+ "\n",
+ "reasoner = Reasoner()\n",
+ "\n",
+ "reasoner.add_rule(\"IF IP attempts Event AND Event type failed_login AND Event count > 3 THEN IP triggers Alert\")\n",
+ "reasoner.add_rule(\"IF User from IP AND IP triggers Alert THEN User associated_with Alert\")\n",
+ "\n",
+ "inferred_facts = reasoner.infer_facts(kg)\n",
+ "\n",
+ "anomaly_paths = reasoner.find_paths(\n",
+ " kg,\n",
+ " source_type=\"IP\",\n",
+ " target_type=\"Alert\",\n",
+ " max_hops=2\n",
+ ")\n",
+ "\n",
+ "print(f\"Inferred {len(inferred_facts)} facts\")\n",
+ "print(f\"Found {len(anomaly_paths)} anomaly paths\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Storing Security Knowledge Graph (Optional)\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.graph_store import GraphStore\n",
+ "\n",
+ "# Optional: Store to persistent graph database\n",
+ "# graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",
+ "# graph_store.store_graph(kg)\n",
+ "\n",
+ "print(\"Graph store configured (commented out for demo)\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## GraphRAG: Hybrid Vector + Graph Queries\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.context import AgentContext\n",
+ "\n",
+ "context = AgentContext(vector_store=vector_store, knowledge_graph=kg)\n",
+ "\n",
+ "query = \"What IPs are associated with security alerts?\"\n",
+ "results = context.retrieve(\n",
+ " query,\n",
+ " max_results=10,\n",
+ " use_graph=True,\n",
+ " expand_graph=True,\n",
+ " include_entities=True,\n",
+ " include_relationships=True\n",
+ ")\n",
+ "\n",
+ "print(f\"GraphRAG query: '{query}'\")\n",
+ "print(f\"\\nRetrieved {len(results)} results:\\n\")\n",
+ "for i, result in enumerate(results[:5], 1):\n",
+ " print(f\"{i}. Score: {result.get('score', 0):.3f}\")\n",
+ " print(f\" Content: {result.get('content', '')[:200]}...\")\n",
+ " if result.get('related_entities'):\n",
+ " print(f\" Related entities: {len(result['related_entities'])}\")\n",
+ " print()\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Visualizing the Temporal Security Knowledge Graph\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(\n",
+ " kg,\n",
+ " output_path=\"anomaly_detection_kg.html\",\n",
+ " layout=\"temporal\",\n",
+ " node_size=20\n",
+ ")\n",
+ "\n",
+ "print(\"Visualization saved to anomaly_detection_kg.html\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Exporting Results\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.export import GraphExporter\n",
+ "\n",
+ "exporter = GraphExporter()\n",
+ "exporter.export(kg, output_path=\"anomaly_detection_kg.json\", format=\"json\")\n",
+ "exporter.export(kg, output_path=\"anomaly_detection_kg.graphml\", format=\"graphml\")\n",
+ "exporter.export(kg, output_path=\"anomaly_detection_alerts.csv\", format=\"csv\")\n",
+ "\n",
+ "print(\"Exported knowledge graph to JSON, GraphML, and CSV formats\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
}
diff --git a/cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb b/cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb
index 6addff70..42bbf7ab 100644
--- a/cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb
+++ b/cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb
@@ -1,361 +1,712 @@
{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb)\n",
- "\n",
- "# Threat Intelligence Hybrid RAG - Vector + Graph Retrieval\n",
- "\n",
- "## Overview\n",
- "\n",
- "This notebook demonstrates **threat intelligence hybrid RAG** using Semantica with focus on **hybrid search**, **vector + graph retrieval**, and **context-aware queries**. The pipeline combines vector search with temporal knowledge graphs for advanced threat intelligence querying.\n",
- "\n",
- "### Key Features\n",
- "\n",
- "- **Hybrid RAG**: Combines vector similarity search with knowledge graph traversal\n",
- "- **Vector + Graph Retrieval**: Uses both vector embeddings and graph relationships\n",
- "- **Context-Aware Queries**: Provides context-aware retrieval for threat intelligence\n",
- "- **Temporal Knowledge Graphs**: Builds temporal KGs for threat timeline analysis\n",
- "- **Multi-hop Reasoning**: Follows relationships across the graph for deeper context\n",
- "\n",
- "### Pipeline Architecture\n",
- "\n",
- "1. **Phase 0**: Setup & Configuration\n",
- "2. **Phase 1**: Threat Intelligence Data Ingestion\n",
- "3. **Phase 2**: Entity Extraction (IOC, Campaign, Threat, Actor, TTP)\n",
- "4. **Phase 3**: Temporal Knowledge Graph Construction\n",
- "5. **Phase 4**: Embedding Generation & Vector Store\n",
- "6. **Phase 5**: Hybrid Search Setup (Vector + Graph)\n",
- "7. **Phase 6**: Context-Aware Query System\n",
- "8. **Phase 7**: Visualization & Export\n",
- "\n",
- "---\n",
- "\n",
- "## Installation\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu groq sentence-transformers\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 0: Setup & Configuration\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import os\n",
- "from semantica.core import Semantica, ConfigManager\n",
- "from semantica.vector_store import VectorStore\n",
- "from semantica.context import AgentContext\n",
- "\n",
- "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
- "\n",
- "config_dict = {\n",
- " \"project_name\": \"Threat_Intelligence_Hybrid_RAG\",\n",
- " \"embedding\": {\"provider\": \"sentence_transformers\", \"model\": \"all-MiniLM-L6-v2\"},\n",
- " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
- " \"vector_store\": {\"provider\": \"faiss\", \"dimension\": 384},\n",
- " \"knowledge_graph\": {\"backend\": \"networkx\", \"temporal\": True}\n",
- "}\n",
- "\n",
- "config = ConfigManager().load_from_dict(config_dict)\n",
- "core = Semantica(config=config)\n",
- "vector_store = VectorStore(backend=\"faiss\", dimension=384)\n",
- "print(\"Configured for threat intelligence hybrid RAG\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 1: Real Data Ingestion (Security RSS Feeds)\n",
- "\n",
- "Ingest threat intelligence data from multiple security RSS feeds.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.ingest import FeedIngestor, FileIngestor\n",
- "import os\n",
- "\n",
- "os.makedirs(\"data\", exist_ok=True)\n",
- "\n",
- "# Ingest from multiple security RSS feeds (real data sources)\n",
- "security_feeds = [\n",
- " \"https://www.us-cert.gov/ncas/alerts.xml\", # US-CERT alerts\n",
- " # Add more security feeds as needed\n",
- "]\n",
- "\n",
- "documents = []\n",
- "for feed_url in security_feeds:\n",
- " try:\n",
- " feed_ingestor = FeedIngestor()\n",
- " feed_documents = feed_ingestor.ingest(feed_url, method=\"rss\")\n",
- " print(f\"Ingested {len(feed_documents)} documents from {feed_url}\")\n",
- " documents.extend(feed_documents)\n",
- " except Exception as e:\n",
- " print(f\"Feed ingestion failed for {feed_url}: {e}\")\n",
- "\n",
- "# Fallback: Sample threat intelligence data\n",
- "if not documents:\n",
- " threat_data = \"\"\"\n",
- " IOC: IP address 192.168.1.50 associated with APT28 campaign.\n",
- " Threat actor APT28 uses TTP: Spear phishing and credential harvesting.\n",
- " Campaign Operation GhostShell targets financial institutions.\n",
- " Malware sample hash: abc123def456 linked to APT28 infrastructure.\n",
- " IOC: Domain example-malicious.com linked to APT29 operations.\n",
- " \"\"\"\n",
- " with open(\"data/threat_intel.txt\", \"w\") as f:\n",
- " f.write(threat_data)\n",
- " documents = FileIngestor().ingest(\"data/threat_intel.txt\")\n",
- " print(f\"Ingested {len(documents)} documents from sample data\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 2: Text Normalization & Advanced Chunking\n",
- "\n",
- "Normalize IOC data and use entity-aware/relation-aware chunking for threat relationships.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.normalize import TextNormalizer\n",
- "from semantica.split import TextSplitter, EntityAwareChunker, RelationAwareChunker\n",
- "from semantica.deduplication import DuplicateDetector\n",
- "\n",
- "# Normalize IOC data and threat intelligence\n",
- "normalizer = TextNormalizer()\n",
- "normalized_documents = []\n",
- "for doc in documents:\n",
- " normalized_text = normalizer.normalize(\n",
- " doc.content if hasattr(doc, 'content') else str(doc),\n",
- " clean_html=True,\n",
- " normalize_entities=True,\n",
- " remove_extra_whitespace=True\n",
- " )\n",
- " normalized_documents.append(normalized_text)\n",
- "\n",
- "print(f\"Normalized {len(normalized_documents)} documents\")\n",
- "\n",
- "# Use entity-aware chunking to preserve threat entity boundaries for GraphRAG\n",
- "entity_splitter = TextSplitter(\n",
- " method=\"entity_aware\",\n",
- " ner_method=\"llm\",\n",
- " chunk_size=1000,\n",
- " chunk_overlap=200\n",
- ")\n",
- "\n",
- "# Alternative: relation-aware chunking to preserve threat relationship triplets\n",
- "relation_splitter = TextSplitter(\n",
- " method=\"relation_aware\",\n",
- " chunk_size=1000,\n",
- " chunk_overlap=200\n",
- ")\n",
- "\n",
- "# Chunk with entity-aware (preserves IOC, Actor, Campaign boundaries)\n",
- "chunked_docs = []\n",
- "for doc_text in normalized_documents:\n",
- " chunks = entity_splitter.split(doc_text)\n",
- " chunked_docs.extend([chunk.content if hasattr(chunk, 'content') else str(chunk) for chunk in chunks])\n",
- "\n",
- "print(f\"Created {len(chunked_docs)} entity-aware chunks\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 3: Knowledge Graph Construction & Deduplication\n",
- "\n",
- "Build temporal knowledge graph and deduplicate threat entities.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Build knowledge base with both vectors and graph\n",
- "result = core.build_knowledge_base(\n",
- " sources=chunked_docs,\n",
- " custom_entity_types=[\"IOC\", \"Campaign\", \"Threat\", \"Actor\", \"TTP\", \"Malware\"],\n",
- " embeddings=True,\n",
- " graph=True,\n",
- " temporal=True\n",
- ")\n",
- "\n",
- "kg = result[\"knowledge_graph\"]\n",
- "entities = result[\"entities\"]\n",
- "embeddings_data = result[\"embeddings\"]\n",
- "\n",
- "# Deduplicate threat entities (IOCs, actors, campaigns)\n",
- "iocs = [e for e in entities if e.get(\"type\") == \"IOC\" or \"ioc\" in e.get(\"type\", \"\").lower()]\n",
- "actors = [e for e in entities if e.get(\"type\") == \"Actor\" or \"actor\" in e.get(\"type\", \"\").lower()]\n",
- "\n",
- "detector = DuplicateDetector()\n",
- "ioc_duplicates = detector.detect_duplicates(iocs, threshold=0.9)\n",
- "actor_duplicates = detector.detect_duplicates(actors, threshold=0.9)\n",
- "\n",
- "deduplicated_iocs = detector.resolve_duplicates(iocs, ioc_duplicates)\n",
- "deduplicated_actors = detector.resolve_duplicates(actors, actor_duplicates)\n",
- "\n",
- "print(f\"Built hybrid system: {len(kg.get('entities', []))} entities, {len(embeddings_data['vectors'])} vectors\")\n",
- "print(f\"Deduplicated: {len(iocs)} -> {len(deduplicated_iocs)} unique IOCs\")\n",
- "print(f\"Deduplicated: {len(actors)} -> {len(deduplicated_actors)} unique actors\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 4: Vector Store Population\n",
- "\n",
- "Store embeddings in vector store for hybrid retrieval.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Store embeddings in vector store\n",
- "vector_store.store_vectors(\n",
- " vectors=embeddings_data[\"vectors\"],\n",
- " metadata=embeddings_data[\"metadata\"]\n",
- ")\n",
- "\n",
- "print(f\"Stored {len(embeddings_data['vectors'])} embeddings in vector store\")\n",
- "print(\"Focus: Hybrid RAG, vector + graph retrieval, context-aware queries\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": []
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.context import AgentContext\n",
- "from semantica.embeddings import EmbeddingGenerator\n",
- "\n",
- "# Initialize enhanced GraphRAG context\n",
- "context = AgentContext(vector_store=vector_store, knowledge_graph=kg)\n",
- "\n",
- "# Example hybrid query\n",
- "query = \"What threats are associated with APT28?\"\n",
- "print(f\"Query: {query}\\n\")\n",
- "\n",
- "# Generate query embedding\n",
- "embedding_gen = EmbeddingGenerator(provider=\"sentence_transformers\", model=\"all-MiniLM-L6-v2\")\n",
- "query_embedding = embedding_gen.generate_embeddings([query])[0]\n",
- "\n",
- "# Vector search\n",
- "vector_results = vector_store.search_vectors(query_embedding, k=5)\n",
- "\n",
- "# Enhanced GraphRAG retrieval with graph expansion\n",
- "graph_context = context.retrieve(\n",
- " query,\n",
- " max_results=10,\n",
- " use_graph=True, # Enable graph traversal\n",
- " expand_graph=True, # Expand graph relationships\n",
- " include_entities=True, # Include related entities\n",
- " include_relationships=True # Include relationships\n",
- ")\n",
- "\n",
- "print(f\"Hybrid RAG results:\")\n",
- "print(f\" - Vector search: {len(vector_results)} matches\")\n",
- "print(f\" - GraphRAG retrieval: {len(graph_context)} context items with graph expansion\")\n",
- "print(f\"\\nTop GraphRAG results:\")\n",
- "for i, result in enumerate(graph_context[:3], 1):\n",
- " print(f\"{i}. Score: {result.get('score', 0):.3f}\")\n",
- " print(f\" Content: {result.get('content', '')[:150]}...\")\n",
- " if result.get('related_entities'):\n",
- " print(f\" Related entities: {len(result['related_entities'])}\")\n",
- "print(\"\\nThis cookbook emphasizes enhanced GraphRAG with entity-aware chunking and deduplication\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 7: Visualization & Summary\n",
- "\n",
- "Visualize threat intelligence knowledge graph.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.visualization import KGVisualizer\n",
- "\n",
- "visualizer = KGVisualizer()\n",
- "visualizer.visualize(kg, output_path=\"threat_intelligence_kg.html\")\n",
- "\n",
- "print(\"Threat intelligence hybrid RAG analysis complete\")\n",
- "print(\"\\n=== Pipeline Summary ===\")\n",
- "print(f\"✓ Ingested {len(documents)} documents from security RSS feeds\")\n",
- "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
- "print(f\"✓ Created {len(chunked_docs)} entity-aware chunks\")\n",
- "print(f\"✓ Deduplicated IOCs and actors\")\n",
- "print(f\"✓ Built temporal KG with {len(kg.get('entities', []))} entities\")\n",
- "print(f\"✓ Stored {len(embeddings_data['vectors'])} embeddings\")\n",
- "print(f\"✓ Enhanced GraphRAG with graph expansion enabled\")\n",
- "print(f\"✓ Emphasizes: Hybrid RAG, entity-aware chunking, vector + graph retrieval, context-aware queries\")\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/02_Threat_Intelligence_Hybrid_RAG.ipynb)\n",
+ "\n",
+ "# Threat Intelligence Hybrid RAG - Vector + Graph Retrieval\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **threat intelligence hybrid RAG** using Semantica with focus on **hybrid search**, **vector + graph retrieval**, and **context-aware queries**. The pipeline combines vector search with temporal knowledge graphs for advanced threat intelligence querying.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Hybrid RAG**: Combines vector similarity search with knowledge graph traversal\n",
+ "- **Vector + Graph Retrieval**: Uses both vector embeddings and graph relationships\n",
+ "- **Context-Aware Queries**: Provides context-aware retrieval for threat intelligence\n",
+ "- **Temporal Knowledge Graphs**: Builds temporal KGs for threat timeline analysis\n",
+ "- **Multi-hop Reasoning**: Follows relationships across the graph for deeper context\n",
+ "- **Comprehensive Data Sources**: Multiple threat intelligence feeds, APIs, and databases\n",
+ "- **Modular Architecture**: Direct use of Semantica modules without core orchestrator\n",
+ "\n",
+ "### Learning Objectives\n",
+ "\n",
+ "- Ingest threat intelligence data from multiple sources\n",
+ "- Extract threat entities (IOCs, Campaigns, Threats, Actors, TTPs, Malware)\n",
+ "- Build temporal threat intelligence knowledge graphs\n",
+ "- Generate embeddings and populate vector stores\n",
+ "- Perform hybrid vector + graph queries\n",
+ "- Analyze threat networks using graph analytics\n",
+ "- Store and query threat intelligence using vector stores and graph stores\n",
+ "\n",
+ "### Pipeline Flow\n",
+ "\n",
+ "```mermaid\n",
+ "graph TD\n",
+ " A[Data Ingestion] --> B[Document Parsing]\n",
+ " B --> C[Text Processing]\n",
+ " C --> D[Entity Extraction]\n",
+ " D --> E[Relationship Extraction]\n",
+ " E --> F[Deduplication]\n",
+ " F --> G[Conflict Detection]\n",
+ " G --> H[Temporal Knowledge Graph]\n",
+ " H --> I[Embeddings]\n",
+ " I --> J[Vector Store]\n",
+ " H --> K[Temporal Queries]\n",
+ " K --> L[Graph Analytics]\n",
+ " L --> M[GraphRAG Queries]\n",
+ " J --> M\n",
+ " H --> N[Reasoning & Threat]\n",
+ " M --> O[Visualization]\n",
+ " N --> O\n",
+ " H --> P[Graph Store]\n",
+ " P --> O\n",
+ " O --> Q[Export]\n",
+ "```\n",
+ "\n",
+ "### Data Sources\n",
+ "\n",
+ "#### Threat Intelligence RSS Feeds\n",
+ "- **US-CERT Alerts**: https://www.us-cert.gov/ncas/alerts.xml\n",
+ "- **SANS Internet Storm Center**: https://isc.sans.edu/rssfeed.xml\n",
+ "- **Krebs on Security**: https://krebsonsecurity.com/feed/\n",
+ "- **ThreatPost**: https://threatpost.com/feed/\n",
+ "- **BleepingComputer**: https://www.bleepingcomputer.com/feed/\n",
+ "- **SecurityWeek**: https://www.securityweek.com/rss\n",
+ "\n",
+ "#### Threat Intelligence APIs\n",
+ "- **MITRE ATT&CK**: https://attack.mitre.org/\n",
+ "- **VirusTotal API**: https://www.virustotal.com/gui/join-us\n",
+ "- **AbuseIPDB API**: https://www.abuseipdb.com/api\n",
+ "- **AlienVault OTX**: https://otx.alienvault.com/api\n",
+ "- **Shodan API**: https://www.shodan.io/\n",
+ "- **ThreatCrowd API**: https://www.threatcrowd.org/\n",
+ "\n",
+ "#### IOC Sources\n",
+ "- **MISP (Malware Information Sharing Platform)**: https://www.misp-project.org/\n",
+ "- **OpenCTI**: https://www.opencti.io/\n",
+ "- **ThreatFox**: https://threatfox.abuse.ch/\n",
+ "- **URLhaus**: https://urlhaus.abuse.ch/\n",
+ "\n",
+ "#### Database Links\n",
+ "- **MITRE ATT&CK**: https://attack.mitre.org/\n",
+ "- **CVE Database**: https://cve.mitre.org/\n",
+ "- **NVD (National Vulnerability Database)**: https://nvd.nist.gov/\n",
+ "- **Exploit-DB**: https://www.exploit-db.com/\n",
+ "- **CAPEC (Common Attack Pattern)**: https://capec.mitre.org/\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq sentence-transformers scikit-learn\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Configuration & Setup\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key-here\")\n",
+ "\n",
+ "# Configuration constants\n",
+ "EMBEDDING_DIMENSION = 384\n",
+ "EMBEDDING_MODEL = \"all-MiniLM-L6-v2\"\n",
+ "CHUNK_SIZE = 1000\n",
+ "CHUNK_OVERLAP = 200\n",
+ "TEMPORAL_GRANULARITY = \"day\"\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Ingesting Threat Intelligence Data\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, WebIngestor, FileIngestor\n",
+ "import os\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "feed_sources = [\n",
+ " # Threat Intelligence RSS Feeds\n",
+ " (\"US-CERT Alerts\", \"https://www.us-cert.gov/ncas/alerts.xml\"),\n",
+ " (\"SANS ISC\", \"https://isc.sans.edu/rssfeed.xml\"),\n",
+ " (\"Krebs on Security\", \"https://krebsonsecurity.com/feed/\"),\n",
+ " (\"ThreatPost\", \"https://threatpost.com/feed/\"),\n",
+ " (\"BleepingComputer\", \"https://www.bleepingcomputer.com/feed/\"),\n",
+ " (\"SecurityWeek\", \"https://www.securityweek.com/rss\"),\n",
+ "]\n",
+ "\n",
+ "feed_ingestor = FeedIngestor()\n",
+ "all_documents = []\n",
+ "\n",
+ "for feed_name, feed_url in feed_sources:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " feed_data = feed_ingestor.ingest_feed(feed_url, validate=False)\n",
+ " for item in feed_data.items:\n",
+ " if not item.content:\n",
+ " item.content = item.description or item.title or \"\"\n",
+ " if item.content:\n",
+ " if not hasattr(item, 'metadata'):\n",
+ " item.metadata = {}\n",
+ " item.metadata['source'] = feed_name\n",
+ " all_documents.append(item)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "if not all_documents:\n",
+ " threat_data = \"\"\"\n",
+ " IOC: IP address 192.168.1.50 associated with APT28 campaign.\n",
+ " Threat actor APT28 uses TTP: Spear phishing and credential harvesting.\n",
+ " Campaign Operation GhostShell targets financial institutions.\n",
+ " Malware sample hash: abc123def456 linked to APT28 infrastructure.\n",
+ " IOC: Domain example-malicious.com linked to APT29 operations.\n",
+ " Threat actor APT29 uses TTP: Watering hole attacks and lateral movement.\n",
+ " Campaign Operation SolarWinds targets technology companies.\n",
+ " IOC: File hash xyz789ghi012 associated with ransomware group.\n",
+ " \"\"\"\n",
+ " with open(\"data/threat_intel.txt\", \"w\") as f:\n",
+ " f.write(threat_data)\n",
+ " file_ingestor = FileIngestor()\n",
+ " all_documents = file_ingestor.ingest(\"data/threat_intel.txt\")\n",
+ "\n",
+ "documents = all_documents\n",
+ "print(f\"Ingested {len(documents)} documents\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Parsing Threat Intelligence Documents\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.parse import DocumentParser\n",
+ "\n",
+ "parser = DocumentParser()\n",
+ "\n",
+ "parsed_documents = []\n",
+ "for doc in documents:\n",
+ " try:\n",
+ " parsed = parser.parse(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " content_type=\"text\"\n",
+ " )\n",
+ " parsed_documents.append(parsed)\n",
+ " except Exception:\n",
+ " parsed_documents.append(doc)\n",
+ "\n",
+ "documents = parsed_documents\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Normalizing and Chunking Threat Intelligence Data\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.split import TextSplitter\n",
+ "\n",
+ "normalizer = TextNormalizer()\n",
+ "# Use entity-aware chunking to preserve threat entity boundaries for GraphRAG\n",
+ "splitter = TextSplitter(\n",
+ " method=\"entity_aware\",\n",
+ " ner_method=\"spacy\",\n",
+ " chunk_size=CHUNK_SIZE,\n",
+ " chunk_overlap=CHUNK_OVERLAP\n",
+ ")\n",
+ "\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True,\n",
+ " lowercase=False\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "chunked_documents = []\n",
+ "for doc_text in normalized_documents:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " chunks = splitter.split(doc_text)\n",
+ " chunked_documents.extend(chunks)\n",
+ " except Exception:\n",
+ " simple_splitter = TextSplitter(method=\"recursive\", chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)\n",
+ " chunks = simple_splitter.split(doc_text)\n",
+ " chunked_documents.extend(chunks)\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import NERExtractor\n",
+ "\n",
+ "entity_extractor = NERExtractor(\n",
+ " method=\"llm\",\n",
+ " provider=\"groq\",\n",
+ " llm_model=\"llama-3.1-8b-instant\",\n",
+ " temperature=0.0\n",
+ ")\n",
+ "\n",
+ "all_entities = []\n",
+ "for chunk in chunked_documents:\n",
+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",
+ " try:\n",
+ " entities = entity_extractor.extract_entities(\n",
+ " chunk_text,\n",
+ " entity_types=[\"IOC\", \"Campaign\", \"Threat\", \"Actor\", \"TTP\", \"Malware\"]\n",
+ " )\n",
+ " all_entities.extend(entities)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "iocs = [e for e in all_entities if e.label == \"IOC\" or \"ioc\" in e.label.lower()]\n",
+ "actors = [e for e in all_entities if e.label == \"Actor\" or \"actor\" in e.label.lower()]\n",
+ "campaigns = [e for e in all_entities if e.label == \"Campaign\" or \"campaign\" in e.label.lower()]\n",
+ "ttps = [e for e in all_entities if e.label == \"TTP\" or \"ttp\" in e.label.lower()]\n",
+ "\n",
+ "print(f\"Extracted {len(iocs)} IOCs, {len(actors)} actors, {len(campaigns)} campaigns, {len(ttps)} TTPs\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Extracting Threat Relationships\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import RelationExtractor\n",
+ "\n",
+ "relation_extractor = RelationExtractor(\n",
+ " method=\"llm\",\n",
+ " provider=\"groq\",\n",
+ " llm_model=\"llama-3.1-8b-instant\",\n",
+ " temperature=0.0\n",
+ ")\n",
+ "\n",
+ "all_relationships = []\n",
+ "for chunk in chunked_documents:\n",
+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",
+ " try:\n",
+ " relationships = relation_extractor.extract_relations(\n",
+ " chunk_text,\n",
+ " entities=all_entities,\n",
+ " relation_types=[\"associated_with\", \"uses\", \"targets\", \"linked_to\", \"part_of\", \"employs\"]\n",
+ " )\n",
+ " all_relationships.extend(relationships)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "print(f\"Extracted {len(all_relationships)} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Resolving Duplicate IOCs and Actors\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.deduplication import DuplicateDetector\n",
+ "\n",
+ "duplicate_detector = DuplicateDetector(\n",
+ " similarity_threshold=0.85,\n",
+ " method=\"semantic\"\n",
+ ")\n",
+ "\n",
+ "deduplicated_entities = duplicate_detector.detect_duplicates(all_entities)\n",
+ "merged_entities = duplicate_detector.merge_duplicates(deduplicated_entities)\n",
+ "\n",
+ "print(f\"Deduplicated {len(all_entities)} entities to {len(merged_entities)} unique entities\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Detecting Threat Intelligence Conflicts\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.conflicts import ConflictDetector\n",
+ "\n",
+ "conflict_detector = ConflictDetector()\n",
+ "\n",
+ "conflicts = conflict_detector.detect_conflicts(merged_entities, all_relationships)\n",
+ "\n",
+ "if conflicts:\n",
+ " resolved = conflict_detector.resolve_conflicts(conflicts, strategy=\"highest_confidence\")\n",
+ " print(f\"Detected {len(conflicts)} conflicts, resolved {len(resolved)}\")\n",
+ "else:\n",
+ " print(\"No conflicts detected\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Building Temporal Threat Intelligence Knowledge Graph\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphBuilder\n",
+ "\n",
+ "graph_builder = GraphBuilder(\n",
+ " merge_entities=True,\n",
+ " resolve_conflicts=True,\n",
+ " entity_resolution_strategy=\"fuzzy\",\n",
+ " enable_temporal=True,\n",
+ " temporal_granularity=TEMPORAL_GRANULARITY\n",
+ ")\n",
+ "\n",
+ "kg_sources = [{\n",
+ " \"entities\": [{\"text\": e.text, \"type\": e.label, \"confidence\": e.confidence} for e in merged_entities],\n",
+ " \"relationships\": [{\"source\": r.source, \"target\": r.target, \"type\": r.label, \"confidence\": r.confidence} for r in all_relationships]\n",
+ "}]\n",
+ "\n",
+ "kg = graph_builder.build(kg_sources)\n",
+ "\n",
+ "entities_count = len(kg.get('entities', []))\n",
+ "relationships_count = len(kg.get('relationships', []))\n",
+ "print(f\"Graph: {entities_count} entities, {relationships_count} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Generating Embeddings for IOCs and Threats\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.embeddings import EmbeddingGenerator\n",
+ "\n",
+ "embedding_gen = EmbeddingGenerator(\n",
+ " provider=\"sentence_transformers\",\n",
+ " model=EMBEDDING_MODEL\n",
+ ")\n",
+ "\n",
+ "ioc_texts = [f\"{ioc.text} {getattr(ioc, 'description', '')}\" for ioc in iocs]\n",
+ "ioc_embeddings = embedding_gen.generate_embeddings(ioc_texts)\n",
+ "\n",
+ "actor_texts = [f\"{actor.text} {getattr(actor, 'description', '')}\" for actor in actors]\n",
+ "actor_embeddings = embedding_gen.generate_embeddings(actor_texts)\n",
+ "\n",
+ "print(f\"Generated {len(ioc_embeddings)} IOC embeddings and {len(actor_embeddings)} actor embeddings\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Populating Vector Store\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.vector_store import VectorStore\n",
+ "\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=EMBEDDING_DIMENSION)\n",
+ "\n",
+ "ioc_ids = vector_store.store_vectors(\n",
+ " vectors=ioc_embeddings,\n",
+ " metadata=[{\"type\": \"ioc\", \"name\": ioc.text, \"label\": ioc.label} for ioc in iocs]\n",
+ ")\n",
+ "\n",
+ "actor_ids = vector_store.store_vectors(\n",
+ " vectors=actor_embeddings,\n",
+ " metadata=[{\"type\": \"actor\", \"name\": actor.text, \"label\": actor.label} for actor in actors]\n",
+ ")\n",
+ "\n",
+ "print(f\"Stored {len(ioc_ids)} IOC vectors and {len(actor_ids)} actor vectors\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Temporal Graph Queries\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import TemporalGraphQuery\n",
+ "\n",
+ "temporal_query = TemporalGraphQuery(\n",
+ " enable_temporal_reasoning=True,\n",
+ " temporal_granularity=TEMPORAL_GRANULARITY\n",
+ ")\n",
+ "\n",
+ "query_results = temporal_query.query_at_time(\n",
+ " kg,\n",
+ " query={\"type\": \"Campaign\"},\n",
+ " at_time=\"2024-01-01\"\n",
+ ")\n",
+ "\n",
+ "evolution = temporal_query.analyze_evolution(kg)\n",
+ "temporal_patterns = temporal_query.detect_temporal_patterns(kg, pattern_type=\"sequence\")\n",
+ "\n",
+ "print(f\"Temporal queries: {len(query_results)} campaigns at query time\")\n",
+ "print(f\"Temporal patterns detected: {len(temporal_patterns)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Analyzing Threat Network Structure\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
+ "\n",
+ "graph_analyzer = GraphAnalyzer()\n",
+ "centrality_calc = CentralityCalculator()\n",
+ "community_detector = CommunityDetector()\n",
+ "\n",
+ "analysis = graph_analyzer.analyze_graph(kg)\n",
+ "\n",
+ "degree_centrality = centrality_calc.calculate_degree_centrality(kg)\n",
+ "betweenness_centrality = centrality_calc.calculate_betweenness_centrality(kg)\n",
+ "\n",
+ "communities = community_detector.detect_communities(kg, method=\"louvain\")\n",
+ "connectivity = graph_analyzer.analyze_connectivity(kg)\n",
+ "\n",
+ "print(f\"Graph analytics:\")\n",
+ "print(f\" - Communities: {len(communities)}\")\n",
+ "print(f\" - Connected components: {len(connectivity.get('components', []))}\")\n",
+ "print(f\" - Graph density: {analysis.get('density', 0):.3f}\")\n",
+ "print(f\" - Central nodes (degree): {len(degree_centrality)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## GraphRAG: Hybrid Vector + Graph Queries\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.context import AgentContext\n",
+ "\n",
+ "context = AgentContext(vector_store=vector_store, knowledge_graph=kg)\n",
+ "\n",
+ "query = \"What threats are associated with APT28?\"\n",
+ "results = context.retrieve(\n",
+ " query,\n",
+ " max_results=10,\n",
+ " use_graph=True,\n",
+ " expand_graph=True,\n",
+ " include_entities=True,\n",
+ " include_relationships=True\n",
+ ")\n",
+ "\n",
+ "print(f\"GraphRAG query: '{query}'\")\n",
+ "print(f\"\\nRetrieved {len(results)} results:\\n\")\n",
+ "for i, result in enumerate(results[:5], 1):\n",
+ " print(f\"{i}. Score: {result.get('score', 0):.3f}\")\n",
+ " print(f\" Content: {result.get('content', '')[:200]}...\")\n",
+ " if result.get('related_entities'):\n",
+ " print(f\" Related entities: {len(result['related_entities'])}\")\n",
+ " print()\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Reasoning and Threat Analysis\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.reasoning import Reasoner\n",
+ "\n",
+ "reasoner = Reasoner()\n",
+ "\n",
+ "reasoner.add_rule(\"IF IOC associated_with Campaign AND Campaign uses TTP THEN IOC linked_to TTP\")\n",
+ "reasoner.add_rule(\"IF Actor uses TTP AND TTP targets Campaign THEN Actor part_of Campaign\")\n",
+ "\n",
+ "inferred_facts = reasoner.infer_facts(kg)\n",
+ "\n",
+ "threat_paths = reasoner.find_paths(\n",
+ " kg,\n",
+ " source_type=\"Actor\",\n",
+ " target_type=\"IOC\",\n",
+ " max_hops=3\n",
+ ")\n",
+ "\n",
+ "print(f\"Inferred {len(inferred_facts)} facts\")\n",
+ "print(f\"Found {len(threat_paths)} threat paths\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Storing Threat Intelligence Graph (Optional)\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.graph_store import GraphStore\n",
+ "\n",
+ "# Optional: Store to persistent graph database\n",
+ "# graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",
+ "# graph_store.store_graph(kg)\n",
+ "\n",
+ "print(\"Graph store configured (commented out for demo)\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Visualizing the Threat Intelligence Knowledge Graph\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(\n",
+ " kg,\n",
+ " output_path=\"threat_intelligence_kg.html\",\n",
+ " layout=\"spring\",\n",
+ " node_size=20\n",
+ ")\n",
+ "\n",
+ "print(\"Visualization saved to threat_intelligence_kg.html\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Exporting Results\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.export import GraphExporter\n",
+ "\n",
+ "exporter = GraphExporter()\n",
+ "exporter.export(kg, output_path=\"threat_intelligence_kg.json\", format=\"json\")\n",
+ "exporter.export(kg, output_path=\"threat_intelligence_kg.graphml\", format=\"graphml\")\n",
+ "exporter.export(kg, output_path=\"threat_intelligence_iocs.csv\", format=\"csv\")\n",
+ "\n",
+ "print(\"Exported threat intelligence knowledge graph to JSON, GraphML, and CSV formats\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
}