haiku.rag 0.12.1__py3-none-any.whl → 0.13.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of haiku.rag might be problematic. Click here for more details.

haiku/rag/migration.py DELETED
@@ -1,316 +0,0 @@
1
- import json
2
- import sqlite3
3
- import struct
4
- from pathlib import Path
5
- from uuid import uuid4
6
-
7
- from rich.console import Console
8
- from rich.progress import Progress, TaskID
9
-
10
- from haiku.rag.store.engine import Store
11
-
12
-
13
- def deserialize_sqlite_embedding(data: bytes) -> list[float]:
14
- """Deserialize sqlite-vec embedding from bytes."""
15
- if not data:
16
- return []
17
- # sqlite-vec stores embeddings as float32 arrays
18
- num_floats = len(data) // 4
19
- return list(struct.unpack(f"{num_floats}f", data))
20
-
21
-
22
- class SQLiteToLanceDBMigrator:
23
- """Migrates data from SQLite to LanceDB."""
24
-
25
- def __init__(self, sqlite_path: Path, lancedb_path: Path):
26
- self.sqlite_path = sqlite_path
27
- self.lancedb_path = lancedb_path
28
- self.console = Console()
29
-
30
- async def migrate(self) -> bool:
31
- """Perform the migration."""
32
- try:
33
- self.console.print(
34
- f"[blue]Starting migration from {self.sqlite_path} to {self.lancedb_path}[/blue]"
35
- )
36
-
37
- # Check if SQLite database exists
38
- if not self.sqlite_path.exists():
39
- self.console.print(
40
- f"[red]SQLite database not found: {self.sqlite_path}[/red]"
41
- )
42
- return False
43
-
44
- # Connect to SQLite database
45
- sqlite_conn = sqlite3.connect(self.sqlite_path)
46
- sqlite_conn.row_factory = sqlite3.Row
47
-
48
- # Load the sqlite-vec extension
49
- try:
50
- import sqlite_vec # type: ignore
51
-
52
- sqlite_conn.enable_load_extension(True)
53
- sqlite_vec.load(sqlite_conn)
54
- self.console.print("[cyan]Loaded sqlite-vec extension[/cyan]")
55
- except Exception as e:
56
- self.console.print(
57
- f"[yellow]Warning: Could not load sqlite-vec extension: {e}[/yellow]"
58
- )
59
- self.console.print(
60
- "[yellow]Install sqlite-vec with[/yellow]\n[green]uv pip install sqlite-vec [/green]"
61
- )
62
- exit(1)
63
-
64
- # Create LanceDB store
65
- lance_store = Store(self.lancedb_path, skip_validation=True)
66
-
67
- with Progress() as progress:
68
- # Migrate documents
69
- doc_task = progress.add_task(
70
- "[green]Migrating documents...", total=None
71
- )
72
- document_id_mapping = self._migrate_documents(
73
- sqlite_conn, lance_store, progress, doc_task
74
- )
75
-
76
- # Migrate chunks and embeddings
77
- chunk_task = progress.add_task(
78
- "[yellow]Migrating chunks and embeddings...", total=None
79
- )
80
- self._migrate_chunks(
81
- sqlite_conn, lance_store, progress, chunk_task, document_id_mapping
82
- )
83
-
84
- # Migrate settings
85
- settings_task = progress.add_task(
86
- "[blue]Migrating settings...", total=None
87
- )
88
- self._migrate_settings(
89
- sqlite_conn, lance_store, progress, settings_task
90
- )
91
-
92
- sqlite_conn.close()
93
-
94
- # Optimize and cleanup using centralized vacuum
95
- self.console.print("[cyan]Optimizing LanceDB...[/cyan]")
96
- try:
97
- await lance_store.vacuum()
98
- self.console.print("[green]✅ Optimization completed[/green]")
99
- except Exception as e:
100
- self.console.print(
101
- f"[yellow]Warning: Optimization failed: {e}[/yellow]"
102
- )
103
-
104
- lance_store.close()
105
-
106
- self.console.print("[green]✅ Migration completed successfully![/green]")
107
- self.console.print(
108
- f"[green]✅ Migrated {len(document_id_mapping)} documents[/green]"
109
- )
110
- return True
111
-
112
- except Exception as e:
113
- self.console.print(f"[red]❌ Migration failed: {e}[/red]")
114
- import traceback
115
-
116
- self.console.print(f"[red]{traceback.format_exc()}[/red]")
117
- return False
118
-
119
- def _migrate_documents(
120
- self,
121
- sqlite_conn: sqlite3.Connection,
122
- lance_store: Store,
123
- progress: Progress,
124
- task: TaskID,
125
- ) -> dict[int, str]:
126
- """Migrate documents from SQLite to LanceDB and return ID mapping."""
127
- cursor = sqlite_conn.cursor()
128
- cursor.execute(
129
- "SELECT id, content, uri, metadata, created_at, updated_at FROM documents ORDER BY id"
130
- )
131
-
132
- documents = []
133
- id_mapping = {} # Maps old integer ID to new UUID
134
-
135
- for row in cursor.fetchall():
136
- new_uuid = str(uuid4())
137
- id_mapping[row["id"]] = new_uuid
138
-
139
- doc_data = {
140
- "id": new_uuid,
141
- "content": row["content"],
142
- "uri": row["uri"],
143
- "metadata": json.loads(row["metadata"]) if row["metadata"] else {},
144
- "created_at": row["created_at"],
145
- "updated_at": row["updated_at"],
146
- }
147
- documents.append(doc_data)
148
-
149
- # Batch insert documents to LanceDB
150
- if documents:
151
- from haiku.rag.store.engine import DocumentRecord
152
-
153
- doc_records = [
154
- DocumentRecord(
155
- id=doc["id"],
156
- content=doc["content"],
157
- uri=doc["uri"],
158
- metadata=json.dumps(doc["metadata"]),
159
- created_at=doc["created_at"],
160
- updated_at=doc["updated_at"],
161
- )
162
- for doc in documents
163
- ]
164
- lance_store.documents_table.add(doc_records)
165
-
166
- progress.update(task, completed=len(documents), total=len(documents))
167
- return id_mapping
168
-
169
- def _migrate_chunks(
170
- self,
171
- sqlite_conn: sqlite3.Connection,
172
- lance_store: Store,
173
- progress: Progress,
174
- task: TaskID,
175
- document_id_mapping: dict[int, str],
176
- ):
177
- """Migrate chunks and embeddings from SQLite to LanceDB."""
178
- cursor = sqlite_conn.cursor()
179
-
180
- # Get chunks first
181
- cursor.execute("""
182
- SELECT id, document_id, content, metadata
183
- FROM chunks
184
- ORDER BY id
185
- """)
186
-
187
- chunks_data = cursor.fetchall()
188
-
189
- # Get embeddings using the sqlite-vec virtual table
190
- embeddings_map = {}
191
- try:
192
- # Use the virtual table to get embeddings properly
193
- cursor.execute("""
194
- SELECT chunk_id, embedding
195
- FROM chunk_embeddings
196
- """)
197
-
198
- for row in cursor.fetchall():
199
- chunk_id = row[0]
200
- embedding_blob = row[1]
201
- if embedding_blob and chunk_id not in embeddings_map:
202
- embeddings_map[chunk_id] = embedding_blob
203
-
204
- except sqlite3.OperationalError as e:
205
- self.console.print(
206
- f"[yellow]Warning: Could not extract embeddings from virtual table: {e}[/yellow]"
207
- )
208
-
209
- chunks = []
210
- for row in chunks_data:
211
- # Generate new UUID for chunk
212
- chunk_uuid = str(uuid4())
213
-
214
- # Map the old document_id to new UUID
215
- document_uuid = document_id_mapping.get(row["document_id"])
216
- if not document_uuid:
217
- self.console.print(
218
- f"[yellow]Warning: Document ID {row['document_id']} not found in mapping for chunk {row['id']}[/yellow]"
219
- )
220
- continue
221
-
222
- # Get embedding for this chunk
223
- embedding = []
224
- embedding_blob = embeddings_map.get(row["id"])
225
- if embedding_blob:
226
- try:
227
- embedding = deserialize_sqlite_embedding(embedding_blob)
228
- except Exception as e:
229
- self.console.print(
230
- f"[yellow]Warning: Failed to deserialize embedding for chunk {row['id']}: {e}[/yellow]"
231
- )
232
- # Generate a zero vector of the expected dimension
233
- embedding = [0.0] * lance_store.embedder._vector_dim
234
- else:
235
- # No embedding found, generate zero vector
236
- embedding = [0.0] * lance_store.embedder._vector_dim
237
-
238
- chunk_data = {
239
- "id": chunk_uuid,
240
- "document_id": document_uuid,
241
- "content": row["content"],
242
- "metadata": json.loads(row["metadata"]) if row["metadata"] else {},
243
- "vector": embedding,
244
- }
245
- chunks.append(chunk_data)
246
-
247
- # Batch insert chunks to LanceDB
248
- if chunks:
249
- chunk_records = [
250
- lance_store.ChunkRecord(
251
- id=chunk["id"],
252
- document_id=chunk["document_id"],
253
- content=chunk["content"],
254
- metadata=json.dumps(chunk["metadata"]),
255
- vector=chunk["vector"],
256
- )
257
- for chunk in chunks
258
- ]
259
- lance_store.chunks_table.add(chunk_records)
260
-
261
- progress.update(task, completed=len(chunks), total=len(chunks))
262
-
263
- def _migrate_settings(
264
- self,
265
- sqlite_conn: sqlite3.Connection,
266
- lance_store: Store,
267
- progress: Progress,
268
- task: TaskID,
269
- ):
270
- """Migrate settings from SQLite to LanceDB."""
271
- cursor = sqlite_conn.cursor()
272
-
273
- try:
274
- cursor.execute("SELECT id, settings FROM settings WHERE id = 1")
275
- row = cursor.fetchone()
276
-
277
- if row:
278
- settings_data = json.loads(row["settings"]) if row["settings"] else {}
279
-
280
- # Update the existing settings in LanceDB (use string ID)
281
- lance_store.settings_table.update(
282
- where="id = 'settings'",
283
- values={"settings": json.dumps(settings_data)},
284
- )
285
-
286
- progress.update(task, completed=1, total=1)
287
- else:
288
- progress.update(task, completed=0, total=0)
289
-
290
- except sqlite3.OperationalError:
291
- # Settings table doesn't exist in old SQLite database
292
- self.console.print(
293
- "[yellow]No settings table found in SQLite database[/yellow]"
294
- )
295
- progress.update(task, completed=0, total=0)
296
-
297
-
298
- async def migrate_sqlite_to_lancedb(
299
- sqlite_path: Path, lancedb_path: Path | None = None
300
- ) -> bool:
301
- """
302
- Migrate an existing SQLite database to LanceDB.
303
-
304
- Args:
305
- sqlite_path: Path to the existing SQLite database
306
- lancedb_path: Path for the new LanceDB database (optional, will auto-generate if not provided)
307
-
308
- Returns:
309
- True if migration was successful, False otherwise
310
- """
311
- if lancedb_path is None:
312
- # Auto-generate LanceDB path
313
- lancedb_path = sqlite_path.parent / (sqlite_path.stem + ".lancedb")
314
-
315
- migrator = SQLiteToLanceDBMigrator(sqlite_path, lancedb_path)
316
- return await migrator.migrate()