|
| 1 | +import glob |
1 | 2 | from pathlib import Path |
2 | 3 | import sqlite3 |
3 | 4 | from typing import Optional |
@@ -36,18 +37,62 @@ def _ensure_initialized(self): |
36 | 37 |
|
37 | 38 | self.ready = True |
38 | 39 |
|
39 | | - def add(self, path: str): |
| 40 | + def add(self, path: str, recursively: bool = False): |
40 | 41 | """Add the file content into the database""" |
41 | 42 | self._ensure_initialized() |
42 | 43 |
|
43 | 44 | if not Path(path).exists(): |
44 | | - raise FileNotFoundError(f"File {path} does not exist.") |
| 45 | + raise FileNotFoundError(f"{path} does not exist.") |
45 | 46 |
|
46 | | - # TODO: check the file extension |
47 | | - content = FileReader.parse_file(Path(path)) |
48 | | - # TODO: include metadata extraction and mdx options (see our docsearch) |
49 | | - document = Document(content=content, uri=path) |
| 47 | + files_to_process: list[Path] = [] |
| 48 | + path_obj = Path(path) |
| 49 | + |
| 50 | + if path_obj.is_file(): |
| 51 | + files_to_process.append(path_obj) |
| 52 | + elif path_obj.is_dir(): |
| 53 | + if recursively: |
| 54 | + files_to_process = list(path_obj.rglob("*")) |
| 55 | + else: |
| 56 | + files_to_process = list(path_obj.glob("*")) |
| 57 | + |
| 58 | + files_to_process = [ |
| 59 | + f |
| 60 | + for f in files_to_process |
| 61 | + if f.is_file() and FileReader.is_supported(f) |
| 62 | + ] |
| 63 | + |
| 64 | + for file_path in files_to_process: |
| 65 | + # TODO: check the file extension |
| 66 | + content = FileReader.parse_file(file_path) |
| 67 | + # TODO: include metadata extraction and mdx options (see our docsearch) |
| 68 | + document = Document(content=content, uri=str(file_path)) |
| 69 | + chunks = self._chunker.chunk(document.content) |
| 70 | + chunks = self._engine.generate_embedding(chunks) |
| 71 | + document.chunks = chunks |
| 72 | + |
| 73 | + self._repository.add_document(document) |
| 74 | + |
| 75 | + if self.settings.quantize_scan: |
| 76 | + self._engine.quantize() |
| 77 | + |
| 78 | + def add_text( |
| 79 | + self, text: str, uri: Optional[str] = None, metadata: dict = {} |
| 80 | + ) -> None: |
| 81 | + """Add a text content into the database""" |
| 82 | + self._ensure_initialized() |
| 83 | + |
| 84 | + document = Document(content=text, uri=uri, metadata=metadata) |
50 | 85 | chunks = self._chunker.chunk(document.content) |
| 86 | + chunks = self._engine.generate_embedding(chunks) |
51 | 87 | document.chunks = chunks |
52 | 88 |
|
53 | 89 | self._repository.add_document(document) |
| 90 | + |
| 91 | + if self.settings.quantize_scan: |
| 92 | + self._engine.quantize() |
| 93 | + |
| 94 | + def list_documents(self) -> list[Document]: |
| 95 | + """List all documents in the database""" |
| 96 | + self._ensure_initialized() |
| 97 | + |
| 98 | + return self._repository.list_documents() |
0 commit comments