#!/usr/bin/env python3 """Obsidian Vault Sync & Vector Ingestion Utility. Recursively scans the Obsidian vault markdown files, processes changes using MD5 hashes, chunks content using hybrid markdown chunking, generates embeddings via Gemini, and upserts them to Supabase pgvector agent_memories table. """ import os import sys import json import hashlib import uuid import asyncio from typing import Dict, List, Any, Tuple from loguru import logger from sqlalchemy import text # Add parent directory to sys.path to allow imports from app parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) if parent_dir not in sys.path: sys.path.append(parent_dir) from dotenv import load_dotenv load_dotenv(encoding="utf-8") from app.database import AsyncSessionLocal from app.services.ai_service import generate_embedding def get_file_hash(filepath: str) -> str: """Compute MD5 hash of a file.""" hasher = hashlib.md5() with open(filepath, 'rb') as f: buf = f.read() hasher.update(buf) return hasher.hexdigest() def split_markdown_by_headings(content: str) -> List[Dict[str, Any]]: """Perform hybrid markdown chunking by splitting text on headings #, ##, ###.""" sections = [] current_headings = {1: "", 2: "", 3: ""} current_lines = [] lines = content.splitlines() for line in lines: stripped = line.strip() is_heading = False level = 0 heading_text = "" if stripped.startswith("# "): is_heading = True level = 1 heading_text = stripped[2:].strip() elif stripped.startswith("## "): is_heading = True level = 2 heading_text = stripped[3:].strip() elif stripped.startswith("### "): is_heading = True level = 3 heading_text = stripped[4:].strip() if is_heading: if current_lines: sections.append({ "headings": {k: v for k, v in current_headings.items()}, "text": "\n".join(current_lines) }) current_lines = [] # Update headings hierarchy if level == 1: current_headings[1] = heading_text current_headings[2] = "" current_headings[3] = "" elif level == 2: current_headings[2] = heading_text current_headings[3] = "" elif level == 3: current_headings[3] = heading_text current_lines.append(line) else: current_lines.append(line) if current_lines: sections.append({ "headings": {k: v for k, v in current_headings.items()}, "text": "\n".join(current_lines) }) return sections def chunk_text(text_content: str, max_chars: int = 1000, overlap: int = 150) -> List[str]: """Split text into smaller overlapping chunks if it exceeds max_chars.""" if overlap >= max_chars: raise ValueError("Overlap must be strictly less than max_chars") if len(text_content) <= max_chars: return [text_content] chunks = [] start = 0 while start < len(text_content): end = min(start + max_chars, len(text_content)) chunks.append(text_content[start:end]) if end == len(text_content): break start = end - overlap if start >= end: start = end - 1 return chunks def format_headings(headings_dict: Dict[int, str]) -> str: """Format the hierarchy of headings as a readable string.""" parts = [headings_dict[1], headings_dict[2], headings_dict[3]] non_empty = [p for p in parts if p] return " > ".join(non_empty) if non_empty else "Root" async def delete_file_chunks(db, rel_path: str): """Delete all chunks for a given file relative path from agent_memories.""" query = text(""" DELETE FROM agent_memories WHERE agent_id = 'obsidian-vault' AND task_context = :task_context """) await db.execute(query, {"task_context": rel_path}) async def process_file_sections(db, rel_path: str, sections: List[Dict[str, Any]]) -> bool: """Chunk, embed, and store already split markdown sections.""" chunks_inserted = 0 for section in sections: headings_str = format_headings(section["headings"]) raw_text = section["text"] # Split section if it exceeds 1000 characters sub_chunks = chunk_text(raw_text, max_chars=1000, overlap=150) for sub_chunk in sub_chunks: sub_chunk_stripped = sub_chunk.strip() if not sub_chunk_stripped: continue header = f"[File: {rel_path}] [Heading: {headings_str}]\n" full_chunk_text = header + sub_chunk_stripped # Generate Embedding Vector (768 dimensions) embedding = await generate_embedding(full_chunk_text) if sum(embedding) == 0.0: logger.warning(f"Embedding is all zeros for chunk in {rel_path} (AI disabled or API issue).") # Save to agent_memories query = text(""" INSERT INTO agent_memories (id, agent_id, content, embedding, task_context, success) VALUES (:id, :agent_id, :content, :embedding, :task_context, :success) """) await db.execute(query, { "id": str(uuid.uuid4()), "agent_id": "obsidian-vault", "content": full_chunk_text, "embedding": str(embedding), "task_context": rel_path, "success": True }) chunks_inserted += 1 logger.info(f"Processed {rel_path}: split into {chunks_inserted} chunks.") return True async def process_file(db, rel_path: str, full_path: str) -> bool: """Read, chunk, embed, and store a markdown file's sections.""" try: with open(full_path, "r", encoding="utf-8", errors="ignore") as f: content = f.read() except Exception as e: logger.error(f"Failed to read file {full_path}: {e}") return False try: sections = split_markdown_by_headings(content) except Exception as e: logger.error(f"Failed to split file {full_path}: {e}") return False return await process_file_sections(db, rel_path, sections) async def sync_obsidian(): """Main sync function.""" obsidian_vault_path = os.getenv("OBSIDIAN_VAULT_PATH") if not obsidian_vault_path: logger.error("OBSIDIAN_VAULT_PATH is not set in environment/env file.") sys.exit(1) if not os.path.exists(obsidian_vault_path) or not os.path.isdir(obsidian_vault_path): logger.error(f"Obsidian Vault path does not exist or is not a directory: {obsidian_vault_path}") sys.exit(1) cache_path = os.path.join(parent_dir, ".obsidian_sync_cache.json") # Load cache cache = {} if os.path.exists(cache_path): try: with open(cache_path, "r", encoding="utf-8") as f: cache = json.load(f) except Exception as e: logger.warning(f"Could not load cache file, starting fresh: {e}") # Scan all markdown files in vault current_hashes = {} for root, _, files in os.walk(obsidian_vault_path): for file in files: if file.endswith(".md"): full_path = os.path.join(root, file) rel_path = os.path.relpath(full_path, obsidian_vault_path).replace("\\", "/") try: current_hashes[rel_path] = (full_path, get_file_hash(full_path)) except Exception as e: logger.error(f"Failed to calculate hash for {full_path}: {e}") # Determine changes added_files = [path for path in current_hashes if path not in cache] modified_files = [path for path in current_hashes if path in cache and current_hashes[path][1] != cache[path]] deleted_files = [path for path in cache if path not in current_hashes] if not added_files and not modified_files and not deleted_files: logger.info("No changes detected in Obsidian Vault. Sync skipped.") return logger.info(f"Syncing Obsidian Vault: {len(added_files)} added, {len(modified_files)} modified, {len(deleted_files)} deleted.") db = AsyncSessionLocal() try: # Run DB modifications within a manual transaction block # 1. Process deletions for rel_path in deleted_files: logger.info(f"Deleting memory for: {rel_path}") await delete_file_chunks(db, rel_path) if rel_path in cache: del cache[rel_path] # 2. Process modified files for rel_path in modified_files: logger.info(f"Updating memory for: {rel_path}") full_path, file_hash = current_hashes[rel_path] try: with open(full_path, "r", encoding="utf-8", errors="ignore") as f: content = f.read() sections = split_markdown_by_headings(content) except Exception as e: logger.error(f"Failed to read or split modified file {full_path}: {e}") continue await delete_file_chunks(db, rel_path) success = await process_file_sections(db, rel_path, sections) if success: cache[rel_path] = file_hash # 3. Process added files for rel_path in added_files: logger.info(f"Inserting memory for: {rel_path}") full_path, file_hash = current_hashes[rel_path] success = await process_file(db, rel_path, full_path) if success: cache[rel_path] = file_hash await db.commit() # Save cache to disk after successful commit with open(cache_path, "w", encoding="utf-8") as f: json.dump(cache, f, indent=2) logger.success("Obsidian Vault sync completed and cache updated.") except Exception as e: await db.rollback() logger.error(f"Obsidian Vault sync failed, rolled back DB changes. Error: {e}") raise finally: await db.close() if __name__ == "__main__": asyncio.run(sync_obsidian())