Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
Fix bugs in Ingestion module and update Data Ingestion cookbook
KaifAhmad12f9ad467f060
diff --git a/cookbook/introduction/02_Data_Ingestion.ipynb b/cookbook/introduction/02_Data_Ingestion.ipynbindex ee4020ff..f95a5204 100644--- a/cookbook/introduction/02_Data_Ingestion.ipynb+++ b/cookbook/introduction/02_Data_Ingestion.ipynb@@ -326,49 +326,50 @@},{"cell_type": "code",- "execution_count": 6,+ "execution_count": null,"metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Extracted Text: Hello WorldThis is a test.Link\n",- "Extracted Links: ['https://example.com/link']\n"- ]- },- {- "ename": "TypeError",- "evalue": "RobotsChecker.can_fetch() takes 2 positional arguments but 3 were given",- "output_type": "error",- "traceback": [- "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",- "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",- "Cell \u001b[1;32mIn[6], line 13\u001b[0m\n\u001b[0;32m 11\u001b[0m \u001b[38;5;66;03m# --- RobotsChecker ---\u001b[39;00m\n\u001b[0;32m 12\u001b[0m checker \u001b[38;5;241m=\u001b[39m RobotsChecker()\n\u001b[1;32m---> 13\u001b[0m can_fetch \u001b[38;5;241m=\u001b[39m \u001b[43mchecker\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcan_fetch\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mhttps://www.google.com/search\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mMyBot\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[0;32m 14\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCan fetch google search? \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcan_fetch\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 16\u001b[0m \u001b[38;5;66;03m# --- WebIngestor ---\u001b[39;00m\n",- "\u001b[1;31mTypeError\u001b[0m: RobotsChecker.can_fetch() takes 2 positional arguments but 3 were given"- ]- }- ],+ "outputs": [],"source": [+ "import requests\n","from semantica.ingest import WebIngestor, ContentExtractor, SitemapCrawler, RobotsChecker\n","\n","# --- ContentExtractor ---\n",+ "# Demonstrating extraction from a real, content-rich web page\n","extractor = ContentExtractor()\n",- "html_content = \"<html><body><h1>Hello World</h1><p>This is a test.</p><a href='/link'>Link</a></body></html>\"\n",+ "url = \"https://en.wikipedia.org/wiki/Artificial_intelligence\"\n",+ "try:\n",+ " # Wikipedia requires a User-Agent header\n",+ " headers = {'User-Agent': 'Semantica/1.0 (Education/Example)'}\n",+ " response = requests.get(url, headers=headers)\n",+ " html_content = response.text\n",+ " print(f\"Fetched content from {url}\")\n",+ "except Exception as e:\n",+ " print(f\"Failed to fetch {url}: {e}\")\n",+ " # Fallback content\n",+ " html_content = \"<html><body><h1>Hello World</h1><p>This is a test.</p><a href='/link'>Link</a></body></html>\"\n",+ "\n","text = extractor.extract_text(html_content)\n",- "links = extractor.extract_links(html_content, base_url=\"https://example.com\")\n",- "print(f\"Extracted Text: {text}\")\n",- "print(f\"Extracted Links: {links}\")\n",+ "links = extractor.extract_links(html_content, base_url=url)\n",+ "print(f\"Extracted Text (excerpt): {text[:200]}...\")\n",+ "print(f\"Found {len(links)} links\")\n","\n","# --- RobotsChecker ---\n",- "checker = RobotsChecker()\n",- "can_fetch = checker.can_fetch(\"https://www.google.com/search\", \"MyBot\")\n",- "print(f\"Can fetch google search? {can_fetch}\")\n",+ "# Initialize with user agent\n",+ "checker = RobotsChecker(user_agent=\"SemanticaBot\")\n",+ "# Check if we can fetch a specific page (e.g. Wikipedia Special pages are often restricted)\n",+ "check_url = \"https://en.wikipedia.org/wiki/Special:Search\"\n",+ "can_fetch = checker.can_fetch(check_url)\n",+ "print(f\"Can fetch {check_url}? {can_fetch}\")\n","\n","# --- WebIngestor ---\n",- "web_ingestor = WebIngestor(delay=1.0)\n",+ "# Configure WebIngestor to be polite but allow the demo to run\n",+ "web_ingestor = WebIngestor(\n",+ " delay=1.0,\n",+ " user_agent=\"Semantica/1.0 (Education/Example)\",\n",+ " respect_robots=False # Disabled for this demo to ensure Wikipedia access\n",+ ")\n","try:\n",- " web_content = web_ingestor.ingest_url(\"https://example.com\")\n",+ " web_content = web_ingestor.ingest_url(url)\n"," print(f\"Web Content Title: {web_content.title}\")\n","except Exception as e:\n"," print(f\"Web ingest failed: {e}\")\n",@@ -376,8 +377,10 @@"# --- SitemapCrawler ---\n","crawler = SitemapCrawler()\n","try:\n",- " urls = crawler.parse_sitemap(\"https://www.google.com/sitemap.xml\")\n",- " print(f\"Found {len(urls)} URLs in sitemap\")\n",+ " # Using FastAPI documentation sitemap as a clean, technical example\n",+ " sitemap_url = \"https://fastapi.tiangolo.com/sitemap.xml\"\n",+ " urls = crawler.parse_sitemap(sitemap_url)\n",+ " print(f\"Found {len(urls)} URLs in sitemap: {sitemap_url}\")\n","except Exception as e:\n"," print(f\"Sitemap crawl failed: {e}\")"]@@ -402,21 +405,27 @@"\n","# --- FeedIngestor ---\n","feed_ingestor = FeedIngestor()\n",+ "# Using Lilian Weng's AI Blog RSS feed as a reliable source\n",+ "feed_url = \"https://lilianweng.github.io/index.xml\"\n","try:\n",- " feed_data = feed_ingestor.ingest_feed(\"https://feeds.feedburner.com/oreilly/radar\")\n",+ " feed_data = feed_ingestor.ingest_feed(feed_url)\n"," print(f\"Feed Title: {feed_data.title}\")\n",+ " if feed_data.items:\n",+ " print(f\"Latest Post: {feed_data.items[0].title}\")\n","except Exception as e:\n"," print(f\"Feed ingest failed: {e}\")\n","\n","# --- FeedMonitor ---\n",- "def feed_callback(feed_data):\n",- " print(f\"Feed Updated: {feed_data.title} with {len(feed_data.items)} items\")\n",+ "def feed_callback(feed_url, new_items):\n",+ " print(f\"Feed Updated: {feed_url} with {len(new_items)} new items\")\n","\n","monitor = FeedMonitor(check_interval=5)\n","try:\n",- " monitor.monitor(\"https://feeds.feedburner.com/oreilly/radar\", callback=feed_callback)\n",+ " monitor.add_feed(feed_url)\n",+ " monitor.set_update_callback(feed_callback)\n",+ " monitor.start_monitoring()\n"," time.sleep(2) # Let it run briefly\n",- " monitor.stop()\n",+ " monitor.stop_monitoring()\n","except Exception as e:\n"," print(f\"Feed monitor failed: {e}\")\n"]@@ -441,11 +450,21 @@"stream_ingestor = StreamIngestor()\n","\n","# --- Kafka Processor ---\n",+ "# Note: This requires a running Kafka instance. We wrap it in try-except for the demo.\n","kafka_config = {\"bootstrap_servers\": [\"localhost:9092\"]}\n",- "kafka_processor = stream_ingestor.ingest_kafka(\"my-topic\", **kafka_config)\n",+ "try:\n",+ " kafka_processor = stream_ingestor.ingest_kafka(\"my-topic\", **kafka_config)\n",+ " print(\"Kafka processor initialized.\")\n",+ "except Exception as e:\n",+ " print(f\"Kafka ingest skipped (requires active broker): {e}\")\n","\n","# --- RabbitMQ Processor ---\n",- "rabbitmq_processor = stream_ingestor.ingest_rabbitmq(\"my-queue\", \"amqp://guest:guest@localhost:5672/\")\n",+ "# Note: This requires a running RabbitMQ instance. We wrap it in try-except for the demo.\n",+ "try:\n",+ " rabbitmq_processor = stream_ingestor.ingest_rabbitmq(\"my-queue\", \"amqp://guest:guest@localhost:5672/\")\n",+ " print(\"RabbitMQ processor initialized.\")\n",+ "except Exception as e:\n",+ " print(f\"RabbitMQ ingest skipped (requires active broker): {e}\")\n","\n","# --- Stream Monitor ---\n","monitor = stream_ingestor.monitor\n",@@ -470,27 +489,42 @@"outputs": [],"source": ["from semantica.ingest import RepoIngestor, CodeExtractor, GitAnalyzer\n",+ "from pathlib import Path\n",+ "import os\n","\n","# --- CodeExtractor ---\n","code_extractor = CodeExtractor()\n","py_code = \"class MyClass:\\n def my_method(self):\\n pass\"\n",- "structure = code_extractor.extract_structure(py_code, language=\"python\")\n",+ "# Note: Using internal method _extract_structure for demonstration on string input\n",+ "structure = code_extractor._extract_structure(py_code, language=\"python\")\n","print(f\"Classes: {structure.get('classes')}\")\n","print(f\"Functions: {structure.get('functions')}\")\n","\n","# --- RepoIngestor ---\n","repo_ingestor = RepoIngestor()\n","try:\n",- " repo_data = repo_ingestor.ingest_repository(\"https://github.com/Hawksight-AI/semantica.git\")\n",- " print(f\"Repo Name: {repo_data['name']}\")\n",+ " # Ingesting a public repository (requests) for reliable demonstration\n",+ " repo_data = repo_ingestor.ingest_repository(\"https://github.com/psf/requests.git\")\n",+ " # Accessing repo info from the returned dictionary\n",+ " repo_info = repo_data.get('repository_info', {})\n",+ " print(f\"Ingested Repo URL: {repo_info.get('url')}\")\n",+ " print(f\"Branches: {repo_info.get('branches')[:5]}...\") # Show first 5 branches\n",+ " repo_ingestor.cleanup() # Clean up temp files\n","except Exception as e:\n"," print(f\"Repo ingest failed: {e}\")\n","\n","# --- GitAnalyzer ---\n","try:\n",- " analyzer = GitAnalyzer(\".\")\n",- " stats = analyzer.get_statistics()\n",- " print(f\"Commits in current repo: {stats.get('total_commits', 'N/A')}\")\n",+ " # Initialize analyzer\n",+ " analyzer = GitAnalyzer()\n",+ " \n",+ " # Use current directory for demonstration\n",+ " current_path = Path(\".\")\n",+ " \n",+ " # Metrics calculation\n",+ " metrics = analyzer.calculate_metrics(current_path)\n",+ " print(f\"Total Files (recursive): {metrics.get('total_files')}\")\n",+ " print(f\"Total Lines: {metrics.get('total_lines')}\")\n","except Exception as e:\n"," print(f\"Git analysis failed: {e}\")\n"]@@ -511,21 +545,33 @@"outputs": [],"source": ["from semantica.ingest import EmailIngestor, AttachmentProcessor\n",+ "import tempfile\n",+ "import os\n",+ "\n",+ "# Create a temporary directory if not exists (though AttachmentProcessor handles its own temp dir)\n",+ "temp_dir = tempfile.gettempdir()\n","\n","# --- AttachmentProcessor ---\n","att_processor = AttachmentProcessor()\n","dummy_content = b\"PDF Content\"\n",- "saved_path = att_processor.save_attachment(dummy_content, \"doc.pdf\", temp_dir)\n",- "print(f\"Saved attachment to: {saved_path}\")\n",+ "# Use the correct method 'process_attachment' instead of 'save_attachment'\n",+ "# This method saves the file and returns metadata including the saved path\n",+ "att_info = att_processor.process_attachment(dummy_content, \"doc.pdf\", \"application/pdf\")\n",+ "print(f\"Saved attachment to: {att_info.get('saved_path')}\")\n","\n","# --- EmailIngestor ---\n","email_ingestor = EmailIngestor()\n","try:\n",+ " # Note: This will fail without real credentials, identifying it as an example\n",+ " # We wrap it in a try-block to allow the notebook to proceed\n"," email_ingestor.connect_imap(\"imap.gmail.com\", \"user\", \"pass\")\n"," emails = email_ingestor.ingest_mailbox(\"INBOX\", max_emails=5)\n"," print(f\"Fetched {len(emails)} emails\")\n","except Exception as e:\n",- " print(f\"Email ingest failed (Auth required): {e}\")\n"+ " print(f\"Email ingest skipped (Auth required): {e}\")\n",+ "\n",+ "# Cleanup any temp files creation by attachment processor\n",+ "att_processor.cleanup_attachments()\n"]},{@@ -545,9 +591,15 @@"source": ["from semantica.ingest import DBIngestor, DatabaseConnector\n","import sqlite3\n",+ "import os\n",+ "import tempfile\n","\n",- "# Setup SQLite DB\n",+ "# Setup SQLite DB in temp dir\n",+ "temp_dir = tempfile.gettempdir()\n","db_path = os.path.join(temp_dir, \"test.db\")\n",+ "if os.path.exists(db_path):\n",+ " os.remove(db_path)\n",+ "\n","conn = sqlite3.connect(db_path)\n","conn.execute(\"CREATE TABLE items (id INT, name TEXT)\")\n","conn.execute(\"INSERT INTO items VALUES (1, 'Item 1'), (2, 'Item 2')\")\n",@@ -556,16 +608,19 @@"\n","# --- DatabaseConnector ---\n","connector = DatabaseConnector()\n",- "engine = connector.create_engine(f\"sqlite:///{db_path}\")\n",- "print(f\"Connected to DB: {engine.name}\")\n",+ "# Fix: Use 'connect' method, not 'create_engine'\n",+ "engine = connector.connect(f\"sqlite:///{db_path}\")\n",+ "# engine.name for sqlite is 'sqlite'\n",+ "print(f\"Connected to DB Driver: {engine.name}\")\n",+ "connector.disconnect()\n","\n","# --- DBIngestor ---\n","db_ingestor = DBIngestor()\n",- "table_data = db_ingestor.ingest_database(f\"sqlite:///{db_path}\", table=\"items\")\n",+ "# Fix: Use 'export_table' to get a single TableData object, matching the variable usage\n",+ "table_data = db_ingestor.export_table(f\"sqlite:///{db_path}\", table_name=\"items\")\n","print(f\"Table: {table_data.table_name}\")\n","print(f\"Rows: {table_data.row_count}\")\n",- "for row in table_data.rows:\n",- " print(f\" - {row}\")\n"+ "print(f\"Data: {table_data.rows}\")\n"]},{@@ -584,22 +639,51 @@"outputs": [],"source": ["from semantica.ingest import MCPIngestor\n",+ "import logging\n","\n",+ "# --- MCPIngestor ---\n","mcp_ingestor = MCPIngestor()\n","\n",- "try:\n",- " # Connect\n",- " mcp_ingestor.connect(\"weather_server\", url=\"http://localhost:8000/mcp\")\n",+ "# Public Daemon MCP Server\n",+ "# Source: https://danielmiessler.com/p/daemon-mcp-server\n",+ "mcp_server_url = \"https://mcp.daemon.danielmiessler.com\"\n","\n",- " # Ingest Resources\n",- " resources = mcp_ingestor.ingest_resources(\"weather_server\")\n",- " print(f\"Resources: {len(resources)}\")\n",+ "try:\n",+ " print(f\"Connecting to public MCP server: {mcp_server_url}...\")\n",+ " \n",+ " # This server supports standard JSON-RPC over HTTP\n",+ " mcp_ingestor.connect(\"daemon_server\", url=mcp_server_url)\n",+ "\n",+ " # 1. List Available Tools\n",+ " print(\"\\n--- Available Tools ---\")\n",+ " tools = mcp_ingestor.list_available_tools(\"daemon_server\")\n",+ " for tool in tools:\n",+ " # Print first 5 tools to avoid clutter\n",+ " if tools.index(tool) < 5:\n",+ " print(f\"- {tool.name}: {tool.description or 'No description'}\")\n",+ " if len(tools) > 5:\n",+ " print(f\"... and {len(tools) - 5} more.\")\n",+ "\n",+ " # 2. Call Tool (get_about)\n",+ " tool_name = \"get_about\"\n",+ " print(f\"\\n--- Calling Tool '{tool_name}' ---\")\n",+ " \n",+ " result = mcp_ingestor.ingest_tool_output(\"daemon_server\", tool_name, {})\n",+ " \n",+ " # Parse content\n",+ " content = result.content.get('content', [])\n",+ " if content and isinstance(content, list):\n",+ " for block in content:\n",+ " if block.get('type') == 'text':\n",+ " # Truncate if too long\n",+ " text = block.get('text', '')\n",+ " preview = text[:200] + \"...\" if len(text) > 200 else text\n",+ " print(f\"Result: {preview}\")\n",+ " else:\n",+ " print(f\"Raw Result: {result.content}\")\n","\n",- " # Call Tool\n",- " result = mcp_ingestor.ingest_tool_output(\"weather_server\", \"get_forecast\", {\"city\": \"NYC\"})\n",- " print(f\"Tool Result: {result.content}\")\n","except Exception as e:\n",- " print(f\"MCP ingest failed (Server required): {e}\")\n"+ " print(f\"MCP Ingestion failed: {e}\")\n"]},{@@ -650,4 +734,4 @@},"nbformat": 4,"nbformat_minor": 2-}+}\ No newline at end of filediff --git a/semantica/ingest/repo_ingestor.py b/semantica/ingest/repo_ingestor.pyindex f7a6a9ba..3b12ed44 100644--- a/semantica/ingest/repo_ingestor.py+++ b/semantica/ingest/repo_ingestor.py@@ -307,7 +307,7 @@ class CodeExtractor:structure["classes"] = re.findall(class_pattern, content, re.MULTILINE)# Extract functions- func_pattern = r"^def\s+(\w+)"+ func_pattern = r"^\s*def\s+(\w+)"structure["functions"] = re.findall(func_pattern, content, re.MULTILINE)elif language in ["javascript", "typescript"]:@@ -641,7 +641,7 @@ class RepoIngestor:try:for commit in repo.iter_commits(*log_args):# Get files changed- files_changed = [item.a_path for item in commit.stats.files.keys()]+ files_changed = list(commit.stats.files.keys())# Calculate statsstats = commit.stats.total@@ -769,5 +769,28 @@ class RepoIngestor:def cleanup(self):"""Cleanup temporary repository files."""if self.temp_dir and os.path.exists(self.temp_dir):- shutil.rmtree(self.temp_dir)+ def onexc(func, path, exc_info):+ """+ Error handler for shutil.rmtree.++ If the error is due to an access error (read only file)+ it attempts to add write permission and then retries.++ If the error is for another reason it re-raises the error.++ Usage : shutil.rmtree(path, onerror=onexc)+ """+ import stat+ if not os.access(path, os.W_OK):+ # Is the error an access error ?+ os.chmod(path, stat.S_IWUSR)+ func(path)+ else:+ raise++ try:+ shutil.rmtree(self.temp_dir, onerror=onexc)+ except Exception as e:+ self.logger.warning(f"Failed to clean up temp dir {self.temp_dir}: {e}")+self.temp_dir = None