File size: 4,763 Bytes
a7d7463
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
"""Build markdown index for fast searching"""

import json
from pathlib import Path
from typing import Dict, List

sys.path.insert(0, str(Path(__file__).parent.parent))

from src.utils import MarkdownParser


class MarkdownIndexBuilder:
    """Build searchable index from markdown files"""

    def __init__(self, knowledge_dir: Path, output_file: Path):
        self.knowledge_dir = Path(knowledge_dir)
        self.output_file = Path(output_file)
        self.index: Dict = {
            "files": [],
            "headings": [],
            "code_blocks": [],
            "keywords": {},
        }

    def build(self):
        """Build index from all markdown files"""
        print("🔍 Building markdown index...")

        md_files = list(self.knowledge_dir.rglob("*.md"))
        print(f"Found {len(md_files)} markdown files")

        for md_file in md_files:
            self._index_file(md_file)

        self._save_index()
        print(f"✓ Index saved to {self.output_file}")

    def _index_file(self, file_path: Path):
        """Index a single markdown file"""
        parser = MarkdownParser.from_file(str(file_path))

        relative_path = file_path.relative_to(self.knowledge_dir.parent)
        file_info = {
            "path": str(relative_path),
            "name": file_path.name,
            "stem": file_path.stem,
        }

        headings = parser.extract_headings()
        for heading in headings:
            self.index["headings"].append(
                {
                    "file": str(relative_path),
                    "level": heading.level,
                    "text": heading.text,
                    "line": heading.line,
                }
            )

        code_blocks = parser.extract_code_blocks()
        for block in code_blocks:
            self.index["code_blocks"].append(
                {
                    "file": str(relative_path),
                    "language": block.language,
                    "preview": block.content[:100],
                    "line": block.start_line,
                }
            )

        plain_text = parser.convert_to_plain_text()
        for word in self._extract_keywords(plain_text):
            if word not in self.index["keywords"]:
                self.index["keywords"][word] = []
            self.index["keywords"][word].append(str(relative_path))

        self.index["files"].append(file_info)

        print(f"  ✓ Indexed: {file_path.name}")

    def _extract_keywords(self, text: str) -> List[str]:
        """Extract important keywords from text"""
        import re

        words = re.findall(r"\b[a-zA-Z_]{3,}\b", text.lower())

        common_words = {
            "the",
            "and",
            "for",
            "this",
            "that",
            "with",
            "from",
            "your",
        }
        keywords = [w for w in words if w not in common_words]

        from collections import Counter

        word_freq = Counter(keywords)
        return [w for w, _ in word_freq.most_common(100)]

    def _save_index(self):
        """Save index to JSON file"""
        self.output_file.parent.mkdir(parents=True, exist_ok=True)
        with open(self.output_file, "w", encoding="utf-8") as f:
            json.dump(self.index, f, indent=2, ensure_ascii=False)

    def search(self, query: str) -> List[Dict]:
        """Search the index"""
        with open(self.output_file, "r", encoding="utf-8") as f:
            index = json.load(f)

        results = []
        query_lower = query.lower()

        for heading in index["headings"]:
            if query_lower in heading["text"].lower():
                results.append(
                    {
                        "type": "heading",
                        "file": heading["file"],
                        "text": heading["text"],
                        "line": heading["line"],
                    }
                )

        for code in index["code_blocks"]:
            if query_lower in code["preview"].lower():
                results.append(
                    {
                        "type": "code",
                        "file": code["file"],
                        "language": code["language"],
                        "preview": code["preview"],
                        "line": code["line"],
                    }
                )

        return results


import sys

if __name__ == "__main__":
    base_dir = Path(__file__).parent.parent
    knowledge_dir = base_dir / "data" / "knowledge"
    output_file = base_dir / "data" / "cache" / "markdown_index.json"

    builder = MarkdownIndexBuilder(knowledge_dir, output_file)
    builder.build()

    print("\n📋 Search index built successfully!")
    print(f"📁 Output: {output_file}")