File size: 5,699 Bytes
92cf271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
from __future__ import annotations

import argparse
import json
import sys
from dataclasses import asdict, dataclass
from pathlib import Path


BACKEND_DIR = Path(__file__).resolve().parents[1]
PROJECT_ROOT = BACKEND_DIR.parent
CHATBOT_SERVICE_DIR = PROJECT_ROOT / 'chatbot_service'

if str(CHATBOT_SERVICE_DIR) not in sys.path:
    sys.path.insert(0, str(CHATBOT_SERVICE_DIR))


from rag.document_loader import LoadedDocument, load_documents  # noqa: E402
from rag.embeddings import normalize_text  # noqa: E402


DEFAULT_PERSIST_DIR = BACKEND_DIR / 'data' / 'chroma_db'


@dataclass(slots=True)
class IndexedChunk:
    chunk_id: str
    source: str
    title: str
    category: str
    content: str


def _default_source_dirs() -> list[Path]:
    return [
        BACKEND_DIR / 'datasets' / 'legal',
        CHATBOT_SERVICE_DIR / 'data' / 'legal',
        CHATBOT_SERVICE_DIR / 'data' / 'medical',
    ]


def _origin_label(path: Path) -> str:
    try:
        return str(path.resolve().relative_to(PROJECT_ROOT)).replace('\\', '/')
    except ValueError:
        return str(path.resolve()).replace('\\', '/')


def _merged_category(origin: Path, document: LoadedDocument) -> str:
    base_category = origin.name.lower() or 'general'
    if document.category and document.category != 'general':
        return f'{base_category}/{document.category}'
    return base_category


def _chunk_document(document: LoadedDocument, *, origin_label: str, category: str) -> list[IndexedChunk]:
    paragraphs = [normalize_text(item) for item in document.text.split('\n') if normalize_text(item)]
    if not paragraphs:
        paragraphs = [document.text]

    chunks: list[IndexedChunk] = []
    current: list[str] = []
    current_length = 0
    chunk_index = 1
    source = f'{origin_label}/{document.source}'
    for paragraph in paragraphs:
        if current and current_length + len(paragraph) > 900:
            chunks.append(
                IndexedChunk(
                    chunk_id=f'{source}:{chunk_index}',
                    source=source,
                    title=document.title,
                    category=category,
                    content='\n'.join(current),
                )
            )
            chunk_index += 1
            current = []
            current_length = 0
        current.append(paragraph)
        current_length += len(paragraph)

    if current:
        chunks.append(
            IndexedChunk(
                chunk_id=f'{source}:{chunk_index}',
                source=source,
                title=document.title,
                category=category,
                content='\n'.join(current),
            )
        )
    return chunks


def _collect_chunks(source_dirs: list[Path]) -> tuple[list[IndexedChunk], dict[str, int]]:
    chunks: list[IndexedChunk] = []
    source_counts: dict[str, int] = {}
    for source_dir in source_dirs:
        if not source_dir.exists():
            continue
        origin_label = _origin_label(source_dir)
        documents = load_documents(source_dir)
        source_counts[origin_label] = len(documents)
        for document in documents:
            category = _merged_category(source_dir, document)
            chunks.extend(_chunk_document(document, origin_label=origin_label, category=category))
    return chunks, source_counts


def _write_index(persist_dir: Path, chunks: list[IndexedChunk], source_counts: dict[str, int]) -> None:
    persist_dir.mkdir(parents=True, exist_ok=True)
    index_path = persist_dir / 'simple_index.json'
    manifest_path = persist_dir / 'manifest.json'
    index_path.write_text(
        json.dumps([asdict(chunk) for chunk in chunks], ensure_ascii=False, indent=2),
        encoding='utf-8',
    )
    manifest_path.write_text(
        json.dumps(
            {
                'chunk_count': len(chunks),
                'category_count': len({chunk.category for chunk in chunks}),
                'sources': source_counts,
            },
            ensure_ascii=False,
            indent=2,
        ),
        encoding='utf-8',
    )


def main() -> None:
    parser = argparse.ArgumentParser(
        description='Build a lightweight local document index for backend legal and medical datasets.',
    )
    parser.add_argument(
        '--source-dir',
        action='append',
        type=Path,
        help='Optional source directory. Repeat to include multiple directories. Defaults to backend legal plus chatbot legal/medical data.',
    )
    parser.add_argument(
        '--persist-dir',
        type=Path,
        default=DEFAULT_PERSIST_DIR,
        help=f'Directory for the generated JSON index. Defaults to {DEFAULT_PERSIST_DIR}',
    )
    parser.add_argument(
        '--mirror-chatbot-index',
        action='store_true',
        help='Also copy the generated index into chatbot_service/data/chroma_db.',
    )
    args = parser.parse_args()

    source_dirs = args.source_dir or _default_source_dirs()
    chunks, source_counts = _collect_chunks(source_dirs)
    if not chunks:
        raise SystemExit(
            'No supported documents were found. Add PDFs, CSVs, JSON, TXT, or MD files to one of: '
            + ', '.join(str(path) for path in source_dirs)
        )

    _write_index(args.persist_dir, chunks, source_counts)
    print(
        f'Indexed {len(chunks)} chunks from {sum(source_counts.values())} documents '
        f'into {args.persist_dir / "simple_index.json"}'
    )

    if args.mirror_chatbot_index:
        mirror_dir = CHATBOT_SERVICE_DIR / 'data' / 'chroma_db'
        _write_index(mirror_dir, chunks, source_counts)
        print(f'Mirrored the index to {mirror_dir / "simple_index.json"}')


if __name__ == '__main__':
    main()