|
| 1 | +import os, re, glob, pathlib, yaml |
| 2 | +from typing import List |
| 3 | +from llama_index.core import VectorStoreIndex, StorageContext, Document, Settings |
| 4 | +from llama_index.core.node_parser import SimpleNodeParser |
| 5 | +from llama_index.embeddings.ollama import OllamaEmbedding |
| 6 | +from llama_index.llms.ollama import Ollama |
| 7 | +from llama_index.vector_stores.chroma import ChromaVectorStore |
| 8 | +import chromadb |
| 9 | + |
| 10 | +CONFIG = yaml.safe_load(open("config.yaml", "r")) |
| 11 | + |
| 12 | +PAGE_LINK = re.compile(r"\[\[([^\]]+)\]\]") # [[Page]] |
| 13 | +BLOCK_REF = re.compile(r"\(\(([a-zA-Z0-9_-]{6,})\)\)") # ((block-id)) |
| 14 | +TAG_HASH = re.compile(r"(?<!\w)#([A-Za-z0-9/_-]+)") # #tag |
| 15 | +TAG_PROP = re.compile(r"^tags::\s*(.+)$", re.MULTILINE) # tags:: a, b |
| 16 | + |
| 17 | +def normalize_logseq_links(text: str) -> str: |
| 18 | + text = PAGE_LINK.sub(lambda m: m.group(1), text) |
| 19 | + text = BLOCK_REF.sub(lambda m: f"[ref:{m.group(1)}]", text) |
| 20 | + return text |
| 21 | + |
| 22 | +def parse_tags(text: str) -> List[str]: |
| 23 | + tags = set() |
| 24 | + for m in TAG_HASH.finditer(text): |
| 25 | + tags.add(m.group(1)) |
| 26 | + for m in TAG_PROP.finditer(text): |
| 27 | + raw = [t.strip(" ,#") for t in m.group(1).split(",")] |
| 28 | + for t in raw: |
| 29 | + if t: |
| 30 | + tags.add(t) |
| 31 | + return sorted(tags) |
| 32 | + |
| 33 | +def page_title_from_path(path: str) -> str: |
| 34 | + name = pathlib.Path(path).stem |
| 35 | + return name.replace("_", "-") |
| 36 | + |
| 37 | +def collect_files(root: str, include_dirs: List[str], file_exts: List[str], exclude_globs: List[str]) -> List[str]: |
| 38 | + files = [] |
| 39 | + for rel in include_dirs: |
| 40 | + base = os.path.join(root, rel) |
| 41 | + for ext in file_exts: |
| 42 | + files.extend(glob.glob(os.path.join(base, f"**/*{ext}"), recursive=True)) |
| 43 | + excluded = set() |
| 44 | + for pat in exclude_globs: |
| 45 | + excluded.update(glob.glob(os.path.join(root, pat), recursive=True)) |
| 46 | + return [f for f in files if f not in excluded and os.path.isfile(f)] |
| 47 | + |
| 48 | +def load_documents(paths: List[str]) -> List[Document]: |
| 49 | + docs = [] |
| 50 | + for p in paths: |
| 51 | + try: |
| 52 | + txt = open(p, "r", encoding="utf-8").read() |
| 53 | + except Exception: |
| 54 | + continue |
| 55 | + |
| 56 | + clean = normalize_logseq_links(txt) |
| 57 | + |
| 58 | + # compute tags here so tags_csv is in scope |
| 59 | + tags_list = parse_tags(txt) |
| 60 | + tags_csv = ", ".join(tags_list) if tags_list else None |
| 61 | + |
| 62 | + title = page_title_from_path(p) |
| 63 | + meta = { |
| 64 | + "source": p, |
| 65 | + "title": title, |
| 66 | + "tags": tags_csv, # scalar (str/None), not a list |
| 67 | + "basename": os.path.basename(p), |
| 68 | + "dir": os.path.basename(os.path.dirname(p)), |
| 69 | + } |
| 70 | + docs.append(Document(text=clean, metadata=meta)) |
| 71 | + return docs |
| 72 | + |
| 73 | +def main(): |
| 74 | + root = CONFIG["logseq_root"] |
| 75 | + include_dirs = CONFIG["include_dirs"] |
| 76 | + file_exts = CONFIG["file_exts"] |
| 77 | + exclude = CONFIG["exclude_globs"] |
| 78 | + |
| 79 | + if not os.path.isdir(root): |
| 80 | + raise SystemExit(f"Logseq root does not exist: {root}\nEdit config.yaml to set logseq_root.") |
| 81 | + |
| 82 | + paths = collect_files(root, include_dirs, file_exts, exclude) |
| 83 | + print(f"Found {len(paths)} markdown files.") |
| 84 | + |
| 85 | + docs = load_documents(paths) |
| 86 | + print(f"Loaded {len(docs)} documents.") |
| 87 | + |
| 88 | + Settings.llm = Ollama(model=CONFIG["models"]["llm"], request_timeout=180) |
| 89 | + Settings.embed_model = OllamaEmbedding(model_name=CONFIG["models"]["embedding"]) |
| 90 | + |
| 91 | + parser = SimpleNodeParser.from_defaults( |
| 92 | + include_metadata=True, |
| 93 | + chunk_size=CONFIG["chunk"]["chunk_size"], |
| 94 | + chunk_overlap=CONFIG["chunk"]["chunk_overlap"] |
| 95 | + ) |
| 96 | + nodes = parser.get_nodes_from_documents(docs) |
| 97 | + print(f"Parsed into {len(nodes)} nodes.") |
| 98 | + |
| 99 | + chroma_path = CONFIG["storage"]["chroma_path"] |
| 100 | + os.makedirs(chroma_path, exist_ok=True) |
| 101 | + client = chromadb.PersistentClient(path=chroma_path) |
| 102 | + collection = client.get_or_create_collection("logseq_rag") |
| 103 | + |
| 104 | + vector_store = ChromaVectorStore(chroma_collection=collection) |
| 105 | + storage_ctx = StorageContext.from_defaults(vector_store=vector_store) |
| 106 | + |
| 107 | + _ = VectorStoreIndex(nodes, storage_context=storage_ctx) |
| 108 | + print("Index built and persisted to Chroma.") |
| 109 | + |
| 110 | +if __name__ == "__main__": |
| 111 | + main() |
0 commit comments